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

GitHubSourceControlProvider.test.ts

1,270 lines42.2 KB

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