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