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

GitHubSourceControlProvider.test.ts

1,169 lines38.8 KB

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