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

GitHubSourceControlProvider.test.ts

1,227 lines40.3 KB

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