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