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

GitHubSourceControlProvider.test.ts

1,314 lines44.1 KB

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