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