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