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

GitHubSourceControlProvider.test.ts

1,066 lines34.5 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​
83interface GraphQlCall {
84 readonly host: string;
85 readonly operationName: string;
86 readonly query: string;
87 readonly lookups: ReadonlyArray<Readonly<Record<string, unknown>>>;
89​
90type GraphQlAnswer = unknown;
91type GraphQlRespond = (
92 lookup: Readonly<Record<string, unknown>>,
93 call: GraphQlCall,
94) => GraphQlAnswer | Response;
95​
96function graphQlHttp(respond: GraphQlRespond, calls: Array<GraphQlCall>) {
97 return HttpClient.make((request) =>
98 Effect.sync(() => {
99 const sent =
100 request.body._tag === "Uint8Array"
101 ? (JSON.parse(new TextDecoder().decode(request.body.body)) as {
102 readonly query: string;
103 readonly operationName: string;
104 readonly variables: Readonly<Record<string, unknown>>;
105 })
106 : { query: "", operationName: "", variables: {} };
107 const prefixes = [
108 ...new Set(Object.keys(sent.variables).flatMap((key) => /^_\d+_/.exec(key) ?? [])),
109 ];
110 const lookups =
111 prefixes.length === 0
112 ? [sent.variables]
113 : prefixes.map((prefix) =>
114 Object.fromEntries(
115 Object.entries(sent.variables)
116 .filter(([key]) => key.startsWith(prefix))
117 .map(([key, value]) => [key.slice(prefix.length), value]),
118 ),
119 );
120 const call: GraphQlCall = {
121 host: new URL(request.url).hostname.replace(/^api\./, ""),
122 operationName: sent.operationName,
123 query: sent.query,
124 lookups,
125 };
126 calls.push(call);
127 const answers = lookups.map((lookup) => respond(lookup, call));
128 const refusal = answers.find((answer) => answer instanceof Response);
129 const response =
130 refusal ??
131 new Response(
132 encodeJson({
133 data: Object.fromEntries(
134 answers.map((answer, index) => [
135 prefixes.length === 0 ? "repository" : `${prefixes[index]}repository`,
136 answer,
137 ]),
138 ),
139 }),
140 { headers: { "content-type": "application/json" } },
141 );
142 return HttpClientResponse.fromWeb(request, response);
143 }),
144 );
146​
147function harness(input: {
148 readonly remotes: string;
149 readonly api?: Partial<GitHubRest.GitHubRest["Service"]>;
150 readonly graphql?: GraphQlRespond;
151 readonly credential?: (
152 host: string,
153 ) => Effect.Effect<
154 GitHubCredentials.GitHubCredential,
155 GitHubCredentials.GitHubCredentialUnavailableError
156 >;
157 readonly localBranches?: ReadonlyArray<string>;
158 readonly resolved?: string;
159 readonly gitFailure?: unknown;
160}) {
161 const git: Array<readonly [string, unknown]> = [];
162 const graphqlCalls: Array<GraphQlCall> = [];
163 const record =
164 <A>(name: string, value: A) =>
165 (args: unknown) =>
166 Effect.sync(() => {
167 git.push([name, args]);
168 return value;
169 });
170 const hostGit: Partial<SourceControlHost.SourceControlHost["Service"]["git"]> = {
171 execute: (args) =>
172 Effect.sync(() => {
173 git.push(["execute", args.args]);
174 return processOutput("");
175 }),
176 resolvePrimaryRemoteName: () => Effect.succeed("origin"),
177 readConfigValue: () => Effect.succeed("git@github.com:acme/web.git"),
178 ensureRemote: (args) =>
179 Effect.sync(() => {
180 git.push(["ensureRemote", args]);
181 return args.preferredName;
182 }),
183 fetchRemoteTrackingBranch: (args) => record("fetchRemoteTrackingBranch", undefined)(args),
184 setBranchUpstream: (args) => record("setBranchUpstream", undefined)(args),
185 switchRef: (args) => record("switchRef", { refName: args.refName })(args) as never,
186 listLocalBranchNames: () =>
187 input.gitFailure === undefined
188 ? Effect.succeed([...(input.localBranches ?? [])])
189 : Effect.fail(input.gitFailure as never),
190 resolveCommit: () => Effect.succeed({ commitSha: "abc123" }),
191 };
192 const host = TestSourceControlHost.layer({
193 git: hostGit,
194 process: {
195 run: (args) =>
196 Effect.succeed(
197 args.args[0] === "remote"
198 ? processOutput(input.remotes)
199 : processOutput(input.resolved ?? "", input.resolved ? 0 : 1),
200 ),
201 },
202 });
203 const graphql =
204 input.graphql ??
205 (() => {
206 throw new Error("Unexpected GraphQL read");
207 });
208 const policy = GitHubRequestPolicy.layer.pipe(
209 Layer.provide(
210 Layer.mergeAll(
211 Layer.succeed(GitHubCredentials.GitHubCredentials, {
212 get:
213 input.credential ??
214 ((host) =>
215 Effect.succeed({
216 host,
217 token: Redacted.make("token"),
218 source: "gh" as const,
219 fingerprint: `${host}:token`,
220 })),
221 invalidate: () => Effect.void,
222 }),
223 GitHubQuota.layer,
224 SourceControlRateLimit.layer,
225 ),
226 ),
227 );
228 const layer = Layer.mergeAll(
229 host,
230 Layer.mock(GitHubRest.GitHubRest)(input.api ?? {}),
231 policy,
232 Layer.succeed(HttpClient.HttpClient, graphQlHttp(graphql, graphqlCalls)),
233 NodeServices.layer,
234 );
235 return { layer, git, graphqlCalls };
237​
238const makeProvider = (api: Partial<GitHubRest.GitHubRest["Service"]>) =>
239 GitHubSourceControlProvider.make.pipe(Effect.provide(harness({ remotes: "", api }).layer));
240​
241const githubContext = (host: string) => ({
242 provider: {
243 kind: SourceControlProviderKind.make("github"),
244 name: "GitHub",
245 baseUrl: `https://${host}`,
246 },
247 remoteName: "origin",
248 remoteUrl: `git@${host}:acme/web.git`,
249});
250​
251describe("GitHubSourceControlProvider repository resolution", () => {
252 it.effect("reads the repository gh would pick from the remotes", () => {
253 const paths: string[] = [];
254 const { layer } = harness({
255 remotes: remotesOutput(
256 ["origin", "git@github.com:me/web.git"],
257 ["upstream", "https://github.com/acme/web.git"],
258 ),
259 api: {
260 rest: (input) =>
261 Effect.sync(() => {
262 paths.push(`${input.host} ${input.path}`);
263 return restResponse({
264 full_name: "acme/web",
265 html_url: "https://github.com/acme/web",
266 ssh_url: "git@github.com:acme/web.git",
267 default_branch: "trunk",
268 });
269 }),
270 },
271 });
272 return Effect.gen(function* () {
273 const gh = yield* GitHubSourceControlProvider.make;
274 assert.strictEqual(yield* gh.getDefaultBranch({ cwd: "/repo" }), "trunk");
275 assert.deepStrictEqual(paths, ["github.com repos/acme/web"]);
276 }).pipe(Effect.provide(layer));
277 });
278});
279​
280describe("GitHubSourceControlProvider change request lookups by head", () => {
281 const remotes = remotesOutput(["origin", "git@github.com:acme/web.git"]);
282​
283 it.effect("matches an owner:branch selector on the head owner", () => {
284 const { layer } = harness({
285 remotes,
286 graphql: (lookup) => ({
287 pullRequests: {
288 nodes:
289 lookup.head === "main"
290 ? [node(9, "main", "someone"), node(8, "main", "me"), node(7, "main", "me")]
291 : [],
292 },
293 }),
294 });
295 return Effect.gen(function* () {
296 const gh = yield* GitHubSourceControlProvider.make;
297 const open = yield* gh
298 .listChangeRequests({ cwd: "/repo", headSelector: "me:main", state: "open", limit: 1 })
299 .pipe(Effect.forkChild);
300 yield* TestClock.adjust("50 millis");
301 assert.deepStrictEqual(
302 (yield* Fiber.join(open)).map((pr) => pr.number),
303 [8],
304 );
305 }).pipe(Effect.provide(layer));
306 });
307​
308 it.effect("maps API failures onto the errors callers handle", () => {
309 let signedIn = false;
310 const { layer } = harness({
311 remotes,
312 credential: (host) =>
313 signedIn
314 ? Effect.succeed({
315 host,
316 token: Redacted.make("token"),
317 source: "gh" as const,
318 fingerprint: "fp",
319 })
320 : Effect.fail(new GitHubCredentials.GitHubCliMissingError({ host })),
321 graphql: () =>
322 new Response(encodeJson({ message: "API rate limit exceeded" }), {
323 status: 403,
324 headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": "123" },
325 }),
326 });
327 return Effect.gen(function* () {
328 const gh = yield* GitHubSourceControlProvider.make;
329 const read = (headSelector: string) =>
330 gh
331 .listChangeRequests({ cwd: "/repo", headSelector, state: "open", limit: 1 })
332 .pipe(Effect.flip, Effect.forkChild);
333 const missing = yield* read("missing");
334 yield* TestClock.adjust("500 millis");
335 assert.include((yield* Fiber.join(missing)).detail, "No GitHub credential on the server");
336 signedIn = true;
337 const limited = yield* read("limited");
338 yield* TestClock.adjust("500 millis");
339 const error = yield* Fiber.join(limited);
340 assert.include(error.detail, "rate limit exceeded");
341 assert.propertyVal(error.cause, "retryAt", 123_000);
342 }).pipe(Effect.provide(layer));
343 });
344});
345​
346describe("GitHubSourceControlProvider.getChangeRequest", () => {
347 it.effect("reads a pull request by number, and by URL on its own repository", () => {
348 const { layer, graphqlCalls } = harness({
349 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
350 graphql: () => ({ pullRequest: node(42, "feature") }),
351 });
352 return Effect.gen(function* () {
353 const gh = yield* GitHubSourceControlProvider.make;
354 assert.strictEqual(
355 (yield* gh.getChangeRequest({ cwd: "/repo", reference: "#42" })).number,
356 42,
357 );
358 yield* gh.getChangeRequest({
359 cwd: "/repo",
360 reference: "https://github.com/other/thing/pull/42",
361 });
362 assert.deepStrictEqual(
363 graphqlCalls.flatMap((call) => call.lookups),
364 [
365 { owner: "acme", name: "web", number: 42 },
366 { owner: "other", name: "thing", number: 42 },
367 ],
368 );
369 }).pipe(Effect.provide(layer));
370 });
371});
372​
373describe("GitHubSourceControlProvider writes", () => {
374 it.effect("creates a cross-repository pull request with an owner:branch head", () => {
375 const requests: Array<GitHubRest.GitHubRestInput> = [];
376 const { layer } = harness({
377 remotes: remotesOutput(
378 ["origin", "git@github.com:me/web.git"],
379 ["upstream", "git@github.com:acme/web.git"],
380 ),
381 api: {
382 rest: (input) =>
383 Effect.sync(() => {
384 requests.push(input);
385 return restResponse({ number: 1 }, 201);
386 }),
387 },
388 });
389 return Effect.gen(function* () {
390 const fs = yield* FileSystem.FileSystem;
391 const bodyFile = yield* fs.makeTempFileScoped({ suffix: ".md" });
392 yield* fs.writeFileString(bodyFile, "Body");
393 const gh = yield* GitHubSourceControlProvider.make;
394 yield* gh.createChangeRequest({
395 cwd: "/repo",
396 baseRefName: "main",
397 headSelector: "me:feature",
398 title: "Title",
399 bodyFile,
400 });
401 assert.strictEqual(requests[0]!.method, "POST");
402 assert.strictEqual(requests[0]!.path, "repos/acme/web/pulls");
403 assert.strictEqual(requests[0]!.allowReserve, true);
404 assert.deepStrictEqual(requests[0]!.body, {
405 base: "main",
406 head: "me:feature",
407 title: "Title",
408 body: "Body",
409 maintainer_can_modify: true,
410 });
411 }).pipe(Effect.provide(Layer.merge(layer, NodeServices.layer)), Effect.scoped);
412 });
413​
414 it.effect("creates a repository under an organization the viewer is not", () => {
415 const requests: Array<string> = [];
416 const { layer } = harness({
417 remotes: "",
418 api: {
419 rest: (input) =>
420 Effect.sync(() => {
421 requests.push(`${input.method ?? "GET"} ${input.path}`);
422 return input.path === "user"
423 ? restResponse({ login: "me" })
424 : restResponse({
425 full_name: "acme/new",
426 html_url: "https://github.com/acme/new",
427 ssh_url: "git@github.com:acme/new.git",
428 });
429 }),
430 },
431 });
432 return Effect.gen(function* () {
433 const gh = yield* GitHubSourceControlProvider.make;
434 const urls = yield* gh.createRepository({
435 cwd: "/repo",
436 repository: "acme/new",
437 visibility: "private",
438 });
439 assert.deepStrictEqual(urls, {
440 nameWithOwner: "acme/new",
441 url: "https://github.com/acme/new",
442 sshUrl: "git@github.com:acme/new.git",
443 });
444 assert.deepStrictEqual(requests, ["GET user", "POST orgs/acme/repos"]);
445 }).pipe(Effect.provide(layer));
446 });
447​
448 it.effect("looks up a bare repository name under the signed-in account on that host", () => {
449 const requests: Array<string> = [];
450 return Effect.gen(function* () {
451 const gh = yield* makeProvider({
452 rest: (input) =>
453 Effect.sync(() => {
454 requests.push(`${input.host} ${input.method ?? "GET"} ${input.path}`);
455 return input.path === "user"
456 ? restResponse({ login: "me" })
457 : restResponse({
458 full_name: "me/notes",
459 html_url: `https://${input.host}/me/notes`,
460 ssh_url: `git@${input.host}:me/notes.git`,
461 });
462 }),
463 });
464​
465 const urls = yield* gh.getRepositoryCloneUrls({
466 cwd: "/repo",
467 context: githubContext("code.example.test"),
468 repository: " notes.git ",
469 });
470​
471 assert.deepStrictEqual(urls, {
472 nameWithOwner: "me/notes",
473 url: "https://code.example.test/me/notes",
474 sshUrl: "git@code.example.test:me/notes.git",
475 });
476 assert.deepStrictEqual(requests, [
477 "code.example.test GET user",
478 "code.example.test GET repos/me/notes",
479 ]);
480 for (const repository of ["me/", "/notes", "a/b/c/d", "", "two words"]) {
481 const error = yield* Effect.flip(gh.getRepositoryCloneUrls({ cwd: "/repo", repository }));
482 assert.include(error.message, "Repositories are named owner/name.");
483 }
484 assert.strictEqual(requests.length, 2);
485 });
486 });
487});
488​
489describe("GitHubSourceControlProvider.checkoutChangeRequest", () => {
490 it.effect("refuses a fork checkout when the base's default branch cannot be read", () => {
491 const { layer, git } = harness({
492 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
493 localBranches: ["main"],
494 graphql: () => ({ pullRequest: node(6, "main", "someone") }),
495 api: {
496 rest: () =>
497 Effect.fail(
498 new GitHubRequestPolicy.GitHubApiRequestError({
499 host: "github.com",
500 operation: "x",
501 cause: "offline",
502 }),
503 ),
504 },
505 });
506 return Effect.gen(function* () {
507 const gh = yield* GitHubSourceControlProvider.make;
508 yield* Effect.flip(gh.checkoutChangeRequest({ cwd: "/repo", reference: "6", force: true }));
509 assert.deepStrictEqual(git, []);
510 }).pipe(Effect.provide(layer));
511 });
512​
513 it.effect("keeps git's own output out of what a failed checkout reports", () => {
514 const { layer } = harness({
515 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
516 gitFailure: new Error("fatal: /home/me/secret-path: permission denied"),
517 graphql: () => ({ pullRequest: node(5, "feature/x") }),
518 });
519 return Effect.gen(function* () {
520 const gh = yield* GitHubSourceControlProvider.make;
521 const error = yield* gh
522 .checkoutChangeRequest({ cwd: "/repo", reference: "5" })
523 .pipe(Effect.flip);
524 assert.strictEqual(error.detail, "The pull request could not be checked out with git.");
525 assert.notInclude(error.message, "secret-path");
526 }).pipe(Effect.provide(layer));
527 });
528​
529 it("names the local branch the way gh pr checkout does", () => {
530 const name = (headRefName: string, isCrossRepository: boolean) =>
531 GitHubSourceControlProvider.pullRequestCheckoutBranchName({
532 headRefName,
533 headOwner: "someone",
534 isCrossRepository,
535 defaultBranch: "main",
536 });
537 assert.strictEqual(name("main", true), "someone/main");
538 assert.strictEqual(name("feature", true), "feature");
539 assert.strictEqual(name("main", false), "main");
540 });
541});
542​
543it("accepts active authenticated GitHub accounts when another account fails", () => {
544 const auth = GitHubSourceControlProvider.discovery.parseAuth(
545 processResult(
546 JSON.stringify({
547 hosts: {
548 "github.com": [
549 {
550 state: "success",
551 active: true,
552 host: "github.com",
553 login: "active-user",
554 tokenSource: "keyring",
555 gitProtocol: "ssh",
556 },
557 {
558 state: "error",
559 active: false,
560 host: "github.com",
561 login: "stale-user",
562 tokenSource: "keyring",
563 gitProtocol: "ssh",
564 error: "The token in keyring is invalid.",
565 },
566 ],
567 },
568 }),
569 ),
570 );
571​
572 assert.deepStrictEqual(
573 {
574 status: auth.status,
575 account: auth.account,
576 host: auth.host,
577 },
578 {
579 status: "authenticated",
580 account: Option.some("active-user"),
581 host: Option.some("github.com"),
582 },
583 );
584});
585​
586it("parses GitHub auth JSON from stdout when stderr has warnings", () => {
587 const auth = GitHubSourceControlProvider.discovery.parseAuth(
588 processResult(
589 JSON.stringify({
590 hosts: {
591 "github.com": [
592 {
593 state: "success",
594 active: true,
595 host: "github.com",
596 login: "active-user",
597 tokenSource: "keyring",
598 gitProtocol: "ssh",
599 },
600 ],
601 },
602 }),
603 { stderr: "warning: ignored diagnostic from gh\n" },
604 ),
605 );
606​
607 assert.deepStrictEqual(
608 {
609 status: auth.status,
610 account: auth.account,
611 host: auth.host,
612 },
613 {
614 status: "authenticated",
615 account: Option.some("active-user"),
616 host: Option.some("github.com"),
617 },
618 );
619});
620​
621it("parses GitHub auth status accounts by host and active state", () => {
622 assert.deepStrictEqual(
623 parseGitHubAuthStatus(
624 JSON.stringify({
625 hosts: {
626 "github.com": [
627 {
628 state: "success",
629 active: true,
630 host: "github.com",
631 login: "active-user",
632 tokenSource: "keyring",
633 gitProtocol: "ssh",
634 },
635 {
636 state: "error",
637 active: false,
638 host: "github.com",
639 login: "stale-user",
640 tokenSource: "keyring",
641 gitProtocol: "ssh",
642 },
643 ],
644 "github.example.test": [
645 {
646 state: "success",
647 active: false,
648 host: "github.example.test",
649 login: "enterprise-user",
650 tokenSource: "keyring",
651 gitProtocol: "ssh",
652 },
653 ],
654 },
655 }),
656 ).accounts,
657 [
658 {
659 host: "github.com",
660 account: "active-user",
661 authenticated: true,
662 active: true,
663 error: null,
664 environmentVariable: null,
665 },
666 {
667 host: "github.com",
668 account: "stale-user",
669 authenticated: false,
670 active: false,
671 error: null,
672 environmentVariable: null,
673 },
674 {
675 host: "github.example.test",
676 account: "enterprise-user",
677 authenticated: true,
678 active: false,
679 error: null,
680 environmentVariable: null,
681 },
682 ],
683 );
684});
685​
686it("reports unauthenticated when GitHub JSON has accounts but none are valid", () => {
687 const auth = GitHubSourceControlProvider.discovery.parseAuth(
688 processResult(
689 JSON.stringify({
690 hosts: {
691 "github.com": [
692 {
693 state: "error",
694 active: true,
695 host: "github.com",
696 login: "stale-user",
697 tokenSource: "keyring",
698 gitProtocol: "ssh",
699 error: "The token in keyring is invalid.",
700 },
701 ],
702 },
703 }),
704 ),
705 );
706​
707 assert.deepStrictEqual(
708 {
709 status: auth.status,
710 host: auth.host,
711 detail: auth.detail,
712 },
713 {
714 status: "unauthenticated",
715 host: Option.some("github.com"),
716 detail: Option.some("The token in keyring is invalid."),
717 },
718 );
719});
720​
721it("reports an update hint instead of unauthenticated when gh predates --json", () => {
722 const auth = GitHubSourceControlProvider.discovery.parseAuth(
723 processResult("", {
724 stderr: "unknown flag: --json\n\nUsage: gh auth status [flags]\n",
725 exitCode: ChildProcessSpawner.ExitCode(1),
726 }),
727 );
728​
729 assert.strictEqual(auth.status, "unknown");
730 assert.match(
731 Option.getOrElse(auth.detail, () => ""),
732 /2\.81\.0/,
733 );
734});
735​
736it.effect.each(["pull", "issues"])(
737 "resolves %s subjects on the linked host without using the checkout",
738 (kind) =>
739 Effect.gen(function* () {
740 const provider = yield* makeProvider({
741 rest: (input) => {
742 assert.strictEqual(input.host, "github.com");
743 assert.strictEqual(input.path, "repos/owner/repo/issues/42");
744 return Effect.succeed(
745 restResponse({ title: "Pairing expiry", body: "Preserve remote access", id: 1 }),
746 );
747 },
748 });
749 const lookup = provider.resolveLink?.({
750 cwd: "/unrelated",
751 url: new URL(`https://github.com/owner/repo/${kind}/42`),
752 });
753 assert.ok(lookup);
754 assert.deepStrictEqual(yield* lookup, {
755 title: "Pairing expiry",
756 body: "Preserve remote access",
757 });
758 for (const url of [
759 "https://github.com/owner/repo",
760 "https://github.attacker.test/owner/repo/issues/42",
761 ]) {
762 assert.strictEqual(
763 provider.resolveLink?.({ cwd: "/unrelated", url: new URL(url) }),
764 undefined,
765 );
766 }
767 }),
768);
769​
770it.effect.each(["read", "decode"] as const)(
771 "retains the %s failure without exposing its raw contents",
772 (stage) =>
773 Effect.gen(function* () {
774 const cause = new GitHubRequestPolicy.GitHubApiResponseError({
775 host: "github.com",
776 operation: "resolveLink",
777 status: 500,
778 });
779 const provider = yield* makeProvider({
780 rest: () =>
781 stage === "read"
782 ? Effect.fail(cause)
783 : Effect.succeed({ ...restResponse(undefined), body: "private response text" }),
784 });
785 const lookup = provider.resolveLink?.({
786 cwd: "/repo",
787 url: new URL("https://github.com/owner/repo/issues/42"),
788 });
789 assert.ok(lookup);
790 const error = yield* Effect.flip(lookup);
791 assert.strictEqual(error.operation, stage === "read" ? "resolveLink" : "resolveLink.decode");
792 assert.strictEqual(error.detail, "The linked subject could not be read.");
793 assert.notInclude(error.message, "private response text");
794 if (stage === "read") assert.strictEqual(error.cause, cause);
795 else assert.propertyVal(error.cause, "_tag", "SchemaError");
796 }),
797);
798​
799const multiAccountStatus = (extra: ReadonlyArray<Record<string, unknown>> = []) =>
800 processResult(
801 JSON.stringify({
802 hosts: {
803 "github.com": [
804 { state: "success", active: true, host: "github.com", login: "personal" },
805 { state: "success", active: false, host: "github.com", login: "work" },
806 ...extra,
807 ],
808 "ghe.acme.test": [
809 { state: "error", active: true, host: "ghe.acme.test", login: "jm", error: "expired" },
810 ],
811 },
812 }),
813 );
814​
815it("reports every gh login and leads with the account Settings pin", () => {
816 const auth = GitHubSourceControlProvider.parseGitHubAuth(multiAccountStatus(), {
817 hosts: { "github.com": { account: "work", enabled: true } },
818 tokens: {},
819 });
820 assert.deepStrictEqual(auth.account, Option.some("work"));
821 assert.deepStrictEqual(auth.accounts, [
822 { host: "github.com", account: "personal", active: true, authenticated: true },
823 { host: "github.com", account: "work", active: false, authenticated: true },
824 { host: "ghe.acme.test", account: "jm", active: true, authenticated: false, error: "expired" },
825 ]);
826});
827​
828it("reports unauthenticated when Settings turn off every signed-in host", () => {
829 const auth = GitHubSourceControlProvider.parseGitHubAuth(multiAccountStatus(), {
830 hosts: { "github.com": { enabled: false } },
831 tokens: {},
832 });
833 assert.strictEqual(auth.status, "unauthenticated");
834 assert.deepStrictEqual(
835 auth.detail,
836 Option.some("Every GitHub host gh is signed in to is turned off in Settings → Source Control."),
837 );
838});
839​
840it("names the environment token that overrides the Settings choice", () => {
841 const auth = GitHubSourceControlProvider.parseGitHubAuth(
842 multiAccountStatus([
843 {
844 state: "success",
845 active: false,
846 host: "github.com",
847 login: "bot",
848 tokenSource: "GH_TOKEN",
849 },
850 ]),
851 { hosts: { "github.com": { account: "work", enabled: true } }, tokens: {} },
852 );
853 assert.deepStrictEqual(auth.account, Option.some("bot"));
854 assert.deepStrictEqual(
855 auth.detail,
856 Option.some(
857 "Using GH_TOKEN from the server environment; it overrides the account chosen in Settings.",
858 ),
859 );
860 assert.strictEqual(auth.accounts?.[2]?.environmentVariable, "GH_TOKEN");
861});
862​
863it.live.each([
864 "git@code.example.test:team/project.git",
865 "ssh://git@code.example.test/team/project.git",
866 "https://code.example.test/team/project.git",
867])("keeps Enterprise operations on the selected remote: %s", (remoteUrl) => {
868 const rest: GitHubRest.GitHubRestInput[] = [];
869 const pr = {
870 ...node(42, "feature", "team"),
871 url: "https://code.example.test/team/project/pull/42",
872 isCrossRepository: false,
873 headRepository: { name: "project", nameWithOwner: "team/project" },
874 };
875 const api = {
876 rest: (input: GitHubRest.GitHubRestInput) =>
877 Effect.sync(() => {
878 rest.push(input);
879 return restResponse({
880 full_name: "team/project",
881 html_url: `https://${input.host}/team/project`,
882 ssh_url: `git@${input.host}:team/project.git`,
883 default_branch: "main",
884 });
885 }),
886 };
887 const { layer, git, graphqlCalls } = harness({
888 remotes: remotesOutput(
889 ["origin", "git@github.com:team/project.git"],
890 ["enterprise", remoteUrl],
891 ),
892 api,
893 graphql: (_, call) =>
894 call.operationName === "PullRequestByNumber"
895 ? { pullRequest: pr }
896 : { pullRequests: { nodes: [pr] } },
897 });
898 return Effect.gen(function* () {
899 const provider = yield* GitHubSourceControlProvider.make;
900 const fs = yield* FileSystem.FileSystem;
901 const bodyFile = yield* fs.makeTempFileScoped({ suffix: ".md" });
902 yield* fs.writeFileString(bodyFile, "Enterprise PR");
903 const input = {
904 cwd: "/repo",
905 context: {
906 provider: {
907 kind: SourceControlProviderKind.make("github"),
908 name: "GitHub Self-Hosted",
909 baseUrl: "https://code.example.test",
910 },
911 remoteName: "enterprise",
912 remoteUrl,
913 },
914 };
915 for (const state of ["open", "closed"] as const) {
916 const prs = yield* provider.listChangeRequests({
917 ...input,
918 state,
919 headSelector: "feature",
920 });
921 assert.strictEqual(prs[0]?.url, "https://code.example.test/team/project/pull/42");
922 }
923 yield* provider.getChangeRequest({ ...input, reference: "42" });
924 yield* provider.getChangeRequest({ ...input, reference: "feature" });
925 yield* provider.createChangeRequest({
926 ...input,
927 baseRefName: "main",
928 headSelector: "feature",
929 title: "PR",
930 bodyFile,
931 });
932 assert.strictEqual(yield* provider.getDefaultBranch(input), "main");
933 yield* provider.checkoutChangeRequest({ ...input, reference: "42" });
934 yield* provider.getRepositoryCloneUrls({ ...input, repository: "team/other" });
935 yield* provider.getRepositoryCloneUrls({ ...input, repository: "github.com/team/explicit" });
936 const lookups = graphqlCalls.flatMap((call) =>
937 call.lookups.map(({ owner, name }) => [call.host, owner, name]),
938 );
939 assert.deepStrictEqual(
940 lookups,
941 Array.from({ length: 5 }, () => ["code.example.test", "team", "project"]),
942 );
943 assert.deepStrictEqual(
944 rest.map(({ host, path }) => [host, path]),
945 [
946 ["code.example.test", "repos/team/project/pulls"],
947 ["code.example.test", "repos/team/project"],
948 ["code.example.test", "repos/team/other"],
949 ["github.com", "repos/team/explicit"],
950 ],
951 );
952 assert.deepStrictEqual(git.find(([name]) => name === "fetchRemoteTrackingBranch")?.[1], {
953 cwd: "/repo",
954 remoteName: "enterprise",
955 remoteBranch: "feature",
956 });
957 }).pipe(Effect.provide(layer), Effect.provideService(HostProcess.Environment, {}), Effect.scoped);
958});
959​
960it.effect.each([
961 { host: "github.com", resolved: "", envRepository: "", expected: "acme/web" },
962 {
963 host: "code.example.test",
964 resolved: "remote.origin.gh-resolved base",
965 envRepository: "",
966 expected: "me/web",
967 },
968 {
969 host: "github.com",
970 resolved: "remote.upstream.gh-resolved acme/other",
971 envRepository: "",
972 expected: "acme/other",
973 },
974 {
975 host: "code.example.test",
976 resolved: "",
977 envRepository: "chosen/repo",
978 expected: "chosen/repo",
979 },
980])(
981 "preserves repository precedence on $host: $resolved $envRepository",
982 ({ host, resolved, envRepository, expected }) => {
983 const targets: string[] = [];
984 const { layer } = harness({
985 remotes: remotesOutput(
986 ["origin", `git@${host}:me/web.git`],
987 ["upstream", `git@${host}:acme/web.git`],
988 ),
989 resolved,
990 api: {
991 rest: (input) =>
992 Effect.sync(() => {
993 targets.push(`${input.host}/${input.path}`);
994 return restResponse({
995 full_name: expected,
996 html_url: `https://${host}/${expected}`,
997 ssh_url: `git@${host}:${expected}.git`,
998 default_branch: "main",
999 });
1000 }),
1001 },
1002 });
1003 return Effect.gen(function* () {
1004 const provider = yield* GitHubSourceControlProvider.make;
1005 const fs = yield* FileSystem.FileSystem;
1006 const bodyFile = yield* fs.makeTempFileScoped();
1007 yield* fs.writeFileString(bodyFile, "Body");
1008 const input = {
1009 cwd: "/repo",
1010 context: {
1011 provider: {
1012 kind: SourceControlProviderKind.make("github"),
1013 name: "GitHub",
1014 baseUrl: `https://${host}`,
1015 },
1016 remoteName: "origin",
1017 remoteUrl: `git@${host}:me/web.git`,
1018 },
1019 };
1020 yield* provider.getDefaultBranch(input);
1021 yield* provider.createChangeRequest({
1022 ...input,
1023 baseRefName: "main",
1024 headSelector: "me:feature",
1025 title: "PR",
1026 bodyFile,
1027 });
1028 assert.deepStrictEqual(targets, [
1029 `${host}/repos/${expected}`,
1030 `${host}/repos/${expected}/pulls`,
1031 ]);
1032 }).pipe(
1033 Effect.provide(layer),
1034 Effect.provideService(HostProcess.Environment, { GH_REPO: envRepository }),
1035 Effect.scoped,
1036 );
1037 },
1039​
1040it.effect("says a GH_REPO naming an unparseable host targets no remote rather than failing", () => {
1041 const { layer } = harness({
1042 remotes: remotesOutput(["upstream", "git@github.com:acme/web.git"]),
1043 resolved: "",
1044 api: {},
1045 });
1046 return Effect.gen(function* () {
1047 const provider = yield* GitHubSourceControlProvider.make;
1048 const targets = yield* provider.createsChangeRequestsIn!({
1049 cwd: "/repo",
1050 context: {
1051 provider: {
1052 kind: SourceControlProviderKind.make("github"),
1053 name: "GitHub",
1054 baseUrl: "https://github.com",
1055 },
1056 remoteName: "upstream",
1057 remoteUrl: "git@github.com:acme/web.git",
1058 },
1059 repository: "acme/web",
1060 });
1061 assert.isFalse(targets);
1062 }).pipe(
1063 Effect.provide(layer),
1064 Effect.provideService(HostProcess.Environment, { GH_REPO: "bad host/acme/web" }),
1065 );
1066});