Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitHubSourceControlProvider.test.ts

1,349 lines44.8 KB

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>>>;
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 );
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 };
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 yield* gh.listChangeRequests({
509 cwd: "/repo",
510 headSelector: "me:main",
511 state: "open",
512 repository: "me/web",
513 });
514 assert.include(paths[2], "repos/me/web/pulls?head=me%3Amain");
515 assert.lengthOf(graphqlCalls, 0);
516 }).pipe(Effect.provide(layer));
517 });
518​
519 it.effect("maps API failures onto the errors callers handle", () => {
520 let signedIn = false;
521 const { layer } = harness({
522 remotes,
523 credential: (host) =>
524 signedIn
525 ? Effect.succeed({
526 host,
527 token: Redacted.make("token"),
528 source: "gh" as const,
529 fingerprint: "fp",
530 })
531 : Effect.fail(new GitHubCredentials.GitHubCliMissingError({ host })),
532 graphql: () =>
533 new Response(encodeJson({ message: "API rate limit exceeded" }), {
534 status: 403,
535 headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": "123" },
536 }),
537 });
538 return Effect.gen(function* () {
539 const gh = yield* GitHubSourceControlProvider.make;
540 const read = (headSelector: string) =>
541 gh
542 .listChangeRequests({ cwd: "/repo", headSelector, state: "open", limit: 1 })
543 .pipe(Effect.flip, Effect.forkChild);
544 const missing = yield* read("missing");
545 yield* TestClock.adjust("500 millis");
546 assert.include((yield* Fiber.join(missing)).detail, "No GitHub credential on the server");
547 signedIn = true;
548 const limited = yield* read("limited");
549 yield* TestClock.adjust("500 millis");
550 const error = yield* Fiber.join(limited);
551 assert.include(error.detail, "rate limit exceeded");
552 assert.propertyVal(error.cause, "retryAt", 123_000);
553 }).pipe(Effect.provide(layer));
554 });
555});
556​
557describe("GitHubSourceControlProvider.getChangeRequest", () => {
558 it.effect("reads a pull request by number, and by URL on its own repository", () => {
559 const { layer, graphqlCalls } = harness({
560 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
561 graphql: () => ({ pullRequest: node(42, "feature") }),
562 });
563 return Effect.gen(function* () {
564 const gh = yield* GitHubSourceControlProvider.make;
565 assert.strictEqual(
566 (yield* gh.getChangeRequest({ cwd: "/repo", reference: "#42" })).number,
567 42,
568 );
569 yield* gh.getChangeRequest({
570 cwd: "/repo",
571 reference: "https://github.com/other/thing/pull/42",
572 });
573 assert.deepStrictEqual(
574 graphqlCalls.flatMap((call) => call.lookups),
575 [
576 { owner: "acme", name: "web", number: 42 },
577 { owner: "other", name: "thing", number: 42 },
578 ],
579 );
580 }).pipe(Effect.provide(layer));
581 });
582});
583​
584describe("GitHubSourceControlProvider writes", () => {
585 it.effect("creates a cross-repository pull request with an owner:branch head", () => {
586 const requests: Array<GitHubRest.GitHubRestInput> = [];
587 const { layer } = harness({
588 remotes: remotesOutput(
589 ["origin", "git@github.com:me/web.git"],
590 ["upstream", "git@github.com:acme/web.git"],
591 ),
592 api: {
593 rest: (input) =>
594 Effect.sync(() => {
595 requests.push(input);
596 return restResponse({ number: 1 }, 201);
597 }),
598 },
599 });
600 return Effect.gen(function* () {
601 const fs = yield* FileSystem.FileSystem;
602 const bodyFile = yield* fs.makeTempFileScoped({ suffix: ".md" });
603 yield* fs.writeFileString(bodyFile, "Body");
604 const gh = yield* GitHubSourceControlProvider.make;
605 yield* gh.createChangeRequest({
606 cwd: "/repo",
607 baseRefName: "main",
608 headSelector: "me:feature",
609 title: "Title",
610 bodyFile,
611 });
612 assert.strictEqual(requests[0]!.method, "POST");
613 assert.strictEqual(requests[0]!.path, "repos/acme/web/pulls");
614 assert.strictEqual(requests[0]!.allowReserve, true);
615 assert.deepStrictEqual(requests[0]!.body, {
616 base: "main",
617 head: "me:feature",
618 title: "Title",
619 body: "Body",
620 maintainer_can_modify: true,
621 });
622 yield* gh.createChangeRequest({
623 cwd: "/repo",
624 baseRefName: "main",
625 headSelector: "me:feature",
626 title: "Title",
627 bodyFile,
628 draft: true,
629 });
630 assert.strictEqual((requests[1]!.body as { draft?: unknown }).draft, true);
631 }).pipe(Effect.provide(Layer.merge(layer, NodeServices.layer)));
632 });
633​
634 it.effect("creates a repository under an organization the viewer is not", () => {
635 const requests: Array<string> = [];
636 const { layer } = harness({
637 remotes: "",
638 api: {
639 rest: (input) =>
640 Effect.sync(() => {
641 requests.push(`${input.method ?? "GET"} ${input.path}`);
642 return input.path === "user"
643 ? restResponse({ login: "me" })
644 : restResponse({
645 full_name: "acme/new",
646 html_url: "https://github.com/acme/new",
647 ssh_url: "git@github.com:acme/new.git",
648 });
649 }),
650 },
651 });
652 return Effect.gen(function* () {
653 const gh = yield* GitHubSourceControlProvider.make;
654 const urls = yield* gh.createRepository({
655 cwd: "/repo",
656 repository: "acme/new",
657 visibility: "private",
658 });
659 assert.deepStrictEqual(urls, {
660 nameWithOwner: "acme/new",
661 url: "https://github.com/acme/new",
662 sshUrl: "git@github.com:acme/new.git",
663 });
664 assert.deepStrictEqual(requests, ["GET user", "POST orgs/acme/repos"]);
665 }).pipe(Effect.provide(layer));
666 });
667​
668 it.effect("looks up a bare repository name under the signed-in account on that host", () => {
669 const requests: Array<string> = [];
670 return Effect.gen(function* () {
671 const gh = yield* makeProvider({
672 rest: (input) =>
673 Effect.sync(() => {
674 requests.push(`${input.host} ${input.method ?? "GET"} ${input.path}`);
675 return input.path === "user"
676 ? restResponse({ login: "me" })
677 : restResponse({
678 full_name: "me/notes",
679 html_url: `https://${input.host}/me/notes`,
680 ssh_url: `git@${input.host}:me/notes.git`,
681 });
682 }),
683 });
684​
685 const urls = yield* gh.getRepositoryCloneUrls({
686 cwd: "/repo",
687 context: githubContext("code.example.test"),
688 repository: " notes.git ",
689 });
690​
691 assert.deepStrictEqual(urls, {
692 nameWithOwner: "me/notes",
693 url: "https://code.example.test/me/notes",
694 sshUrl: "git@code.example.test:me/notes.git",
695 });
696 assert.deepStrictEqual(requests, [
697 "code.example.test GET user",
698 "code.example.test GET repos/me/notes",
699 ]);
700 for (const repository of ["me/", "/notes", "a/b/c/d", "", "two words"]) {
701 const error = yield* Effect.flip(gh.getRepositoryCloneUrls({ cwd: "/repo", repository }));
702 assert.include(error.message, "Repositories are named owner/name.");
703 }
704 assert.strictEqual(requests.length, 2);
705 });
706 });
707});
708​
709describe("GitHubSourceControlProvider.checkoutChangeRequest", () => {
710 it.effect("refuses a fork checkout when the base's default branch cannot be read", () => {
711 const { layer, git } = harness({
712 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
713 localBranches: ["main"],
714 graphql: () => ({ pullRequest: node(6, "main", "someone") }),
715 api: {
716 rest: () =>
717 Effect.fail(
718 new GitHubRequestPolicy.GitHubApiRequestError({
719 host: "github.com",
720 operation: "x",
721 cause: "offline",
722 }),
723 ),
724 },
725 });
726 return Effect.gen(function* () {
727 const gh = yield* GitHubSourceControlProvider.make;
728 yield* Effect.flip(gh.checkoutChangeRequest({ cwd: "/repo", reference: "6", force: true }));
729 assert.deepStrictEqual(git, []);
730 }).pipe(Effect.provide(layer));
731 });
732​
733 it.effect("adds a fork remote with the protocol of the URL origin fetches from", () => {
734 // `git remote -v` shows origin's SSH `insteadOf` rewrite; config holds HTTPS, then an SSH push URL.
735 const { layer, git } = harness({
736 remotes: [
737 "origin\tgit@github.com:acme/web.git (fetch)",
738 "origin\tgit@github.com:acme/web.git (push)",
739 "origin\tgit@github.com:acme/web.git (push)",
740 ].join("\n"),
741 originUrls: "https://github.com/acme/web.git\ngit@github.com:acme/web.git\n",
742 graphql: () => ({ pullRequest: node(7, "feature", "someone") }),
743 api: {
744 rest: (input) => {
745 const fullName = input.path.slice("repos/".length);
746 return Effect.succeed(
747 restResponse({
748 full_name: fullName,
749 html_url: `https://github.com/${fullName}`,
750 ssh_url: `git@github.com:${fullName}.git`,
751 default_branch: "main",
752 }),
753 );
754 },
755 },
756 });
757 return Effect.gen(function* () {
758 const gh = yield* GitHubSourceControlProvider.make;
759 yield* gh.checkoutChangeRequest({ cwd: "/repo", reference: "7" });
760 assert.deepStrictEqual(git.find(([name]) => name === "ensureRemote")?.[1], {
761 cwd: "/repo",
762 preferredName: "someone",
763 url: "https://github.com/someone/web",
764 });
765 }).pipe(Effect.provide(layer));
766 });
767​
768 it.effect("keeps git's own output out of what a failed checkout reports", () => {
769 const { layer } = harness({
770 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
771 gitFailure: new Error("fatal: /home/me/secret-path: permission denied"),
772 graphql: () => ({ pullRequest: node(5, "feature/x") }),
773 });
774 return Effect.gen(function* () {
775 const gh = yield* GitHubSourceControlProvider.make;
776 const error = yield* gh
777 .checkoutChangeRequest({ cwd: "/repo", reference: "5" })
778 .pipe(Effect.flip);
779 assert.strictEqual(error.detail, "The pull request could not be checked out with git.");
780 assert.notInclude(error.message, "secret-path");
781 }).pipe(Effect.provide(layer));
782 });
783​
784 it.effect("records the branch base for gh through the host's config write", () => {
785 const { layer, git } = harness({
786 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
787 });
788 return Effect.gen(function* () {
789 const gh = yield* GitHubSourceControlProvider.make;
790 yield* gh.recordBranchBase!({ cwd: "/repo", branch: "feature", baseBranch: "main" });
791 assert.deepStrictEqual(git, [
792 ["writeConfigValue", { cwd: "/repo", key: "branch.feature.gh-merge-base", value: "main" }],
793 ]);
794 }).pipe(Effect.provide(layer));
795 });
796​
797 it("names the local branch the way gh pr checkout does", () => {
798 const name = (headRefName: string, isCrossRepository: boolean) =>
799 GitHubSourceControlProvider.pullRequestCheckoutBranchName({
800 headRefName,
801 headOwner: "someone",
802 isCrossRepository,
803 defaultBranch: "main",
804 });
805 assert.strictEqual(name("main", true), "someone/main");
806 assert.strictEqual(name("feature", true), "feature");
807 assert.strictEqual(name("main", false), "main");
808 });
809});
810​
811it("accepts active authenticated GitHub accounts when another account fails", () => {
812 const auth = GitHubSourceControlProvider.discovery.parseAuth(
813 processResult(
814 JSON.stringify({
815 hosts: {
816 "github.com": [
817 {
818 state: "success",
819 active: true,
820 host: "github.com",
821 login: "active-user",
822 tokenSource: "keyring",
823 gitProtocol: "ssh",
824 },
825 {
826 state: "error",
827 active: false,
828 host: "github.com",
829 login: "stale-user",
830 tokenSource: "keyring",
831 gitProtocol: "ssh",
832 error: "The token in keyring is invalid.",
833 },
834 ],
835 },
836 }),
837 ),
838 );
839​
840 assert.deepStrictEqual(
841 {
842 status: auth.status,
843 account: auth.account,
844 host: auth.host,
845 },
846 {
847 status: "authenticated",
848 account: Option.some("active-user"),
849 host: Option.some("github.com"),
850 },
851 );
852});
853​
854it("parses GitHub auth JSON from stdout when stderr has warnings", () => {
855 const auth = GitHubSourceControlProvider.discovery.parseAuth(
856 processResult(
857 JSON.stringify({
858 hosts: {
859 "github.com": [
860 {
861 state: "success",
862 active: true,
863 host: "github.com",
864 login: "active-user",
865 tokenSource: "keyring",
866 gitProtocol: "ssh",
867 },
868 ],
869 },
870 }),
871 { stderr: "warning: ignored diagnostic from gh\n" },
872 ),
873 );
874​
875 assert.deepStrictEqual(
876 {
877 status: auth.status,
878 account: auth.account,
879 host: auth.host,
880 },
881 {
882 status: "authenticated",
883 account: Option.some("active-user"),
884 host: Option.some("github.com"),
885 },
886 );
887});
888​
889it("parses GitHub auth status accounts by host and active state", () => {
890 assert.deepStrictEqual(
891 parseGitHubAuthStatus(
892 JSON.stringify({
893 hosts: {
894 "github.com": [
895 {
896 state: "success",
897 active: true,
898 host: "github.com",
899 login: "active-user",
900 tokenSource: "keyring",
901 gitProtocol: "ssh",
902 },
903 {
904 state: "error",
905 active: false,
906 host: "github.com",
907 login: "stale-user",
908 tokenSource: "keyring",
909 gitProtocol: "ssh",
910 },
911 ],
912 "github.example.test": [
913 {
914 state: "success",
915 active: false,
916 host: "github.example.test",
917 login: "enterprise-user",
918 tokenSource: "keyring",
919 gitProtocol: "ssh",
920 },
921 ],
922 },
923 }),
924 ).accounts,
925 [
926 {
927 host: "github.com",
928 account: "active-user",
929 authenticated: true,
930 active: true,
931 error: null,
932 environmentVariable: null,
933 },
934 {
935 host: "github.com",
936 account: "stale-user",
937 authenticated: false,
938 active: false,
939 error: null,
940 environmentVariable: null,
941 },
942 {
943 host: "github.example.test",
944 account: "enterprise-user",
945 authenticated: true,
946 active: false,
947 error: null,
948 environmentVariable: null,
949 },
950 ],
951 );
952});
953​
954it("reports unauthenticated when GitHub JSON has accounts but none are valid", () => {
955 const auth = GitHubSourceControlProvider.discovery.parseAuth(
956 processResult(
957 JSON.stringify({
958 hosts: {
959 "github.com": [
960 {
961 state: "error",
962 active: true,
963 host: "github.com",
964 login: "stale-user",
965 tokenSource: "keyring",
966 gitProtocol: "ssh",
967 error: "The token in keyring is invalid.",
968 },
969 ],
970 },
971 }),
972 ),
973 );
974​
975 assert.deepStrictEqual(
976 {
977 status: auth.status,
978 host: auth.host,
979 detail: auth.detail,
980 },
981 {
982 status: "unauthenticated",
983 host: Option.some("github.com"),
984 detail: Option.some("The token in keyring is invalid."),
985 },
986 );
987});
988​
989it("reports an update hint instead of unauthenticated when gh predates --json", () => {
990 const auth = GitHubSourceControlProvider.discovery.parseAuth(
991 processResult("", {
992 stderr: "unknown flag: --json\n\nUsage: gh auth status [flags]\n",
993 exitCode: ChildProcessSpawner.ExitCode(1),
994 }),
995 );
996​
997 assert.strictEqual(auth.status, "unknown");
998 assert.match(
999 Option.getOrElse(auth.detail, () => ""),
1000 /2\.81\.0/,
1001 );
1002});
1003​
1004it.effect.each(["pull", "issues"])(
1005 "resolves %s subjects on the linked host without using the checkout",
1006 (kind) =>
1007 Effect.gen(function* () {
1008 const provider = yield* makeProvider({
1009 rest: (input) => {
1010 assert.strictEqual(input.host, "github.com");
1011 assert.strictEqual(input.path, "repos/owner/repo/issues/42");
1012 return Effect.succeed(
1013 restResponse({ title: "Pairing expiry", body: "Preserve remote access", id: 1 }),
1014 );
1015 },
1016 });
1017 const lookup = provider.resolveLink?.({
1018 cwd: "/unrelated",
1019 url: new URL(`https://github.com/owner/repo/${kind}/42`),
1020 });
1021 assert.ok(lookup);
1022 assert.deepStrictEqual(yield* lookup, {
1023 title: "Pairing expiry",
1024 body: "Preserve remote access",
1025 });
1026 for (const url of [
1027 "https://github.com/owner/repo",
1028 "https://github.attacker.test/owner/repo/issues/42",
1029 ]) {
1030 assert.strictEqual(
1031 provider.resolveLink?.({ cwd: "/unrelated", url: new URL(url) }),
1032 undefined,
1033 );
1035 }),
1037​
1038it.effect.each(["read", "decode"] as const)(
1039 "retains the %s failure without exposing its raw contents",
1040 (stage) =>
1041 Effect.gen(function* () {
1042 const cause = new GitHubRequestPolicy.GitHubApiResponseError({
1043 host: "github.com",
1044 operation: "resolveLink",
1045 status: 500,
1046 });
1047 const provider = yield* makeProvider({
1048 rest: () =>
1049 stage === "read"
1050 ? Effect.fail(cause)
1051 : Effect.succeed({ ...restResponse(undefined), body: "private response text" }),
1052 });
1053 const lookup = provider.resolveLink?.({
1054 cwd: "/repo",
1055 url: new URL("https://github.com/owner/repo/issues/42"),
1056 });
1057 assert.ok(lookup);
1058 const error = yield* Effect.flip(lookup);
1059 assert.strictEqual(error.operation, stage === "read" ? "resolveLink" : "resolveLink.decode");
1060 assert.strictEqual(error.detail, "The linked subject could not be read.");
1061 assert.notInclude(error.message, "private response text");
1062 if (stage === "read") assert.strictEqual(error.cause, cause);
1063 else assert.propertyVal(error.cause, "_tag", "SchemaError");
1064 }),
1066​
1067const multiAccountStatus = (extra: ReadonlyArray<Record<string, unknown>> = []) =>
1068 processResult(
1069 JSON.stringify({
1070 hosts: {
1071 "github.com": [
1072 { state: "success", active: true, host: "github.com", login: "personal" },
1073 { state: "success", active: false, host: "github.com", login: "work" },
1074 ...extra,
1075 ],
1076 "ghe.acme.test": [
1077 { state: "error", active: true, host: "ghe.acme.test", login: "jm", error: "expired" },
1078 ],
1079 },
1080 }),
1081 );
1082​
1083it("reports every gh login and leads with the account Settings pin", () => {
1084 const auth = GitHubSourceControlProvider.parseGitHubAuth(multiAccountStatus(), {
1085 hosts: { "github.com": { account: "work", enabled: true } },
1086 tokens: {},
1087 signIns: {},
1088 });
1089 assert.deepStrictEqual(auth.account, Option.some("work"));
1090 assert.deepStrictEqual(auth.accounts, [
1091 { host: "github.com", account: "personal", active: true, authenticated: true },
1092 { host: "github.com", account: "work", active: false, authenticated: true },
1093 { host: "ghe.acme.test", account: "jm", active: true, authenticated: false, error: "expired" },
1094 ]);
1095});
1096​
1097it("reports unauthenticated when Settings turn off every signed-in host", () => {
1098 const auth = GitHubSourceControlProvider.parseGitHubAuth(multiAccountStatus(), {
1099 hosts: { "github.com": { enabled: false } },
1100 tokens: {},
1101 signIns: {},
1102 });
1103 assert.strictEqual(auth.status, "unauthenticated");
1104 assert.deepStrictEqual(
1105 auth.detail,
1106 Option.some(
1107 "Every GitHub host gh is signed in to is turned off in Settings → Source control & issues.",
1108 ),
1109 );
1110});
1111​
1112it("names the environment token that overrides the Settings choice", () => {
1113 const auth = GitHubSourceControlProvider.parseGitHubAuth(
1114 multiAccountStatus([
1116 state: "success",
1117 active: false,
1118 host: "github.com",
1119 login: "bot",
1120 tokenSource: "GH_TOKEN",
1121 },
1122 ]),
1123 { hosts: { "github.com": { account: "work", enabled: true } }, tokens: {}, signIns: {} },
1124 );
1125 assert.deepStrictEqual(auth.account, Option.some("bot"));
1126 assert.deepStrictEqual(
1127 auth.detail,
1128 Option.some(
1129 "Using GH_TOKEN from the server environment; it overrides the account chosen in Settings.",
1130 ),
1131 );
1132 assert.strictEqual(auth.accounts?.[2]?.environmentVariable, "GH_TOKEN");
1133});
1134​
1135it.live.each([
1136 "git@code.example.test:team/project.git",
1137 "ssh://git@code.example.test/team/project.git",
1138 "https://code.example.test/team/project.git",
1139])("keeps Enterprise operations on the selected remote: %s", (remoteUrl) => {
1140 const rest: GitHubRest.GitHubRestInput[] = [];
1141 const pr = {
1142 ...node(42, "feature", "team"),
1143 url: "https://code.example.test/team/project/pull/42",
1144 isCrossRepository: false,
1145 headRepository: { name: "project", nameWithOwner: "team/project" },
1146 };
1147 const api = {
1148 rest: (input: GitHubRest.GitHubRestInput) =>
1149 Effect.sync(() => {
1150 rest.push(input);
1151 return restResponse({
1152 full_name: "team/project",
1153 html_url: `https://${input.host}/team/project`,
1154 ssh_url: `git@${input.host}:team/project.git`,
1155 default_branch: "main",
1156 });
1157 }),
1158 };
1159 const { layer, git, graphqlCalls } = harness({
1160 remotes: remotesOutput(
1161 ["origin", "git@github.com:team/project.git"],
1162 ["enterprise", remoteUrl],
1163 ),
1164 api,
1165 graphql: (_, call) =>
1166 call.operationName === "PullRequestByNumber"
1167 ? { pullRequest: pr }
1168 : { pullRequests: { nodes: [pr] } },
1169 });
1170 return Effect.gen(function* () {
1171 const provider = yield* GitHubSourceControlProvider.make;
1172 const fs = yield* FileSystem.FileSystem;
1173 const bodyFile = yield* fs.makeTempFileScoped({ suffix: ".md" });
1174 yield* fs.writeFileString(bodyFile, "Enterprise PR");
1175 const input = {
1176 cwd: "/repo",
1177 context: {
1178 provider: {
1179 kind: SourceControlProviderKind.make("github"),
1180 name: "GitHub Self-Hosted",
1181 baseUrl: "https://code.example.test",
1182 },
1183 remoteName: "enterprise",
1184 remoteUrl,
1185 },
1186 };
1187 for (const state of ["open", "closed"] as const) {
1188 const prs = yield* provider.listChangeRequests({
1189 ...input,
1190 state,
1191 headSelector: "feature",
1192 });
1193 assert.strictEqual(prs[0]?.url, "https://code.example.test/team/project/pull/42");
1195 yield* provider.getChangeRequest({ ...input, reference: "42" });
1196 yield* provider.getChangeRequest({ ...input, reference: "feature" });
1197 yield* provider.createChangeRequest({
1198 ...input,
1199 baseRefName: "main",
1200 headSelector: "feature",
1201 title: "PR",
1202 bodyFile,
1203 });
1204 assert.strictEqual(yield* provider.getDefaultBranch(input), "main");
1205 yield* provider.checkoutChangeRequest({ ...input, reference: "42" });
1206 yield* provider.getRepositoryCloneUrls({ ...input, repository: "team/other" });
1207 yield* provider.getRepositoryCloneUrls({ ...input, repository: "github.com/team/explicit" });
1208 const lookups = graphqlCalls.flatMap((call) =>
1209 call.lookups.map(({ owner, name }) => [call.host, owner, name]),
1210 );
1211 assert.deepStrictEqual(
1212 lookups,
1213 Array.from({ length: 5 }, () => ["code.example.test", "team", "project"]),
1214 );
1215 assert.deepStrictEqual(
1216 rest.map(({ host, path }) => [host, path]),
1218 ["code.example.test", "repos/team/project/pulls"],
1219 ["code.example.test", "repos/team/project"],
1220 ["code.example.test", "repos/team/other"],
1221 ["github.com", "repos/team/explicit"],
1222 ],
1223 );
1224 assert.deepStrictEqual(git.find(([name]) => name === "createBranch")?.[1], {
1225 cwd: "/repo",
1226 branch: "feature",
1227 startPoint: "refs/remotes/enterprise/feature",
1228 });
1229 assert.deepStrictEqual(git.find(([name]) => name === "fetchRemoteTrackingBranch")?.[1], {
1230 cwd: "/repo",
1231 remoteName: "enterprise",
1232 remoteBranch: "feature",
1233 });
1234 }).pipe(Effect.provide(layer), Effect.provideService(HostProcess.Environment, {}));
1235});
1236​
1237it.effect.each([
1238 { host: "github.com", resolved: "", envRepository: "", expected: "acme/web" },
1240 host: "code.example.test",
1241 resolved: "remote.origin.gh-resolved base",
1242 envRepository: "",
1243 expected: "me/web",
1244 },
1246 host: "github.com",
1247 resolved: "remote.upstream.gh-resolved acme/other",
1248 envRepository: "",
1249 expected: "acme/other",
1250 },
1252 host: "code.example.test",
1253 resolved: "",
1254 envRepository: "chosen/repo",
1255 expected: "chosen/repo",
1256 },
1257])(
1258 "preserves repository precedence on $host: $resolved $envRepository",
1259 ({ host, resolved, envRepository, expected }) => {
1260 const targets: string[] = [];
1261 const { layer } = harness({
1262 remotes: remotesOutput(
1263 ["origin", `git@${host}:me/web.git`],
1264 ["upstream", `git@${host}:acme/web.git`],
1265 ),
1266 resolved,
1267 api: {
1268 rest: (input) =>
1269 Effect.sync(() => {
1270 targets.push(`${input.host}/${input.path}`);
1271 return restResponse({
1272 full_name: expected,
1273 html_url: `https://${host}/${expected}`,
1274 ssh_url: `git@${host}:${expected}.git`,
1275 default_branch: "main",
1276 });
1277 }),
1278 },
1279 });
1280 return Effect.gen(function* () {
1281 const provider = yield* GitHubSourceControlProvider.make;
1282 const fs = yield* FileSystem.FileSystem;
1283 const bodyFile = yield* fs.makeTempFileScoped();
1284 yield* fs.writeFileString(bodyFile, "Body");
1285 const input = {
1286 cwd: "/repo",
1287 context: {
1288 provider: {
1289 kind: SourceControlProviderKind.make("github"),
1290 name: "GitHub",
1291 baseUrl: `https://${host}`,
1292 },
1293 remoteName: "origin",
1294 remoteUrl: `git@${host}:me/web.git`,
1295 },
1296 };
1297 yield* provider.getDefaultBranch(input);
1298 yield* provider.createChangeRequest({
1299 ...input,
1300 baseRefName: "main",
1301 headSelector: "me:feature",
1302 title: "PR",
1303 bodyFile,
1304 });
1305 assert.deepStrictEqual(targets, [
1306 `${host}/repos/${expected}`,
1307 `${host}/repos/${expected}/pulls`,
1308 ]);
1309 assert.deepStrictEqual(
1310 yield* provider.createsChangeRequestsIn!({ ...input, repository: "me/web" }),
1311 expected === "me/web",
1312 );
1313 }).pipe(
1314 Effect.provide(layer),
1315 Effect.provideService(HostProcess.Environment, { GH_REPO: envRepository }),
1316 );
1317 },
1319​
1320it.effect(
1321 "says a GH_REPO naming an unparseable host falls back to the remotes, as creation does",
1322 () => {
1323 const { layer } = harness({
1324 remotes: remotesOutput(["upstream", "git@github.com:acme/web.git"]),
1325 resolved: "",
1326 api: {},
1327 });
1328 return Effect.gen(function* () {
1329 const provider = yield* GitHubSourceControlProvider.make;
1330 const targets = yield* provider.createsChangeRequestsIn!({
1331 cwd: "/repo",
1332 context: {
1333 provider: {
1334 kind: SourceControlProviderKind.make("github"),
1335 name: "GitHub",
1336 baseUrl: "https://github.com",
1337 },
1338 remoteName: "upstream",
1339 remoteUrl: "git@github.com:acme/web.git",
1340 },
1341 repository: "acme/web",
1342 });
1343 assert.isTrue(targets);
1344 }).pipe(
1345 Effect.provide(layer),
1346 Effect.provideService(HostProcess.Environment, { GH_REPO: "bad host/acme/web" }),
1347 );
1348 },