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