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