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