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

GitHubSourceControlProvider.test.ts

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