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

GitHubSourceControlProvider.test.ts

1,100 lines36.1 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 gitFailure?: unknown;
175}) {
176 const git: Array<readonly [string, unknown]> = [];
177 const graphqlCalls: Array<GraphQlCall> = [];
178 const record =
179 <A>(name: string, value: A) =>
180 (args: unknown) =>
181 Effect.sync(() => {
182 git.push([name, args]);
183 return value;
184 });
185 const hostGit: Partial<SourceControlHost.SourceControlHost["Service"]["git"]> = {
186 execute: (args) =>
187 Effect.sync(() => {
188 git.push(["execute", args.args]);
189 return processOutput("");
190 }),
191 resolvePrimaryRemoteName: () => Effect.succeed("origin"),
192 readConfigValue: () => Effect.succeed("git@github.com:acme/web.git"),
193 ensureRemote: (args) =>
194 Effect.sync(() => {
195 git.push(["ensureRemote", args]);
196 return args.preferredName;
197 }),
198 fetchRemoteTrackingBranch: (args) => record("fetchRemoteTrackingBranch", undefined)(args),
199 setBranchUpstream: (args) => record("setBranchUpstream", undefined)(args),
200 switchRef: (args) => record("switchRef", { refName: args.refName })(args) as never,
201 listLocalBranchNames: () =>
202 input.gitFailure === undefined
203 ? Effect.succeed([...(input.localBranches ?? [])])
204 : Effect.fail(input.gitFailure as never),
205 resolveCommit: () => Effect.succeed({ commitSha: "abc123" }),
206 };
207 const host = TestSourceControlHost.layer({
208 git: hostGit,
209 process: {
210 run: (args) =>
211 Effect.succeed(
212 args.args[0] === "remote"
213 ? processOutput(input.remotes)
214 : processOutput(input.resolved ?? "", input.resolved ? 0 : 1),
215 ),
216 },
217 });
218 const graphql =
219 input.graphql ??
220 (() => {
221 throw new Error("Unexpected GraphQL read");
222 });
223 const policy = GitHubRequestPolicy.layer.pipe(
224 Layer.provide(
225 Layer.mergeAll(
226 Layer.succeed(GitHubCredentials.GitHubCredentials, {
227 get:
228 input.credential ??
229 ((host) =>
230 Effect.succeed({
231 host,
232 token: Redacted.make("token"),
233 source: "gh" as const,
234 fingerprint: `${host}:token`,
235 })),
236 invalidate: () => Effect.void,
237 }),
238 GitHubQuota.layer,
239 SourceControlRateLimit.layer,
240 ),
241 ),
242 );
243 const layer = Layer.mergeAll(
244 host,
245 Layer.mock(GitHubRest.GitHubRest)(input.api ?? {}),
246 policy,
247 Layer.succeed(HttpClient.HttpClient, graphQlHttp(graphql, graphqlCalls)),
248 NodeServices.layer,
249 );
250 return { layer, git, graphqlCalls };
252​
253/** The provider context for a checkout whose remote is on `host`. */
254/** The provider over a mocked GitHubRest, for reads that never touch the checkout. */
255const makeProvider = (api: Partial<GitHubRest.GitHubRest["Service"]>) =>
256 GitHubSourceControlProvider.make.pipe(Effect.provide(harness({ remotes: "", api }).layer));
257​
258const githubContext = (host: string) => ({
259 provider: {
260 kind: SourceControlProviderKind.make("github"),
261 name: "GitHub",
262 baseUrl: `https://${host}`,
263 },
264 remoteName: "origin",
265 remoteUrl: `git@${host}:acme/web.git`,
266});
267​
268describe("GitHubSourceControlProvider repository resolution", () => {
269 it.effect("reads the repository gh would pick from the remotes", () => {
270 const paths: string[] = [];
271 const { layer } = harness({
272 remotes: remotesOutput(
273 ["origin", "git@github.com:me/web.git"],
274 ["upstream", "https://github.com/acme/web.git"],
275 ),
276 api: {
277 rest: (input) =>
278 Effect.sync(() => {
279 paths.push(`${input.host} ${input.path}`);
280 return restResponse({
281 full_name: "acme/web",
282 html_url: "https://github.com/acme/web",
283 ssh_url: "git@github.com:acme/web.git",
284 default_branch: "trunk",
285 });
286 }),
287 },
288 });
289 return Effect.gen(function* () {
290 const gh = yield* GitHubSourceControlProvider.make;
291 assert.strictEqual(yield* gh.getDefaultBranch({ cwd: "/repo" }), "trunk");
292 assert.deepStrictEqual(paths, ["github.com repos/acme/web"]);
293 }).pipe(Effect.provide(layer));
294 });
295​
296 it.effect("reads an SSH alias remote through github.com", () => {
297 const hosts: string[] = [];
298 const { layer } = harness({
299 remotes: remotesOutput(["origin", "git@github:acme/web.git"]),
300 api: {
301 rest: (input) =>
302 Effect.sync(() => {
303 hosts.push(`${input.host} ${input.path}`);
304 return restResponse({
305 full_name: "acme/web",
306 html_url: "https://github.com/acme/web",
307 ssh_url: "git@github.com:acme/web.git",
308 default_branch: "main",
309 });
310 }),
311 },
312 });
313 return Effect.gen(function* () {
314 const gh = yield* GitHubSourceControlProvider.make;
315 yield* gh.getDefaultBranch({ cwd: "/repo" });
316 yield* gh.getDefaultBranch({ cwd: "/repo", context: githubContext("github") });
317 assert.deepStrictEqual(hosts, ["github.com repos/acme/web", "github.com repos/acme/web"]);
318 }).pipe(Effect.provide(layer));
319 });
320});
321​
322describe("GitHubSourceControlProvider change request lookups by head", () => {
323 const remotes = remotesOutput(["origin", "git@github.com:acme/web.git"]);
324​
325 it.effect("matches an owner:branch selector on the head owner", () => {
326 const { layer } = harness({
327 remotes,
328 graphql: (lookup) => ({
329 pullRequests: {
330 nodes:
331 lookup.head === "main"
332 ? [node(9, "main", "someone"), node(8, "main", "me"), node(7, "main", "me")]
333 : [],
334 },
335 }),
336 });
337 return Effect.gen(function* () {
338 const gh = yield* GitHubSourceControlProvider.make;
339 const open = yield* gh
340 .listChangeRequests({ cwd: "/repo", headSelector: "me:main", state: "open", limit: 1 })
341 .pipe(Effect.forkChild);
342 yield* TestClock.adjust("50 millis");
343 assert.deepStrictEqual(
344 (yield* Fiber.join(open)).map((pr) => pr.number),
345 [8],
346 );
347 }).pipe(Effect.provide(layer));
348 });
349​
350 it.effect("maps API failures onto the errors callers handle", () => {
351 let signedIn = false;
352 const { layer } = harness({
353 remotes,
354 credential: (host) =>
355 signedIn
356 ? Effect.succeed({
357 host,
358 token: Redacted.make("token"),
359 source: "gh" as const,
360 fingerprint: "fp",
361 })
362 : Effect.fail(new GitHubCredentials.GitHubCliMissingError({ host })),
363 graphql: () =>
364 new Response(encodeJson({ message: "API rate limit exceeded" }), {
365 status: 403,
366 headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": "123" },
367 }),
368 });
369 return Effect.gen(function* () {
370 const gh = yield* GitHubSourceControlProvider.make;
371 const read = (headSelector: string) =>
372 gh
373 .listChangeRequests({ cwd: "/repo", headSelector, state: "open", limit: 1 })
374 .pipe(Effect.flip, Effect.forkChild);
375 const missing = yield* read("missing");
376 yield* TestClock.adjust("500 millis");
377 assert.include((yield* Fiber.join(missing)).detail, "No GitHub credential on the server");
378 signedIn = true;
379 const limited = yield* read("limited");
380 yield* TestClock.adjust("500 millis");
381 const error = yield* Fiber.join(limited);
382 assert.include(error.detail, "rate limit exceeded");
383 assert.propertyVal(error.cause, "retryAt", 123_000);
384 }).pipe(Effect.provide(layer));
385 });
386});
387​
388describe("GitHubSourceControlProvider.getChangeRequest", () => {
389 it.effect("reads a pull request by number, and by URL on its own repository", () => {
390 const { layer, graphqlCalls } = harness({
391 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
392 graphql: () => ({ pullRequest: node(42, "feature") }),
393 });
394 return Effect.gen(function* () {
395 const gh = yield* GitHubSourceControlProvider.make;
396 assert.strictEqual(
397 (yield* gh.getChangeRequest({ cwd: "/repo", reference: "#42" })).number,
398 42,
399 );
400 yield* gh.getChangeRequest({
401 cwd: "/repo",
402 reference: "https://github.com/other/thing/pull/42",
403 });
404 assert.deepStrictEqual(
405 graphqlCalls.flatMap((call) => call.lookups),
406 [
407 { owner: "acme", name: "web", number: 42 },
408 { owner: "other", name: "thing", number: 42 },
409 ],
410 );
411 }).pipe(Effect.provide(layer));
412 });
413});
414​
415describe("GitHubSourceControlProvider writes", () => {
416 it.effect("creates a cross-repository pull request with an owner:branch head", () => {
417 const requests: Array<GitHubRest.GitHubRestInput> = [];
418 const { layer } = harness({
419 remotes: remotesOutput(
420 ["origin", "git@github.com:me/web.git"],
421 ["upstream", "git@github.com:acme/web.git"],
422 ),
423 api: {
424 rest: (input) =>
425 Effect.sync(() => {
426 requests.push(input);
427 return restResponse({ number: 1 }, 201);
428 }),
429 },
430 });
431 return Effect.gen(function* () {
432 const fs = yield* FileSystem.FileSystem;
433 const bodyFile = yield* fs.makeTempFileScoped({ suffix: ".md" });
434 yield* fs.writeFileString(bodyFile, "Body");
435 const gh = yield* GitHubSourceControlProvider.make;
436 yield* gh.createChangeRequest({
437 cwd: "/repo",
438 baseRefName: "main",
439 headSelector: "me:feature",
440 title: "Title",
441 bodyFile,
442 });
443 assert.strictEqual(requests[0]!.method, "POST");
444 assert.strictEqual(requests[0]!.path, "repos/acme/web/pulls");
445 assert.strictEqual(requests[0]!.allowReserve, true);
446 assert.deepStrictEqual(requests[0]!.body, {
447 base: "main",
448 head: "me:feature",
449 title: "Title",
450 body: "Body",
451 maintainer_can_modify: true,
452 });
453 }).pipe(Effect.provide(Layer.merge(layer, NodeServices.layer)), Effect.scoped);
454 });
455​
456 it.effect("creates a repository under an organization the viewer is not", () => {
457 const requests: Array<string> = [];
458 const { layer } = harness({
459 remotes: "",
460 api: {
461 rest: (input) =>
462 Effect.sync(() => {
463 requests.push(`${input.method ?? "GET"} ${input.path}`);
464 return input.path === "user"
465 ? restResponse({ login: "me" })
466 : restResponse({
467 full_name: "acme/new",
468 html_url: "https://github.com/acme/new",
469 ssh_url: "git@github.com:acme/new.git",
470 });
471 }),
472 },
473 });
474 return Effect.gen(function* () {
475 const gh = yield* GitHubSourceControlProvider.make;
476 const urls = yield* gh.createRepository({
477 cwd: "/repo",
478 repository: "acme/new",
479 visibility: "private",
480 });
481 assert.deepStrictEqual(urls, {
482 nameWithOwner: "acme/new",
483 url: "https://github.com/acme/new",
484 sshUrl: "git@github.com:acme/new.git",
485 });
486 assert.deepStrictEqual(requests, ["GET user", "POST orgs/acme/repos"]);
487 }).pipe(Effect.provide(layer));
488 });
489​
490 it.effect("looks up a bare repository name under the signed-in account on that host", () => {
491 const requests: Array<string> = [];
492 return Effect.gen(function* () {
493 const gh = yield* makeProvider({
494 rest: (input) =>
495 Effect.sync(() => {
496 requests.push(`${input.host} ${input.method ?? "GET"} ${input.path}`);
497 return input.path === "user"
498 ? restResponse({ login: "me" })
499 : restResponse({
500 full_name: "me/notes",
501 html_url: `https://${input.host}/me/notes`,
502 ssh_url: `git@${input.host}:me/notes.git`,
503 });
504 }),
505 });
506​
507 const urls = yield* gh.getRepositoryCloneUrls({
508 cwd: "/repo",
509 context: githubContext("code.example.test"),
510 repository: " notes.git ",
511 });
512​
513 assert.deepStrictEqual(urls, {
514 nameWithOwner: "me/notes",
515 url: "https://code.example.test/me/notes",
516 sshUrl: "git@code.example.test:me/notes.git",
517 });
518 assert.deepStrictEqual(requests, [
519 "code.example.test GET user",
520 "code.example.test GET repos/me/notes",
521 ]);
522 for (const repository of ["me/", "/notes", "a/b/c/d", "", "two words"]) {
523 const error = yield* Effect.flip(gh.getRepositoryCloneUrls({ cwd: "/repo", repository }));
524 assert.include(error.message, "Repositories are named owner/name.");
525 }
526 assert.strictEqual(requests.length, 2);
527 });
528 });
529});
530​
531describe("GitHubSourceControlProvider.checkoutChangeRequest", () => {
532 it.effect("refuses a fork checkout when the base's default branch cannot be read", () => {
533 const { layer, git } = harness({
534 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
535 localBranches: ["main"],
536 graphql: () => ({ pullRequest: node(6, "main", "someone") }),
537 api: {
538 rest: () =>
539 Effect.fail(
540 new GitHubRequestPolicy.GitHubApiRequestError({
541 host: "github.com",
542 operation: "x",
543 cause: "offline",
544 }),
545 ),
546 },
547 });
548 return Effect.gen(function* () {
549 const gh = yield* GitHubSourceControlProvider.make;
550 yield* Effect.flip(gh.checkoutChangeRequest({ cwd: "/repo", reference: "6", force: true }));
551 assert.deepStrictEqual(git, []);
552 }).pipe(Effect.provide(layer));
553 });
554​
555 it.effect("keeps git's own output out of what a failed checkout reports", () => {
556 const { layer } = harness({
557 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
558 gitFailure: new Error("fatal: /home/me/secret-path: permission denied"),
559 graphql: () => ({ pullRequest: node(5, "feature/x") }),
560 });
561 return Effect.gen(function* () {
562 const gh = yield* GitHubSourceControlProvider.make;
563 const error = yield* gh
564 .checkoutChangeRequest({ cwd: "/repo", reference: "5" })
565 .pipe(Effect.flip);
566 assert.strictEqual(error.detail, "The pull request could not be checked out with git.");
567 assert.notInclude(error.message, "secret-path");
568 }).pipe(Effect.provide(layer));
569 });
570​
571 it("names the local branch the way gh pr checkout does", () => {
572 const name = (headRefName: string, isCrossRepository: boolean) =>
573 GitHubSourceControlProvider.pullRequestCheckoutBranchName({
574 headRefName,
575 headOwner: "someone",
576 isCrossRepository,
577 defaultBranch: "main",
578 });
579 assert.strictEqual(name("main", true), "someone/main");
580 assert.strictEqual(name("feature", true), "feature");
581 assert.strictEqual(name("main", false), "main");
582 });
583});
584​
585it("accepts active authenticated GitHub accounts when another account fails", () => {
586 const auth = GitHubSourceControlProvider.discovery.parseAuth(
587 processResult(
588 JSON.stringify({
589 hosts: {
590 "github.com": [
591 {
592 state: "success",
593 active: true,
594 host: "github.com",
595 login: "active-user",
596 tokenSource: "keyring",
597 gitProtocol: "ssh",
598 },
599 {
600 state: "error",
601 active: false,
602 host: "github.com",
603 login: "stale-user",
604 tokenSource: "keyring",
605 gitProtocol: "ssh",
606 error: "The token in keyring is invalid.",
607 },
608 ],
609 },
610 }),
611 ),
612 );
613​
614 assert.deepStrictEqual(
615 {
616 status: auth.status,
617 account: auth.account,
618 host: auth.host,
619 },
620 {
621 status: "authenticated",
622 account: Option.some("active-user"),
623 host: Option.some("github.com"),
624 },
625 );
626});
627​
628it("parses GitHub auth JSON from stdout when stderr has warnings", () => {
629 const auth = GitHubSourceControlProvider.discovery.parseAuth(
630 processResult(
631 JSON.stringify({
632 hosts: {
633 "github.com": [
634 {
635 state: "success",
636 active: true,
637 host: "github.com",
638 login: "active-user",
639 tokenSource: "keyring",
640 gitProtocol: "ssh",
641 },
642 ],
643 },
644 }),
645 { stderr: "warning: ignored diagnostic from gh\n" },
646 ),
647 );
648​
649 assert.deepStrictEqual(
650 {
651 status: auth.status,
652 account: auth.account,
653 host: auth.host,
654 },
655 {
656 status: "authenticated",
657 account: Option.some("active-user"),
658 host: Option.some("github.com"),
659 },
660 );
661});
662​
663it("parses GitHub auth status accounts by host and active state", () => {
664 assert.deepStrictEqual(
665 parseGitHubAuthStatus(
666 JSON.stringify({
667 hosts: {
668 "github.com": [
669 {
670 state: "success",
671 active: true,
672 host: "github.com",
673 login: "active-user",
674 tokenSource: "keyring",
675 gitProtocol: "ssh",
676 },
677 {
678 state: "error",
679 active: false,
680 host: "github.com",
681 login: "stale-user",
682 tokenSource: "keyring",
683 gitProtocol: "ssh",
684 },
685 ],
686 "github.example.test": [
687 {
688 state: "success",
689 active: false,
690 host: "github.example.test",
691 login: "enterprise-user",
692 tokenSource: "keyring",
693 gitProtocol: "ssh",
694 },
695 ],
696 },
697 }),
698 ).accounts,
699 [
700 {
701 host: "github.com",
702 account: "active-user",
703 authenticated: true,
704 active: true,
705 error: null,
706 environmentVariable: null,
707 },
708 {
709 host: "github.com",
710 account: "stale-user",
711 authenticated: false,
712 active: false,
713 error: null,
714 environmentVariable: null,
715 },
716 {
717 host: "github.example.test",
718 account: "enterprise-user",
719 authenticated: true,
720 active: false,
721 error: null,
722 environmentVariable: null,
723 },
724 ],
725 );
726});
727​
728it("reports unauthenticated when GitHub JSON has accounts but none are valid", () => {
729 const auth = GitHubSourceControlProvider.discovery.parseAuth(
730 processResult(
731 JSON.stringify({
732 hosts: {
733 "github.com": [
734 {
735 state: "error",
736 active: true,
737 host: "github.com",
738 login: "stale-user",
739 tokenSource: "keyring",
740 gitProtocol: "ssh",
741 error: "The token in keyring is invalid.",
742 },
743 ],
744 },
745 }),
746 ),
747 );
748​
749 assert.deepStrictEqual(
750 {
751 status: auth.status,
752 host: auth.host,
753 detail: auth.detail,
754 },
755 {
756 status: "unauthenticated",
757 host: Option.some("github.com"),
758 detail: Option.some("The token in keyring is invalid."),
759 },
760 );
761});
762​
763it("reports an update hint instead of unauthenticated when gh predates --json", () => {
764 const auth = GitHubSourceControlProvider.discovery.parseAuth(
765 processResult("", {
766 stderr: "unknown flag: --json\n\nUsage: gh auth status [flags]\n",
767 exitCode: ChildProcessSpawner.ExitCode(1),
768 }),
769 );
770​
771 assert.strictEqual(auth.status, "unknown");
772 assert.match(
773 Option.getOrElse(auth.detail, () => ""),
774 /2\.81\.0/,
775 );
776});
777​
778it.effect.each(["pull", "issues"])(
779 "resolves %s subjects on the linked host without using the checkout",
780 (kind) =>
781 Effect.gen(function* () {
782 const provider = yield* makeProvider({
783 rest: (input) => {
784 assert.strictEqual(input.host, "github.com");
785 assert.strictEqual(input.path, "repos/owner/repo/issues/42");
786 return Effect.succeed(
787 restResponse({ title: "Pairing expiry", body: "Preserve remote access", id: 1 }),
788 );
789 },
790 });
791 const lookup = provider.resolveLink?.({
792 cwd: "/unrelated",
793 url: new URL(`https://github.com/owner/repo/${kind}/42`),
794 });
795 assert.ok(lookup);
796 assert.deepStrictEqual(yield* lookup, {
797 title: "Pairing expiry",
798 body: "Preserve remote access",
799 });
800 assert.strictEqual(
801 provider.resolveLink?.({
802 cwd: "/unrelated",
803 url: new URL("https://github.com/owner/repo"),
804 }),
805 undefined,
806 );
807 }),
808);
809​
810it.effect.each(["read", "decode"] as const)(
811 "retains the %s failure without exposing its raw contents",
812 (stage) =>
813 Effect.gen(function* () {
814 const cause = new GitHubRequestPolicy.GitHubApiResponseError({
815 host: "github.com",
816 operation: "resolveLink",
817 status: 500,
818 });
819 const provider = yield* makeProvider({
820 rest: () =>
821 stage === "read"
822 ? Effect.fail(cause)
823 : Effect.succeed({ ...restResponse(undefined), body: "private response text" }),
824 });
825 const lookup = provider.resolveLink?.({
826 cwd: "/repo",
827 url: new URL("https://github.com/owner/repo/issues/42"),
828 });
829 assert.ok(lookup);
830 const error = yield* Effect.flip(lookup);
831 assert.strictEqual(error.operation, stage === "read" ? "resolveLink" : "resolveLink.decode");
832 assert.strictEqual(error.detail, "The linked subject could not be read.");
833 assert.notInclude(error.message, "private response text");
834 if (stage === "read") assert.strictEqual(error.cause, cause);
835 else assert.propertyVal(error.cause, "_tag", "SchemaError");
836 }),
837);
838​
839const multiAccountStatus = (extra: ReadonlyArray<Record<string, unknown>> = []) =>
840 processResult(
841 JSON.stringify({
842 hosts: {
843 "github.com": [
844 { state: "success", active: true, host: "github.com", login: "personal" },
845 { state: "success", active: false, host: "github.com", login: "work" },
846 ...extra,
847 ],
848 "ghe.acme.test": [
849 { state: "error", active: true, host: "ghe.acme.test", login: "jm", error: "expired" },
850 ],
851 },
852 }),
853 );
854​
855it("reports every gh login and leads with the account Settings pin", () => {
856 const auth = GitHubSourceControlProvider.parseGitHubAuth(multiAccountStatus(), {
857 hosts: { "github.com": { account: "work", enabled: true } },
858 tokens: {},
859 });
860 assert.deepStrictEqual(auth.account, Option.some("work"));
861 assert.deepStrictEqual(auth.accounts, [
862 { host: "github.com", account: "personal", active: true, authenticated: true },
863 { host: "github.com", account: "work", active: false, authenticated: true },
864 { host: "ghe.acme.test", account: "jm", active: true, authenticated: false, error: "expired" },
865 ]);
866});
867​
868it("falls back to gh's active login when the pinned account is gone", () => {
869 const auth = GitHubSourceControlProvider.parseGitHubAuth(multiAccountStatus(), {
870 hosts: { "github.com": { account: "former-job", enabled: true } },
871 tokens: {},
872 });
873 assert.deepStrictEqual(auth.account, Option.some("personal"));
874});
875​
876it("reports unauthenticated when Settings turn off every signed-in host", () => {
877 const auth = GitHubSourceControlProvider.parseGitHubAuth(multiAccountStatus(), {
878 hosts: { "github.com": { enabled: false } },
879 tokens: {},
880 });
881 assert.strictEqual(auth.status, "unauthenticated");
882 assert.deepStrictEqual(
883 auth.detail,
884 Option.some("Every GitHub host gh is signed in to is turned off in Settings → Source Control."),
885 );
886});
887​
888it("names the environment token that overrides the Settings choice", () => {
889 const auth = GitHubSourceControlProvider.parseGitHubAuth(
890 multiAccountStatus([
891 {
892 state: "success",
893 active: false,
894 host: "github.com",
895 login: "bot",
896 tokenSource: "GH_TOKEN",
897 },
898 ]),
899 { hosts: { "github.com": { account: "work", enabled: true } }, tokens: {} },
900 );
901 assert.deepStrictEqual(auth.account, Option.some("bot"));
902 assert.deepStrictEqual(
903 auth.detail,
904 Option.some(
905 "Using GH_TOKEN from the server environment; it overrides the account chosen in Settings.",
906 ),
907 );
908 assert.strictEqual(auth.accounts?.[2]?.environmentVariable, "GH_TOKEN");
909});
910​
911it.live.each([
912 "git@code.example.test:team/project.git",
913 "ssh://git@code.example.test/team/project.git",
914 "https://code.example.test/team/project.git",
915])("keeps Enterprise operations on the selected remote: %s", (remoteUrl) => {
916 const rest: GitHubRest.GitHubRestInput[] = [];
917 const pr = {
918 ...node(42, "feature", "team"),
919 url: "https://code.example.test/team/project/pull/42",
920 isCrossRepository: false,
921 headRepository: { name: "project", nameWithOwner: "team/project" },
922 };
923 const api = {
924 rest: (input: GitHubRest.GitHubRestInput) =>
925 Effect.sync(() => {
926 rest.push(input);
927 return restResponse({
928 full_name: "team/project",
929 html_url: `https://${input.host}/team/project`,
930 ssh_url: `git@${input.host}:team/project.git`,
931 default_branch: "main",
932 });
933 }),
934 };
935 const { layer, git, graphqlCalls } = harness({
936 remotes: remotesOutput(
937 ["origin", "git@github.com:team/project.git"],
938 ["enterprise", remoteUrl],
939 ),
940 api,
941 graphql: (_, call) =>
942 call.operationName === "PullRequestByNumber"
943 ? { pullRequest: pr }
944 : { pullRequests: { nodes: [pr] } },
945 });
946 return Effect.gen(function* () {
947 const provider = yield* GitHubSourceControlProvider.make;
948 const fs = yield* FileSystem.FileSystem;
949 const bodyFile = yield* fs.makeTempFileScoped({ suffix: ".md" });
950 yield* fs.writeFileString(bodyFile, "Enterprise PR");
951 const input = {
952 cwd: "/repo",
953 context: {
954 provider: {
955 kind: SourceControlProviderKind.make("github"),
956 name: "GitHub Self-Hosted",
957 baseUrl: "https://code.example.test",
958 },
959 remoteName: "enterprise",
960 remoteUrl,
961 },
962 };
963 for (const state of ["open", "closed"] as const) {
964 const prs = yield* provider.listChangeRequests({
965 ...input,
966 state,
967 headSelector: "feature",
968 });
969 assert.strictEqual(prs[0]?.url, "https://code.example.test/team/project/pull/42");
970 }
971 yield* provider.getChangeRequest({ ...input, reference: "42" });
972 yield* provider.getChangeRequest({ ...input, reference: "feature" });
973 yield* provider.createChangeRequest({
974 ...input,
975 baseRefName: "main",
976 headSelector: "feature",
977 title: "PR",
978 bodyFile,
979 });
980 assert.strictEqual(yield* provider.getDefaultBranch(input), "main");
981 yield* provider.checkoutChangeRequest({ ...input, reference: "42" });
982 yield* provider.getRepositoryCloneUrls({ ...input, repository: "team/other" });
983 yield* provider.getRepositoryCloneUrls({ ...input, repository: "github.com/team/explicit" });
984 const lookups = graphqlCalls.flatMap((call) =>
985 call.lookups.map(({ owner, name }) => [call.host, owner, name]),
986 );
987 assert.deepStrictEqual(
988 lookups,
989 Array.from({ length: 5 }, () => ["code.example.test", "team", "project"]),
990 );
991 assert.deepStrictEqual(
992 rest.map(({ host, path }) => [host, path]),
993 [
994 ["code.example.test", "repos/team/project/pulls"],
995 ["code.example.test", "repos/team/project"],
996 ["code.example.test", "repos/team/other"],
997 ["github.com", "repos/team/explicit"],
998 ],
999 );
1000 assert.deepStrictEqual(git.find(([name]) => name === "fetchRemoteTrackingBranch")?.[1], {
1001 cwd: "/repo",
1002 remoteName: "enterprise",
1003 remoteBranch: "feature",
1004 });
1005 }).pipe(Effect.provide(layer), Effect.provideService(HostProcess.Environment, {}), Effect.scoped);
1006});
1007​
1008it.effect.each([
1009 { host: "github.com", resolved: "", envRepository: "", expected: "acme/web" },
1010 { host: "code.example.test", resolved: "", envRepository: "", expected: "acme/web" },
1012 host: "github.com",
1013 resolved: "remote.origin.gh-resolved base",
1014 envRepository: "",
1015 expected: "me/web",
1016 },
1018 host: "code.example.test",
1019 resolved: "remote.origin.gh-resolved base",
1020 envRepository: "",
1021 expected: "me/web",
1022 },
1024 host: "github.com",
1025 resolved: "remote.upstream.gh-resolved acme/other",
1026 envRepository: "",
1027 expected: "acme/other",
1028 },
1030 host: "code.example.test",
1031 resolved: "remote.upstream.gh-resolved acme/other",
1032 envRepository: "",
1033 expected: "acme/other",
1034 },
1035 { host: "github.com", resolved: "", envRepository: "chosen/repo", expected: "chosen/repo" },
1037 host: "code.example.test",
1038 resolved: "",
1039 envRepository: "chosen/repo",
1040 expected: "chosen/repo",
1041 },
1042])(
1043 "preserves repository precedence on $host: $resolved $envRepository",
1044 ({ host, resolved, envRepository, expected }) => {
1045 const targets: string[] = [];
1046 const { layer } = harness({
1047 remotes: remotesOutput(
1048 ["origin", `git@${host}:me/web.git`],
1049 ["upstream", `git@${host}:acme/web.git`],
1050 ),
1051 resolved,
1052 api: {
1053 rest: (input) =>
1054 Effect.sync(() => {
1055 targets.push(`${input.host}/${input.path}`);
1056 return restResponse({
1057 full_name: expected,
1058 html_url: `https://${host}/${expected}`,
1059 ssh_url: `git@${host}:${expected}.git`,
1060 default_branch: "main",
1061 });
1062 }),
1063 },
1064 });
1065 return Effect.gen(function* () {
1066 const provider = yield* GitHubSourceControlProvider.make;
1067 const fs = yield* FileSystem.FileSystem;
1068 const bodyFile = yield* fs.makeTempFileScoped();
1069 yield* fs.writeFileString(bodyFile, "Body");
1070 const input = {
1071 cwd: "/repo",
1072 context: {
1073 provider: {
1074 kind: SourceControlProviderKind.make("github"),
1075 name: "GitHub",
1076 baseUrl: `https://${host}`,
1077 },
1078 remoteName: "origin",
1079 remoteUrl: `git@${host}:me/web.git`,
1080 },
1081 };
1082 yield* provider.getDefaultBranch(input);
1083 yield* provider.createChangeRequest({
1084 ...input,
1085 baseRefName: "main",
1086 headSelector: "me:feature",
1087 title: "PR",
1088 bodyFile,
1089 });
1090 assert.deepStrictEqual(targets, [
1091 `${host}/repos/${expected}`,
1092 `${host}/repos/${expected}/pulls`,
1093 ]);
1094 }).pipe(
1095 Effect.provide(layer),
1096 Effect.provideService(HostProcess.Environment, { GH_REPO: envRepository }),
1097 Effect.scoped,
1098 );
1099 },