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

GitHubSourceControlProvider.test.ts

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