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

GitHubSourceControlProvider.test.ts

1,164 lines38.6 KB

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