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

GitHubSourceControlProvider.test.ts

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