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

GitHubSourceControlProvider.test.ts

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