Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitHubSourceControlProvider.test.ts

967 lines32.2 KB

1import { assert, describe, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as Effect from "effect/Effect";
4import * as Fiber from "effect/Fiber";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Schema from "effect/Schema";
9import { ChildProcessSpawner } from "effect/process";
10import * as TestClock from "effect/testing/TestClock";
11​
12import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
13import * as VcsProcess from "../vcs/VcsProcess.ts";
14import * as GitHubApi from "./GitHubApi.ts";
15import * as GitHubCredentials from "./GitHubCredentials.ts";
16import { parseGitHubAuthStatus } from "./gitHubAuthStatus.ts";
17import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
18​
19const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
20​
21const processResult = (
22 stdout: string,
23 options?: {
24 readonly stderr?: string;
25 readonly exitCode?: ChildProcessSpawner.ExitCode;
26 },
27): VcsProcess.VcsProcessOutput => ({
28 exitCode: options?.exitCode ?? ChildProcessSpawner.ExitCode(0),
29 stdout,
30 stderr: options?.stderr ?? "",
31 stdoutTruncated: false,
32 stderrTruncated: false,
33});
34​
35const processOutput = (stdout: string, exitCode = 0): VcsProcess.VcsProcessOutput => ({
36 exitCode: ChildProcessSpawner.ExitCode(exitCode),
37 stdout,
38 stderr: "",
39 stdoutTruncated: false,
40 stderrTruncated: false,
41});
42​
43const remotesOutput = (...entries: ReadonlyArray<readonly [string, string]>) =>
44 entries
45 .flatMap(([name, url]) => [`${name}\t${url} (fetch)`, `${name}\t${url} (push)`])
46 .join("\n");
47​
48const restResponse = (body: unknown, status = 200): GitHubApi.GitHubRestResponse => ({
49 status,
50 headers: {},
51 body: body === undefined ? "" : encodeJson(body),
52 truncated: false,
53 invalidUtf8: false,
54});
55​
56const node = (number: number, headRefName: string, owner = "acme") => ({
57 number,
58 title: `PR ${number}`,
59 url: `https://github.com/acme/web/pull/${number}`,
60 baseRefName: "main",
61 headRefName,
62 state: "OPEN",
63 isCrossRepository: owner !== "acme",
64 updatedAt: "2026-01-02T00:00:00Z",
65 headRepository: { name: "web", nameWithOwner: `${owner}/web` },
66 headRepositoryOwner: { login: owner },
67});
68​
69/**
70 * The provider over a mocked GitHubApi, git driver and process. `remotes` is what
71 * `git remote -v` prints; `git` records every driver call.
72 */
73function harness(input: {
74 readonly remotes: string;
75 readonly api: Partial<GitHubApi.GitHubApi["Service"]>;
76 readonly localBranches?: ReadonlyArray<string>;
77 /** Fails the local branch listing, the first git read a checkout makes. */
78 readonly gitFailure?: unknown;
79}) {
80 const git: Array<readonly [string, unknown]> = [];
81 const record =
82 <A>(name: string, value: A) =>
83 (args: unknown) =>
84 Effect.sync(() => {
85 git.push([name, args]);
86 return value;
87 });
88 const driver = Layer.mock(GitVcsDriver.GitVcsDriver)({
89 execute: (args) =>
90 Effect.sync(() => {
91 git.push(["execute", args.args]);
92 return processOutput("");
93 }),
94 resolvePrimaryRemoteName: () => Effect.succeed("origin"),
95 readConfigValue: () => Effect.succeed("git@github.com:acme/web.git"),
96 ensureRemote: (args) =>
97 Effect.sync(() => {
98 git.push(["ensureRemote", args]);
99 return args.preferredName;
100 }),
101 fetchRemoteTrackingBranch: (args) => record("fetchRemoteTrackingBranch", undefined)(args),
102 setBranchUpstream: (args) => record("setBranchUpstream", undefined)(args),
103 switchRef: (args) => record("switchRef", { refName: args.refName })(args) as never,
104 listLocalBranchNames: () =>
105 input.gitFailure === undefined
106 ? Effect.succeed([...(input.localBranches ?? [])])
107 : Effect.fail(input.gitFailure as never),
108 resolveCommit: () => Effect.succeed({ commitSha: "abc123" }),
109 });
110 const process = Layer.mock(VcsProcess.VcsProcess)({
111 run: (args) =>
112 Effect.succeed(
113 args.args[0] === "remote" ? processOutput(input.remotes) : processOutput("", 1),
114 ),
115 });
116 const layer = Layer.mergeAll(
117 driver,
118 process,
119 Layer.mock(GitHubApi.GitHubApi)(input.api),
120 NodeServices.layer,
121 );
122 return { layer, git };
124​
125/** The provider context for a checkout whose remote is on `host`. */
126/** The provider over a mocked GitHubApi, for reads that never touch the checkout. */
127const makeProvider = (api: Partial<GitHubApi.GitHubApi["Service"]>) =>
128 GitHubSourceControlProvider.make.pipe(Effect.provide(harness({ remotes: "", api }).layer));
129​
130const githubContext = (host: string) => ({
131 provider: { kind: "github" as const, name: "GitHub", baseUrl: `https://${host}` },
132 remoteName: "origin",
133 remoteUrl: `git@${host}:acme/web.git`,
134});
135​
136describe("GitHubSourceControlProvider repository resolution", () => {
137 it.effect("reads the repository gh would pick from the remotes", () => {
138 const paths: string[] = [];
139 const { layer } = harness({
140 remotes: remotesOutput(
141 ["origin", "git@github.com:me/web.git"],
142 ["upstream", "https://github.com/acme/web.git"],
143 ),
144 api: {
145 rest: (input) =>
146 Effect.sync(() => {
147 paths.push(`${input.host} ${input.path}`);
148 return restResponse({
149 full_name: "acme/web",
150 html_url: "https://github.com/acme/web",
151 ssh_url: "git@github.com:acme/web.git",
152 default_branch: "trunk",
153 });
154 }),
155 },
156 });
157 return Effect.gen(function* () {
158 const gh = yield* GitHubSourceControlProvider.make;
159 assert.strictEqual(yield* gh.getDefaultBranch({ cwd: "/repo" }), "trunk");
160 assert.deepStrictEqual(paths, ["github.com repos/acme/web"]);
161 }).pipe(Effect.provide(layer));
162 });
163​
164 it.effect("reads an SSH alias remote through github.com", () => {
165 const hosts: string[] = [];
166 const { layer } = harness({
167 remotes: remotesOutput(["origin", "git@github:acme/web.git"]),
168 api: {
169 rest: (input) =>
170 Effect.sync(() => {
171 hosts.push(`${input.host} ${input.path}`);
172 return restResponse({
173 full_name: "acme/web",
174 html_url: "https://github.com/acme/web",
175 ssh_url: "git@github.com:acme/web.git",
176 default_branch: "main",
177 });
178 }),
179 },
180 });
181 return Effect.gen(function* () {
182 const gh = yield* GitHubSourceControlProvider.make;
183 yield* gh.getDefaultBranch({ cwd: "/repo" });
184 // A provider's host hint for the same alias (`github` here) resolves the same way.
185 yield* gh.getDefaultBranch({ cwd: "/repo", context: githubContext("github") });
186 assert.deepStrictEqual(hosts, ["github.com repos/acme/web", "github.com repos/acme/web"]);
187 }).pipe(Effect.provide(layer));
188 });
189​
190 it.effect("names a missing repository rather than a pull request", () => {
191 const { layer } = harness({
192 remotes: remotesOutput(["origin", "git@github.com:acme/gone.git"]),
193 api: {
194 rest: (input) =>
195 Effect.fail(
196 new GitHubApi.GitHubApiNotFoundError({ host: input.host, operation: input.operation }),
197 ),
198 },
199 });
200 return Effect.gen(function* () {
201 const gh = yield* GitHubSourceControlProvider.make;
202 const error = yield* gh.getDefaultBranch({ cwd: "/repo" }).pipe(Effect.flip);
203 assert.include(error.detail, "Repository not found");
204 }).pipe(Effect.provide(layer));
205 });
206​
207 it.effect("fails clearly when no remote is on GitHub", () => {
208 const { layer } = harness({
209 remotes: remotesOutput(["origin", "git@gitlab.com:a/b.git"]),
210 api: {},
211 });
212 return Effect.gen(function* () {
213 const gh = yield* GitHubSourceControlProvider.make;
214 const error = yield* gh.getDefaultBranch({ cwd: "/repo" }).pipe(Effect.flip);
215 assert.strictEqual(error._tag, "SourceControlProviderError");
216 assert.include(error.detail, "No GitHub repository");
217 }).pipe(Effect.provide(layer));
218 });
219});
220​
221describe("GitHubSourceControlProvider change request lookups by head", () => {
222 const remotes = remotesOutput(["origin", "git@github.com:acme/web.git"]);
223​
224 it.effect("reads a background sweep's staggered heads in one GraphQL document", () => {
225 const documents: Array<GitHubApi.GitHubGraphQlInput> = [];
226 const { layer } = harness({
227 remotes,
228 api: {
229 graphql: (input) =>
230 Effect.sync(() => {
231 documents.push(input);
232 return encodeJson({
233 data: {
234 repository: {
235 h0: { nodes: [{ ...node(7, "feature/a"), headRefOid: "a".repeat(40) }] },
236 h1: { nodes: [] },
237 },
238 },
239 });
240 }),
241 },
242 });
243 return Effect.gen(function* () {
244 const gh = yield* GitHubSourceControlProvider.make;
245 const lookup = (headSelector: string) =>
246 gh
247 .listChangeRequests({
248 cwd: "/repo",
249 headSelector,
250 state: "all",
251 limit: 100,
252 context: githubContext("github.com"),
253 })
254 .pipe(Effect.forkChild);
255 // Each branch's own git reads come first, so a sweep's lookups arrive spread out.
256 const firstLookup = yield* lookup("feature/a");
257 yield* TestClock.adjust("200 millis");
258 const secondLookup = yield* lookup("feature/b");
259 yield* TestClock.adjust("300 millis");
260 const first = yield* Fiber.join(firstLookup);
261 const second = yield* Fiber.join(secondLookup);
262 assert.deepStrictEqual(
263 first?.map((pr) => pr.number),
264 [7],
265 );
266 assert.strictEqual(first?.[0]?.headSha, "a".repeat(40));
267 assert.deepStrictEqual(second, []);
268 assert.strictEqual(documents.length, 1);
269 assert.include(documents[0]!.query, "headRefOid");
270 assert.deepStrictEqual(documents[0]!.variables, {
271 owner: "acme",
272 name: "web",
273 h0: "feature/a",
274 s0: ["OPEN", "CLOSED", "MERGED"],
275 h1: "feature/b",
276 s1: ["OPEN", "CLOSED", "MERGED"],
277 });
278 }).pipe(Effect.provide(layer));
279 });
280​
281 it.effect("caps a background document at twenty-five heads", () => {
282 const headCounts: Array<number> = [];
283 const { layer } = harness({
284 remotes,
285 api: {
286 graphql: (input) =>
287 Effect.sync(() => {
288 const heads = Object.keys(input.variables ?? {}).filter((key) => /^h\d+$/.test(key));
289 headCounts.push(heads.length);
290 return encodeJson({
291 data: { repository: Object.fromEntries(heads.map((key) => [key, { nodes: [] }])) },
292 });
293 }),
294 },
295 });
296 return Effect.gen(function* () {
297 const gh = yield* GitHubSourceControlProvider.make;
298 const lookups = yield* Effect.all(
299 Array.from({ length: 26 }, (_, index) =>
300 gh.listChangeRequests({
301 cwd: "/repo",
302 headSelector: `feature/${index}`,
303 state: "all",
304 limit: 100,
305 context: githubContext("github.com"),
306 }),
307 ),
308 { concurrency: "unbounded" },
309 ).pipe(Effect.forkChild);
310 yield* TestClock.adjust("500 millis");
311 yield* Fiber.join(lookups);
312 assert.deepStrictEqual(
313 headCounts.toSorted((a, b) => a - b),
314 [1, 25],
315 );
316 }).pipe(Effect.provide(layer));
317 });
318​
319 it.effect("matches an owner:branch selector on the head owner", () => {
320 const { layer } = harness({
321 remotes,
322 api: {
323 graphql: (input) =>
324 Effect.succeed(
325 encodeJson({
326 data: {
327 repository: {
328 h0: {
329 nodes:
330 input.variables?.h0 === "main"
331 ? [node(9, "main", "someone"), node(8, "main", "me"), node(7, "main", "me")]
332 : [],
333 },
334 },
335 },
336 }),
337 ),
338 },
339 });
340 return Effect.gen(function* () {
341 const gh = yield* GitHubSourceControlProvider.make;
342 const open = yield* gh
343 .listChangeRequests({ cwd: "/repo", headSelector: "me:main", state: "open", limit: 1 })
344 .pipe(Effect.forkChild);
345 yield* TestClock.adjust("50 millis");
346 assert.deepStrictEqual(
347 (yield* Fiber.join(open)).map((pr) => pr.number),
348 [8],
349 );
350 }).pipe(Effect.provide(layer));
351 });
352​
353 it.effect("maps API failures onto the errors callers handle", () => {
354 const { layer } = harness({
355 remotes,
356 api: {
357 graphql: (input) =>
358 Effect.fail(
359 input.variables?.h0 === "missing"
360 ? new GitHubCredentials.GitHubCliMissingError({ host: "github.com" })
361 : new GitHubApi.GitHubApiRateLimitError({
362 host: "github.com",
363 operation: "x",
364 retryAt: 123,
365 }),
366 ),
367 },
368 });
369 return Effect.gen(function* () {
370 const gh = yield* GitHubSourceControlProvider.make;
371 const read = (headSelector: string) =>
372 gh
373 .listChangeRequests({ cwd: "/repo", headSelector, state: "open", limit: 1 })
374 .pipe(Effect.flip, Effect.forkChild);
375 const missing = yield* read("missing");
376 yield* TestClock.adjust("500 millis");
377 assert.include((yield* Fiber.join(missing)).detail, "No GitHub credential on the server");
378 const limited = yield* read("limited");
379 yield* TestClock.adjust("500 millis");
380 const error = yield* Fiber.join(limited);
381 assert.include(error.detail, "rate limit exceeded");
382 assert.propertyVal(error.cause, "retryAt", 123);
383 }).pipe(Effect.provide(layer));
384 });
385});
386​
387describe("GitHubSourceControlProvider.getChangeRequest", () => {
388 it.effect("reads a pull request by number, and by URL on its own repository", () => {
389 const variables: Array<unknown> = [];
390 const { layer } = harness({
391 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
392 api: {
393 graphql: (input) =>
394 Effect.sync(() => {
395 variables.push(input.variables);
396 return encodeJson({ data: { repository: { pullRequest: node(42, "feature") } } });
397 }),
398 },
399 });
400 return Effect.gen(function* () {
401 const gh = yield* GitHubSourceControlProvider.make;
402 assert.strictEqual(
403 (yield* gh.getChangeRequest({ cwd: "/repo", reference: "#42" })).number,
404 42,
405 );
406 yield* gh.getChangeRequest({
407 cwd: "/repo",
408 reference: "https://github.com/other/thing/pull/42",
409 });
410 assert.deepStrictEqual(variables, [
411 { owner: "acme", name: "web", number: 42 },
412 { owner: "other", name: "thing", number: 42 },
413 ]);
414 }).pipe(Effect.provide(layer));
415 });
416​
417 it.effect("fails a missing pull request as not found", () => {
418 const { layer } = harness({
419 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
420 api: {
421 graphql: () => Effect.succeed(encodeJson({ data: { repository: { pullRequest: null } } })),
422 },
423 });
424 return Effect.gen(function* () {
425 const gh = yield* GitHubSourceControlProvider.make;
426 const error = yield* gh.getChangeRequest({ cwd: "/repo", reference: "7" }).pipe(Effect.flip);
427 assert.include(error.detail, "Pull request not found");
428 }).pipe(Effect.provide(layer));
429 });
430});
431​
432describe("GitHubSourceControlProvider writes", () => {
433 it.effect("creates a cross-repository pull request with an owner:branch head", () => {
434 const requests: Array<GitHubApi.GitHubRestInput> = [];
435 const { layer } = harness({
436 remotes: remotesOutput(
437 ["origin", "git@github.com:me/web.git"],
438 ["upstream", "git@github.com:acme/web.git"],
439 ),
440 api: {
441 rest: (input) =>
442 Effect.sync(() => {
443 requests.push(input);
444 return restResponse({ number: 1 }, 201);
445 }),
446 },
447 });
448 return Effect.gen(function* () {
449 const fs = yield* FileSystem.FileSystem;
450 const bodyFile = yield* fs.makeTempFileScoped({ suffix: ".md" });
451 yield* fs.writeFileString(bodyFile, "Body");
452 const gh = yield* GitHubSourceControlProvider.make;
453 yield* gh.createChangeRequest({
454 cwd: "/repo",
455 baseRefName: "main",
456 headSelector: "me:feature",
457 title: "Title",
458 bodyFile,
459 });
460 assert.strictEqual(requests[0]!.method, "POST");
461 assert.strictEqual(requests[0]!.path, "repos/acme/web/pulls");
462 // A user's own write, so the background's reserve is not held against it.
463 assert.strictEqual(requests[0]!.allowReserve, true);
464 assert.deepStrictEqual(requests[0]!.body, {
465 base: "main",
466 head: "me:feature",
467 title: "Title",
468 body: "Body",
469 maintainer_can_modify: true,
470 });
471 }).pipe(Effect.provide(Layer.merge(layer, NodeServices.layer)), Effect.scoped);
472 });
473​
474 it.effect("creates a repository under an organization the viewer is not", () => {
475 const requests: Array<string> = [];
476 const { layer } = harness({
477 remotes: "",
478 api: {
479 rest: (input) =>
480 Effect.sync(() => {
481 requests.push(`${input.method ?? "GET"} ${input.path}`);
482 return input.path === "user"
483 ? restResponse({ login: "me" })
484 : restResponse({
485 full_name: "acme/new",
486 html_url: "https://github.com/acme/new",
487 ssh_url: "git@github.com:acme/new.git",
488 });
489 }),
490 },
491 });
492 return Effect.gen(function* () {
493 const gh = yield* GitHubSourceControlProvider.make;
494 const urls = yield* gh.createRepository({
495 cwd: "/repo",
496 repository: "acme/new",
497 visibility: "private",
498 });
499 assert.deepStrictEqual(urls, {
500 nameWithOwner: "acme/new",
501 url: "https://github.com/acme/new",
502 sshUrl: "git@github.com:acme/new.git",
503 });
504 assert.deepStrictEqual(requests, ["GET user", "POST orgs/acme/repos"]);
505 }).pipe(Effect.provide(layer));
506 });
507});
508​
509describe("GitHubSourceControlProvider.checkoutChangeRequest", () => {
510 const repository = (fullName: string, defaultBranch = "main") =>
511 restResponse({
512 full_name: fullName,
513 html_url: `https://github.com/${fullName}`,
514 ssh_url: `git@github.com:${fullName}.git`,
515 default_branch: defaultBranch,
516 });
517​
518 it.effect("checks a same-repository pull request out from its head branch", () => {
519 const { layer, git } = harness({
520 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
521 api: {
522 graphql: () =>
523 Effect.succeed(
524 encodeJson({ data: { repository: { pullRequest: node(5, "feature/x") } } }),
525 ),
526 },
527 });
528 return Effect.gen(function* () {
529 const gh = yield* GitHubSourceControlProvider.make;
530 yield* gh.checkoutChangeRequest({ cwd: "/repo", reference: "5" });
531 assert.deepStrictEqual(git, [
532 [
533 "fetchRemoteTrackingBranch",
534 { cwd: "/repo", remoteName: "origin", remoteBranch: "feature/x" },
535 ],
536 ["execute", ["branch", "feature/x", "refs/remotes/origin/feature/x"]],
537 ["switchRef", { cwd: "/repo", refName: "feature/x" }],
538 [
539 "setBranchUpstream",
540 { cwd: "/repo", branch: "feature/x", remoteName: "origin", remoteBranch: "feature/x" },
541 ],
542 ]);
543 }).pipe(Effect.provide(layer));
544 });
545​
546 it.effect("refuses a fork checkout when the base's default branch cannot be read", () => {
547 const { layer, git } = harness({
548 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
549 localBranches: ["main"],
550 api: {
551 graphql: () =>
552 Effect.succeed(
553 encodeJson({ data: { repository: { pullRequest: node(6, "main", "someone") } } }),
554 ),
555 rest: () =>
556 Effect.fail(
557 new GitHubApi.GitHubApiRequestError({
558 host: "github.com",
559 operation: "x",
560 cause: "offline",
561 }),
562 ),
563 },
564 });
565 return Effect.gen(function* () {
566 const gh = yield* GitHubSourceControlProvider.make;
567 yield* Effect.flip(gh.checkoutChangeRequest({ cwd: "/repo", reference: "6", force: true }));
568 // Nothing touched the local branches: `main` must not be reset to the fork's commit.
569 assert.deepStrictEqual(git, []);
570 }).pipe(Effect.provide(layer));
571 });
572​
573 it.effect("adds a remote for a fork and names a default-branch head after its owner", () => {
574 const { layer, git } = harness({
575 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
576 localBranches: ["someone/main"],
577 api: {
578 graphql: () =>
579 Effect.succeed(
580 encodeJson({ data: { repository: { pullRequest: node(6, "main", "someone") } } }),
581 ),
582 rest: (input) =>
583 Effect.succeed(repository(input.path === "repos/acme/web" ? "acme/web" : "someone/web")),
584 },
585 });
586 return Effect.gen(function* () {
587 const gh = yield* GitHubSourceControlProvider.make;
588 yield* gh.checkoutChangeRequest({ cwd: "/repo", reference: "6", force: true });
589 assert.deepStrictEqual(git, [
590 [
591 "ensureRemote",
592 { cwd: "/repo", preferredName: "someone", url: "git@github.com:someone/web.git" },
593 ],
594 [
595 "fetchRemoteTrackingBranch",
596 { cwd: "/repo", remoteName: "someone", remoteBranch: "main" },
597 ],
598 ["switchRef", { cwd: "/repo", refName: "someone/main" }],
599 ["execute", ["reset", "--hard", "--quiet", "refs/remotes/someone/main"]],
600 [
601 "setBranchUpstream",
602 { cwd: "/repo", branch: "someone/main", remoteName: "someone", remoteBranch: "main" },
603 ],
604 ]);
605 }).pipe(Effect.provide(layer));
606 });
607​
608 it.effect("keeps git's own output out of what a failed checkout reports", () => {
609 const { layer } = harness({
610 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
611 gitFailure: new Error("fatal: /home/me/secret-path: permission denied"),
612 api: {
613 graphql: () =>
614 Effect.succeed(
615 encodeJson({ data: { repository: { pullRequest: node(5, "feature/x") } } }),
616 ),
617 },
618 });
619 return Effect.gen(function* () {
620 const gh = yield* GitHubSourceControlProvider.make;
621 const error = yield* gh
622 .checkoutChangeRequest({ cwd: "/repo", reference: "5" })
623 .pipe(Effect.flip);
624 assert.strictEqual(error.detail, "The pull request could not be checked out with git.");
625 assert.notInclude(error.message, "secret-path");
626 }).pipe(Effect.provide(layer));
627 });
628​
629 it("names the local branch the way gh pr checkout does", () => {
630 const name = (headRefName: string, isCrossRepository: boolean) =>
631 GitHubSourceControlProvider.pullRequestCheckoutBranchName({
632 headRefName,
633 headOwner: "someone",
634 isCrossRepository,
635 defaultBranch: "main",
636 });
637 assert.strictEqual(name("main", true), "someone/main");
638 assert.strictEqual(name("feature", true), "feature");
639 assert.strictEqual(name("main", false), "main");
640 });
641});
642​
643it("accepts active authenticated GitHub accounts when another account fails", () => {
644 const auth = GitHubSourceControlProvider.discovery.parseAuth(
645 processResult(
646 JSON.stringify({
647 hosts: {
648 "github.com": [
649 {
650 state: "success",
651 active: true,
652 host: "github.com",
653 login: "active-user",
654 tokenSource: "keyring",
655 gitProtocol: "ssh",
656 },
657 {
658 state: "error",
659 active: false,
660 host: "github.com",
661 login: "stale-user",
662 tokenSource: "keyring",
663 gitProtocol: "ssh",
664 error: "The token in keyring is invalid.",
665 },
666 ],
667 },
668 }),
669 ),
670 );
671​
672 assert.deepStrictEqual(
673 {
674 status: auth.status,
675 account: auth.account,
676 host: auth.host,
677 },
678 {
679 status: "authenticated",
680 account: Option.some("active-user"),
681 host: Option.some("github.com"),
682 },
683 );
684});
685​
686it("parses GitHub auth JSON from stdout when stderr has warnings", () => {
687 const auth = GitHubSourceControlProvider.discovery.parseAuth(
688 processResult(
689 JSON.stringify({
690 hosts: {
691 "github.com": [
692 {
693 state: "success",
694 active: true,
695 host: "github.com",
696 login: "active-user",
697 tokenSource: "keyring",
698 gitProtocol: "ssh",
699 },
700 ],
701 },
702 }),
703 { stderr: "warning: ignored diagnostic from gh\n" },
704 ),
705 );
706​
707 assert.deepStrictEqual(
708 {
709 status: auth.status,
710 account: auth.account,
711 host: auth.host,
712 },
713 {
714 status: "authenticated",
715 account: Option.some("active-user"),
716 host: Option.some("github.com"),
717 },
718 );
719});
720​
721it("parses GitHub auth status accounts by host and active state", () => {
722 assert.deepStrictEqual(
723 parseGitHubAuthStatus(
724 JSON.stringify({
725 hosts: {
726 "github.com": [
727 {
728 state: "success",
729 active: true,
730 host: "github.com",
731 login: "active-user",
732 tokenSource: "keyring",
733 gitProtocol: "ssh",
734 },
735 {
736 state: "error",
737 active: false,
738 host: "github.com",
739 login: "stale-user",
740 tokenSource: "keyring",
741 gitProtocol: "ssh",
742 },
743 ],
744 "github.example.test": [
745 {
746 state: "success",
747 active: false,
748 host: "github.example.test",
749 login: "enterprise-user",
750 tokenSource: "keyring",
751 gitProtocol: "ssh",
752 },
753 ],
754 },
755 }),
756 ).accounts,
757 [
758 {
759 host: "github.com",
760 account: "active-user",
761 authenticated: true,
762 active: true,
763 error: null,
764 environmentVariable: null,
765 },
766 {
767 host: "github.com",
768 account: "stale-user",
769 authenticated: false,
770 active: false,
771 error: null,
772 environmentVariable: null,
773 },
774 {
775 host: "github.example.test",
776 account: "enterprise-user",
777 authenticated: true,
778 active: false,
779 error: null,
780 environmentVariable: null,
781 },
782 ],
783 );
784});
785​
786it("reports unauthenticated when GitHub JSON has accounts but none are valid", () => {
787 const auth = GitHubSourceControlProvider.discovery.parseAuth(
788 processResult(
789 JSON.stringify({
790 hosts: {
791 "github.com": [
792 {
793 state: "error",
794 active: true,
795 host: "github.com",
796 login: "stale-user",
797 tokenSource: "keyring",
798 gitProtocol: "ssh",
799 error: "The token in keyring is invalid.",
800 },
801 ],
802 },
803 }),
804 ),
805 );
806​
807 assert.deepStrictEqual(
808 {
809 status: auth.status,
810 host: auth.host,
811 detail: auth.detail,
812 },
813 {
814 status: "unauthenticated",
815 host: Option.some("github.com"),
816 detail: Option.some("The token in keyring is invalid."),
817 },
818 );
819});
820​
821it("reports an update hint instead of unauthenticated when gh predates --json", () => {
822 const auth = GitHubSourceControlProvider.discovery.parseAuth(
823 processResult("", {
824 stderr: "unknown flag: --json\n\nUsage: gh auth status [flags]\n",
825 exitCode: ChildProcessSpawner.ExitCode(1),
826 }),
827 );
828​
829 assert.strictEqual(auth.status, "unknown");
830 assert.match(
831 Option.getOrElse(auth.detail, () => ""),
832 /2\.81\.0/,
833 );
834});
835​
836it.effect.each(["pull", "issues"])(
837 "resolves %s subjects on the linked host without using the checkout",
838 (kind) =>
839 Effect.gen(function* () {
840 const provider = yield* makeProvider({
841 rest: (input) => {
842 assert.strictEqual(input.host, "github.com");
843 assert.strictEqual(input.path, "repos/owner/repo/issues/42");
844 return Effect.succeed(
845 restResponse({ title: "Pairing expiry", body: "Preserve remote access", id: 1 }),
846 );
847 },
848 });
849 const lookup = provider.resolveLink?.({
850 cwd: "/unrelated",
851 url: new URL(`https://github.com/owner/repo/${kind}/42`),
852 });
853 assert.ok(lookup);
854 assert.deepStrictEqual(yield* lookup, {
855 title: "Pairing expiry",
856 body: "Preserve remote access",
857 });
858 assert.strictEqual(
859 provider.resolveLink?.({
860 cwd: "/unrelated",
861 url: new URL("https://github.com/owner/repo"),
862 }),
863 undefined,
864 );
865 }),
866);
867​
868it.effect.each(["read", "decode"] as const)(
869 "retains the %s failure without exposing its raw contents",
870 (stage) =>
871 Effect.gen(function* () {
872 const cause = new GitHubApi.GitHubApiResponseError({
873 host: "github.com",
874 operation: "resolveLink",
875 status: 500,
876 });
877 const provider = yield* makeProvider({
878 rest: () =>
879 stage === "read"
880 ? Effect.fail(cause)
881 : Effect.succeed({ ...restResponse(undefined), body: "private response text" }),
882 });
883 const lookup = provider.resolveLink?.({
884 cwd: "/repo",
885 url: new URL("https://github.com/owner/repo/issues/42"),
886 });
887 assert.ok(lookup);
888 const error = yield* Effect.flip(lookup);
889 assert.strictEqual(error.operation, stage === "read" ? "resolveLink" : "resolveLink.decode");
890 assert.strictEqual(error.detail, "The linked subject could not be read.");
891 assert.notInclude(error.message, "private response text");
892 if (stage === "read") assert.strictEqual(error.cause, cause);
893 else assert.propertyVal(error.cause, "_tag", "SchemaError");
894 }),
895);
896​
897const multiAccountStatus = (extra: ReadonlyArray<Record<string, unknown>> = []) =>
898 processResult(
899 JSON.stringify({
900 hosts: {
901 "github.com": [
902 { state: "success", active: true, host: "github.com", login: "personal" },
903 { state: "success", active: false, host: "github.com", login: "work" },
904 ...extra,
905 ],
906 "ghe.acme.test": [
907 { state: "error", active: true, host: "ghe.acme.test", login: "jm", error: "expired" },
908 ],
909 },
910 }),
911 );
912​
913it("reports every gh login and leads with the account Settings pin", () => {
914 const auth = GitHubSourceControlProvider.parseGitHubAuth(multiAccountStatus(), {
915 hosts: { "github.com": { account: "work", enabled: true } },
916 tokens: {},
917 });
918 assert.deepStrictEqual(auth.account, Option.some("work"));
919 assert.deepStrictEqual(auth.accounts, [
920 { host: "github.com", account: "personal", active: true, authenticated: true },
921 { host: "github.com", account: "work", active: false, authenticated: true },
922 { host: "ghe.acme.test", account: "jm", active: true, authenticated: false, error: "expired" },
923 ]);
924});
925​
926it("falls back to gh's active login when the pinned account is gone", () => {
927 const auth = GitHubSourceControlProvider.parseGitHubAuth(multiAccountStatus(), {
928 hosts: { "github.com": { account: "former-job", enabled: true } },
929 tokens: {},
930 });
931 assert.deepStrictEqual(auth.account, Option.some("personal"));
932});
933​
934it("reports unauthenticated when Settings turn off every signed-in host", () => {
935 const auth = GitHubSourceControlProvider.parseGitHubAuth(multiAccountStatus(), {
936 hosts: { "github.com": { enabled: false } },
937 tokens: {},
938 });
939 assert.strictEqual(auth.status, "unauthenticated");
940 assert.deepStrictEqual(
941 auth.detail,
942 Option.some("Every GitHub host gh is signed in to is turned off in Settings → Source Control."),
943 );
944});
945​
946it("names the environment token that overrides the Settings choice", () => {
947 const auth = GitHubSourceControlProvider.parseGitHubAuth(
948 multiAccountStatus([
949 {
950 state: "success",
951 active: false,
952 host: "github.com",
953 login: "bot",
954 tokenSource: "GH_TOKEN",
955 },
956 ]),
957 { hosts: { "github.com": { account: "work", enabled: true } }, tokens: {} },
958 );
959 assert.deepStrictEqual(auth.account, Option.some("bot"));
960 assert.deepStrictEqual(
961 auth.detail,
962 Option.some(
963 "Using GH_TOKEN from the server environment; it overrides the account chosen in Settings.",
964 ),
965 );
966 assert.strictEqual(auth.accounts?.[2]?.environmentVariable, "GH_TOKEN");
967});