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