Open History to see the last commit
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>>>;
96}
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 );
153}
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 };
253}
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 assert.include((yield* Fiber.join(missing)).detail, "No GitHub credential on the server");
548 signedIn = true;
549 const limited = yield* read("limited");
550 yield* TestClock.adjust("500 millis");
551 const error = yield* Fiber.join(limited);
552 assert.include(error.detail, "rate limit exceeded");
553 assert.propertyVal(error.cause, "retryAt", 123_000);
554 }).pipe(Effect.provide(layer));
555 });
556});
557
558describe("GitHubSourceControlProvider.getChangeRequest", () => {
559 it.effect("reads a pull request by number, and by URL on its own repository", () => {
560 const { layer, graphqlCalls } = harness({
561 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
562 graphql: () => ({ pullRequest: { ...node(42, "feature"), baseRefName: "main\u00a0" } }),
563 });
564 return Effect.gen(function* () {
565 const gh = yield* GitHubSourceControlProvider.make;
566 const pr = yield* gh.getChangeRequest({ cwd: "/repo", reference: "#42" });
567 assert.strictEqual(pr.number, 42);
568 assert.strictEqual(pr.baseRefName, "main\u00a0");
569 yield* gh.getChangeRequest({
570 cwd: "/repo",
571 reference: "https://github.com/other/thing/pull/42",
572 });
573 assert.deepStrictEqual(
574 graphqlCalls.flatMap((call) => call.lookups),
575 [
576 { owner: "acme", name: "web", number: 42 },
577 { owner: "other", name: "thing", number: 42 },
578 ],
579 );
580 }).pipe(Effect.provide(layer));
581 });
582});
583
584describe("GitHubSourceControlProvider writes", () => {
585 it.effect("creates a cross-repository pull request with an owner:branch head", () => {
586 const requests: Array<GitHubRest.GitHubRestInput> = [];
587 const { layer } = harness({
588 remotes: remotesOutput(
589 ["origin", "git@github.com:me/web.git"],
590 ["upstream", "git@github.com:acme/web.git"],
591 ),
592 api: {
593 rest: (input) =>
594 Effect.sync(() => {
595 requests.push(input);
596 return restResponse({ number: 1 }, 201);
597 }),
598 },
599 });
600 return Effect.gen(function* () {
601 const fs = yield* FileSystem.FileSystem;
602 const bodyFile = yield* fs.makeTempFileScoped({ suffix: ".md" });
603 yield* fs.writeFileString(bodyFile, "Body");
604 const gh = yield* GitHubSourceControlProvider.make;
605 yield* gh.createChangeRequest({
606 cwd: "/repo",
607 baseRefName: "main",
608 headSelector: "me:feature",
609 title: "Title",
610 bodyFile,
611 });
612 assert.strictEqual(requests[0]!.method, "POST");
613 assert.strictEqual(requests[0]!.path, "repos/acme/web/pulls");
614 assert.strictEqual(requests[0]!.allowReserve, true);
615 assert.deepStrictEqual(requests[0]!.body, {
616 base: "main",
617 head: "me:feature",
618 title: "Title",
619 body: "Body",
620 maintainer_can_modify: true,
621 });
622 yield* gh.createChangeRequest({
623 cwd: "/repo",
624 baseRefName: "main",
625 headSelector: "me:feature",
626 title: "Title",
627 bodyFile,
628 draft: true,
629 });
630 assert.strictEqual((requests[1]!.body as { draft?: unknown }).draft, true);
631 }).pipe(Effect.provide(Layer.merge(layer, NodeServices.layer)));
632 });
633
634 it.effect("creates a repository under an organization the viewer is not", () => {
635 const requests: Array<string> = [];
636 const { layer } = harness({
637 remotes: "",
638 api: {
639 rest: (input) =>
640 Effect.sync(() => {
641 requests.push(`${input.method ?? "GET"} ${input.path}`);
642 return input.path === "user"
643 ? restResponse({ login: "me" })
644 : restResponse({
645 full_name: "acme/new",
646 html_url: "https://github.com/acme/new",
647 ssh_url: "git@github.com:acme/new.git",
648 });
649 }),
650 },
651 });
652 return Effect.gen(function* () {
653 const gh = yield* GitHubSourceControlProvider.make;
654 const urls = yield* gh.createRepository({
655 cwd: "/repo",
656 repository: "acme/new",
657 visibility: "private",
658 });
659 assert.deepStrictEqual(urls, {
660 nameWithOwner: "acme/new",
661 url: "https://github.com/acme/new",
662 sshUrl: "git@github.com:acme/new.git",
663 });
664 assert.deepStrictEqual(requests, ["GET user", "POST orgs/acme/repos"]);
665 }).pipe(Effect.provide(layer));
666 });
667
668 it.effect("looks up a bare repository name under the signed-in account on that host", () => {
669 const requests: Array<string> = [];
670 return Effect.gen(function* () {
671 const gh = yield* makeProvider({
672 rest: (input) =>
673 Effect.sync(() => {
674 requests.push(`${input.host} ${input.method ?? "GET"} ${input.path}`);
675 return input.path === "user"
676 ? restResponse({ login: "me" })
677 : restResponse({
678 full_name: "me/notes",
679 html_url: `https://${input.host}/me/notes`,
680 ssh_url: `git@${input.host}:me/notes.git`,
681 });
682 }),
683 });
684
685 const urls = yield* gh.getRepositoryCloneUrls({
686 cwd: "/repo",
687 context: githubContext("code.example.test"),
688 repository: " notes.git ",
689 });
690
691 assert.deepStrictEqual(urls, {
692 nameWithOwner: "me/notes",
693 url: "https://code.example.test/me/notes",
694 sshUrl: "git@code.example.test:me/notes.git",
695 });
696 assert.deepStrictEqual(requests, [
697 "code.example.test GET user",
698 "code.example.test GET repos/me/notes",
699 ]);
700 for (const repository of ["me/", "/notes", "a/b/c/d", "", "two words"]) {
701 const error = yield* Effect.flip(gh.getRepositoryCloneUrls({ cwd: "/repo", repository }));
702 assert.include(error.message, "Repositories are named owner/name.");
703 assert.strictEqual(
704 userFacingSourceControlDetail(error.cause),
705 "Repositories are named owner/name.",
706 );
707 }
708 assert.strictEqual(requests.length, 2);
709 });
710 });
711 it.effect("exposes only fixed repository lookup details with the resolved owner", () =>
712 Effect.gen(function* () {
713 const gh = yield* makeProvider({
714 rest: (input) =>
715 input.path === "user"
716 ? Effect.succeed(restResponse({ login: "me" }))
717 : input.path === "repos/me/private"
718 ? Effect.fail(
719 new GitHubRequestPolicy.GitHubApiAuthenticationError({
720 host: input.host,
721 operation: input.operation,
722 }),
723 )
724 : Effect.fail(
725 new GitHubRequestPolicy.GitHubApiNotFoundError({
726 host: input.host,
727 operation: input.operation,
728 }),
729 ),
730 });
731 for (const repository of ["vouch", "other/vouch"]) {
732 const error = yield* Effect.flip(gh.getRepositoryCloneUrls({ cwd: "/repo", repository }));
733 assert.strictEqual(
734 userFacingSourceControlDetail(error.cause),
735 `Repository ${repository === "vouch" ? "me/vouch" : repository} was not found. Check the owner and name and try again.`,
736 );
737 }
738 const authError = yield* Effect.flip(
739 gh.getRepositoryCloneUrls({ cwd: "/repo", repository: "me/private" }),
740 );
741 assert.strictEqual(userFacingSourceControlDetail(authError.cause), undefined);
742 }),
743 );
744});
745
746describe("GitHubSourceControlProvider.checkoutChangeRequest", () => {
747 it.effect("refuses a fork checkout when the base's default branch cannot be read", () => {
748 const { layer, git } = harness({
749 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
750 localBranches: ["main"],
751 graphql: () => ({ pullRequest: node(6, "main", "someone") }),
752 api: {
753 rest: () =>
754 Effect.fail(
755 new GitHubRequestPolicy.GitHubApiRequestError({
756 host: "github.com",
757 operation: "x",
758 cause: "offline",
759 }),
760 ),
761 },
762 });
763 return Effect.gen(function* () {
764 const gh = yield* GitHubSourceControlProvider.make;
765 yield* Effect.flip(gh.checkoutChangeRequest({ cwd: "/repo", reference: "6", force: true }));
766 assert.deepStrictEqual(git, []);
767 }).pipe(Effect.provide(layer));
768 });
769
770 it.effect("adds a fork remote with the protocol of the URL origin fetches from", () => {
771 // `git remote -v` shows origin's SSH `insteadOf` rewrite; config holds HTTPS, then an SSH push URL.
772 const { layer, git } = harness({
773 remotes: [
774 "origin\tgit@github.com:acme/web.git (fetch)",
775 "origin\tgit@github.com:acme/web.git (push)",
776 "origin\tgit@github.com:acme/web.git (push)",
777 ].join("\n"),
778 originUrls: "https://github.com/acme/web.git\ngit@github.com:acme/web.git\n",
779 graphql: () => ({ pullRequest: node(7, "feature", "someone") }),
780 api: {
781 rest: (input) => {
782 const fullName = input.path.slice("repos/".length);
783 return Effect.succeed(
784 restResponse({
785 full_name: fullName,
786 html_url: `https://github.com/${fullName}`,
787 ssh_url: `git@github.com:${fullName}.git`,
788 default_branch: "main",
789 }),
790 );
791 },
792 },
793 });
794 return Effect.gen(function* () {
795 const gh = yield* GitHubSourceControlProvider.make;
796 yield* gh.checkoutChangeRequest({ cwd: "/repo", reference: "7" });
797 assert.deepStrictEqual(git.find(([name]) => name === "ensureRemote")?.[1], {
798 cwd: "/repo",
799 preferredName: "someone",
800 url: "https://github.com/someone/web",
801 });
802 }).pipe(Effect.provide(layer));
803 });
804
805 it.effect("keeps git's own output out of what a failed checkout reports", () => {
806 const { layer } = harness({
807 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
808 gitFailure: new Error("fatal: /home/me/secret-path: permission denied"),
809 graphql: () => ({ pullRequest: node(5, "feature/x") }),
810 });
811 return Effect.gen(function* () {
812 const gh = yield* GitHubSourceControlProvider.make;
813 const error = yield* gh
814 .checkoutChangeRequest({ cwd: "/repo", reference: "5" })
815 .pipe(Effect.flip);
816 assert.strictEqual(error.detail, "The pull request could not be checked out with git.");
817 assert.notInclude(error.message, "secret-path");
818 }).pipe(Effect.provide(layer));
819 });
820
821 it.effect("records the branch base for gh through the host's config write", () => {
822 const { layer, git } = harness({
823 remotes: remotesOutput(["origin", "git@github.com:acme/web.git"]),
824 });
825 return Effect.gen(function* () {
826 const gh = yield* GitHubSourceControlProvider.make;
827 yield* gh.recordBranchBase!({ cwd: "/repo", branch: "feature", baseBranch: "main" });
828 assert.deepStrictEqual(git, [
829 ["writeConfigValue", { cwd: "/repo", key: "branch.feature.gh-merge-base", value: "main" }],
830 ]);
831 }).pipe(Effect.provide(layer));
832 });
833
834 it("names the local branch the way gh pr checkout does", () => {
835 const name = (headRefName: string, isCrossRepository: boolean) =>
836 GitHubSourceControlProvider.pullRequestCheckoutBranchName({
837 headRefName,
838 headOwner: "someone",
839 isCrossRepository,
840 defaultBranch: "main",
841 });
842 assert.strictEqual(name("main", true), "someone/main");
843 assert.strictEqual(name("feature", true), "feature");
844 assert.strictEqual(name("main", false), "main");
845 });
846});
847
848it("accepts active authenticated GitHub accounts when another account fails", () => {
849 const auth = GitHubSourceControlProvider.discovery.parseAuth(
850 processResult(
851 JSON.stringify({
852 hosts: {
853 "github.com": [
854 {
855 state: "success",
856 active: true,
857 host: "github.com",
858 login: "active-user",
859 tokenSource: "keyring",
860 gitProtocol: "ssh",
861 },
862 {
863 state: "error",
864 active: false,
865 host: "github.com",
866 login: "stale-user",
867 tokenSource: "keyring",
868 gitProtocol: "ssh",
869 error: "The token in keyring is invalid.",
870 },
871 ],
872 },
873 }),
874 ),
875 );
876
877 assert.deepStrictEqual(
878 {
879 status: auth.status,
880 account: auth.account,
881 host: auth.host,
882 },
883 {
884 status: "authenticated",
885 account: Option.some("active-user"),
886 host: Option.some("github.com"),
887 },
888 );
889});
890
891it("parses GitHub auth JSON from stdout when stderr has warnings", () => {
892 const auth = GitHubSourceControlProvider.discovery.parseAuth(
893 processResult(
894 JSON.stringify({
895 hosts: {
896 "github.com": [
897 {
898 state: "success",
899 active: true,
900 host: "github.com",
901 login: "active-user",
902 tokenSource: "keyring",
903 gitProtocol: "ssh",
904 },
905 ],
906 },
907 }),
908 { stderr: "warning: ignored diagnostic from gh\n" },
909 ),
910 );
911
912 assert.deepStrictEqual(
913 {
914 status: auth.status,
915 account: auth.account,
916 host: auth.host,
917 },
918 {
919 status: "authenticated",
920 account: Option.some("active-user"),
921 host: Option.some("github.com"),
922 },
923 );
924});
925
926it("parses GitHub auth status accounts by host and active state", () => {
927 assert.deepStrictEqual(
928 parseGitHubAuthStatus(
929 JSON.stringify({
930 hosts: {
931 "github.com": [
932 {
933 state: "success",
934 active: true,
935 host: "github.com",
936 login: "active-user",
937 tokenSource: "keyring",
938 gitProtocol: "ssh",
939 },
940 {
941 state: "error",
942 active: false,
943 host: "github.com",
944 login: "stale-user",
945 tokenSource: "keyring",
946 gitProtocol: "ssh",
947 },
948 ],
949 "github.example.test": [
950 {
951 state: "success",
952 active: false,
953 host: "github.example.test",
954 login: "enterprise-user",
955 tokenSource: "keyring",
956 gitProtocol: "ssh",
957 },
958 ],
959 },
960 }),
961 ).accounts,
962 [
963 {
964 host: "github.com",
965 account: "active-user",
966 authenticated: true,
967 active: true,
968 error: null,
969 environmentVariable: null,
970 },
971 {
972 host: "github.com",
973 account: "stale-user",
974 authenticated: false,
975 active: false,
976 error: null,
977 environmentVariable: null,
978 },
979 {
980 host: "github.example.test",
981 account: "enterprise-user",
982 authenticated: true,
983 active: false,
984 error: null,
985 environmentVariable: null,
986 },
987 ],
988 );
989});
990
991it("reports unauthenticated when GitHub JSON has accounts but none are valid", () => {
992 const auth = GitHubSourceControlProvider.discovery.parseAuth(
993 processResult(
994 JSON.stringify({
995 hosts: {
996 "github.com": [
997 {
998 state: "error",
999 active: true,
1000 host: "github.com",
1001 login: "stale-user",
1002 tokenSource: "keyring",
1003 gitProtocol: "ssh",
1004 error: "The token in keyring is invalid.",
1005 },
1006 ],
1007 },
1008 }),
1009 ),
1010 );
1011
1012 assert.deepStrictEqual(
1013 {
1014 status: auth.status,
1015 host: auth.host,
1016 detail: auth.detail,
1017 },
1018 {
1019 status: "unauthenticated",
1020 host: Option.some("github.com"),
1021 detail: Option.some("The token in keyring is invalid."),
1022 },
1023 );
1024});
1025
1026it("reports an update hint instead of unauthenticated when gh predates --json", () => {
1027 const auth = GitHubSourceControlProvider.discovery.parseAuth(
1028 processResult("", {
1029 stderr: "unknown flag: --json\n\nUsage: gh auth status [flags]\n",
1030 exitCode: ChildProcessSpawner.ExitCode(1),
1031 }),
1032 );
1033
1034 assert.strictEqual(auth.status, "unknown");
1035 assert.match(
1036 Option.getOrElse(auth.detail, () => ""),
1037 /2\.81\.0/,
1038 );
1039});
1040
1041it.effect.each(["pull", "issues"])(
1042 "resolves %s subjects on the linked host without using the checkout",
1043 (kind) =>
1044 Effect.gen(function* () {
1045 const provider = yield* makeProvider({
1046 rest: (input) => {
1047 assert.strictEqual(input.host, "github.com");
1048 assert.strictEqual(input.path, "repos/owner/repo/issues/42");
1049 return Effect.succeed(
1050 restResponse({ title: "Pairing expiry", body: "Preserve remote access", id: 1 }),
1051 );
1052 },
1053 });
1054 const lookup = provider.resolveLink?.({
1055 cwd: "/unrelated",
1056 url: new URL(`https://github.com/owner/repo/${kind}/42`),
1057 });
1058 assert.ok(lookup);
1059 assert.deepStrictEqual(yield* lookup, {
1060 title: "Pairing expiry",
1061 body: "Preserve remote access",
1062 });
1063 for (const url of [
1064 "https://github.com/owner/repo",
1065 "https://github.attacker.test/owner/repo/issues/42",
1066 ]) {
1067 assert.strictEqual(
1068 provider.resolveLink?.({ cwd: "/unrelated", url: new URL(url) }),
1069 undefined,
1070 );
1071 }
1072 }),
1073);
1074
1075it.effect.each(["read", "decode"] as const)(
1076 "retains the %s failure without exposing its raw contents",
1077 (stage) =>
1078 Effect.gen(function* () {
1079 const cause = new GitHubRequestPolicy.GitHubApiResponseError({
1080 host: "github.com",
1081 operation: "resolveLink",
1082 status: 500,
1083 });
1084 const provider = yield* makeProvider({
1085 rest: () =>
1086 stage === "read"
1087 ? Effect.fail(cause)
1088 : Effect.succeed({ ...restResponse(undefined), body: "private response text" }),
1089 });
1090 const lookup = provider.resolveLink?.({
1091 cwd: "/repo",
1092 url: new URL("https://github.com/owner/repo/issues/42"),
1093 });
1094 assert.ok(lookup);
1095 const error = yield* Effect.flip(lookup);
1096 assert.strictEqual(error.operation, stage === "read" ? "resolveLink" : "resolveLink.decode");
1097 assert.strictEqual(error.detail, "The linked subject could not be read.");
1098 assert.notInclude(error.message, "private response text");
1099 if (stage === "read") assert.strictEqual(error.cause, cause);
1100 else assert.propertyVal(error.cause, "_tag", "SchemaError");
1101 }),
1102);
1103
1104const multiAccountStatus = (extra: ReadonlyArray<Record<string, unknown>> = []) =>
1105 processResult(
1106 JSON.stringify({
1107 hosts: {
1108 "github.com": [
1109 { state: "success", active: true, host: "github.com", login: "personal" },
1110 { state: "success", active: false, host: "github.com", login: "work" },
1111 ...extra,
1112 ],
1113 "ghe.acme.test": [
1114 { state: "error", active: true, host: "ghe.acme.test", login: "jm", error: "expired" },
1115 ],
1116 },
1117 }),
1118 );
1119
1120it("reports every gh login and leads with the account Settings pin", () => {
1121 const auth = GitHubSourceControlProvider.parseGitHubAuth(multiAccountStatus(), {
1122 hosts: { "github.com": { account: "work", enabled: true } },
1123 tokens: {},
1124 signIns: {},
1125 });
1126 assert.deepStrictEqual(auth.account, Option.some("work"));
1127 assert.deepStrictEqual(auth.accounts, [
1128 { host: "github.com", account: "personal", active: true, authenticated: true },
1129 { host: "github.com", account: "work", active: false, authenticated: true },
1130 { host: "ghe.acme.test", account: "jm", active: true, authenticated: false, error: "expired" },
1131 ]);
1132});
1133
1134it("reports unauthenticated when Settings turn off every signed-in host", () => {
1135 const auth = GitHubSourceControlProvider.parseGitHubAuth(multiAccountStatus(), {
1136 hosts: { "github.com": { enabled: false } },
1137 tokens: {},
1138 signIns: {},
1139 });
1140 assert.strictEqual(auth.status, "unauthenticated");
1141 assert.deepStrictEqual(
1142 auth.detail,
1143 Option.some(
1144 "Every GitHub host gh is signed in to is turned off in Settings → Source control & issues.",
1145 ),
1146 );
1147});
1148
1149it("names the environment token that overrides the Settings choice", () => {
1150 const auth = GitHubSourceControlProvider.parseGitHubAuth(
1151 multiAccountStatus([
1152 {
1153 state: "success",
1154 active: false,
1155 host: "github.com",
1156 login: "bot",
1157 tokenSource: "GH_TOKEN",
1158 },
1159 ]),
1160 { hosts: { "github.com": { account: "work", enabled: true } }, tokens: {}, signIns: {} },
1161 );
1162 assert.deepStrictEqual(auth.account, Option.some("bot"));
1163 assert.deepStrictEqual(
1164 auth.detail,
1165 Option.some(
1166 "Using GH_TOKEN from the server environment; it overrides the account chosen in Settings.",
1167 ),
1168 );
1169 assert.strictEqual(auth.accounts?.[2]?.environmentVariable, "GH_TOKEN");
1170});
1171
1172it.live.each([
1173 "git@code.example.test:team/project.git",
1174 "ssh://git@code.example.test/team/project.git",
1175 "https://code.example.test/team/project.git",
1176])("keeps Enterprise operations on the selected remote: %s", (remoteUrl) => {
1177 const rest: GitHubRest.GitHubRestInput[] = [];
1178 const pr = {
1179 ...node(42, "feature", "team"),
1180 url: "https://code.example.test/team/project/pull/42",
1181 isCrossRepository: false,
1182 headRepository: { name: "project", nameWithOwner: "team/project" },
1183 };
1184 const api = {
1185 rest: (input: GitHubRest.GitHubRestInput) =>
1186 Effect.sync(() => {
1187 rest.push(input);
1188 return restResponse({
1189 full_name: "team/project",
1190 html_url: `https://${input.host}/team/project`,
1191 ssh_url: `git@${input.host}:team/project.git`,
1192 default_branch: "main",
1193 });
1194 }),
1195 };
1196 const { layer, git, graphqlCalls } = harness({
1197 remotes: remotesOutput(
1198 ["origin", "git@github.com:team/project.git"],
1199 ["enterprise", remoteUrl],
1200 ),
1201 api,
1202 graphql: (_, call) =>
1203 call.operationName === "PullRequestByNumber"
1204 ? { pullRequest: pr }
1205 : { pullRequests: { nodes: [pr] } },
1206 });
1207 return Effect.gen(function* () {
1208 const provider = yield* GitHubSourceControlProvider.make;
1209 const fs = yield* FileSystem.FileSystem;
1210 const bodyFile = yield* fs.makeTempFileScoped({ suffix: ".md" });
1211 yield* fs.writeFileString(bodyFile, "Enterprise PR");
1212 const input = {
1213 cwd: "/repo",
1214 context: {
1215 provider: {
1216 kind: SourceControlProviderKind.make("github"),
1217 name: "GitHub Self-Hosted",
1218 baseUrl: "https://code.example.test",
1219 },
1220 remoteName: "enterprise",
1221 remoteUrl,
1222 },
1223 };
1224 for (const state of ["open", "closed"] as const) {
1225 const prs = yield* provider.listChangeRequests({
1226 ...input,
1227 state,
1228 headSelector: "feature",
1229 });
1230 assert.strictEqual(prs[0]?.url, "https://code.example.test/team/project/pull/42");
1231 }
1232 yield* provider.getChangeRequest({ ...input, reference: "42" });
1233 yield* provider.getChangeRequest({ ...input, reference: "feature" });
1234 yield* provider.createChangeRequest({
1235 ...input,
1236 baseRefName: "main",
1237 headSelector: "feature",
1238 title: "PR",
1239 bodyFile,
1240 });
1241 assert.strictEqual(yield* provider.getDefaultBranch(input), "main");
1242 yield* provider.checkoutChangeRequest({ ...input, reference: "42" });
1243 yield* provider.getRepositoryCloneUrls({ ...input, repository: "team/other" });
1244 yield* provider.getRepositoryCloneUrls({ ...input, repository: "github.com/team/explicit" });
1245 const lookups = graphqlCalls.flatMap((call) =>
1246 call.lookups.map(({ owner, name }) => [call.host, owner, name]),
1247 );
1248 assert.deepStrictEqual(
1249 lookups,
1250 Array.from({ length: 5 }, () => ["code.example.test", "team", "project"]),
1251 );
1252 assert.deepStrictEqual(
1253 rest.map(({ host, path }) => [host, path]),
1254 [
1255 ["code.example.test", "repos/team/project/pulls"],
1256 ["code.example.test", "repos/team/project"],
1257 ["code.example.test", "repos/team/other"],
1258 ["github.com", "repos/team/explicit"],
1259 ],
1260 );
1261 assert.deepStrictEqual(git.find(([name]) => name === "createBranch")?.[1], {
1262 cwd: "/repo",
1263 branch: "feature",
1264 startPoint: "refs/remotes/enterprise/feature",
1265 });
1266 assert.deepStrictEqual(git.find(([name]) => name === "fetchRemoteTrackingBranch")?.[1], {
1267 cwd: "/repo",
1268 remoteName: "enterprise",
1269 remoteBranch: "feature",
1270 });
1271 }).pipe(Effect.provide(layer), Effect.provideService(HostProcess.Environment, {}));
1272});
1273
1274it.effect.each([
1275 { host: "github.com", resolved: "", envRepository: "", expected: "acme/web" },
1276 {
1277 host: "code.example.test",
1278 resolved: "remote.origin.gh-resolved base",
1279 envRepository: "",
1280 expected: "me/web",
1281 },
1282 {
1283 host: "github.com",
1284 resolved: "remote.upstream.gh-resolved acme/other",
1285 envRepository: "",
1286 expected: "acme/other",
1287 },
1288 {
1289 host: "code.example.test",
1290 resolved: "",
1291 envRepository: "chosen/repo",
1292 expected: "chosen/repo",
1293 },
1294])(
1295 "preserves repository precedence on $host: $resolved $envRepository",
1296 ({ host, resolved, envRepository, expected }) => {
1297 const targets: string[] = [];
1298 const { layer } = harness({
1299 remotes: remotesOutput(
1300 ["origin", `git@${host}:me/web.git`],
1301 ["upstream", `git@${host}:acme/web.git`],
1302 ),
1303 resolved,
1304 api: {
1305 rest: (input) =>
1306 Effect.sync(() => {
1307 targets.push(`${input.host}/${input.path}`);
1308 return restResponse({
1309 full_name: expected,
1310 html_url: `https://${host}/${expected}`,
1311 ssh_url: `git@${host}:${expected}.git`,
1312 default_branch: "main",
1313 });
1314 }),
1315 },
1316 });
1317 return Effect.gen(function* () {
1318 const provider = yield* GitHubSourceControlProvider.make;
1319 const fs = yield* FileSystem.FileSystem;
1320 const bodyFile = yield* fs.makeTempFileScoped();
1321 yield* fs.writeFileString(bodyFile, "Body");
1322 const input = {
1323 cwd: "/repo",
1324 context: {
1325 provider: {
1326 kind: SourceControlProviderKind.make("github"),
1327 name: "GitHub",
1328 baseUrl: `https://${host}`,
1329 },
1330 remoteName: "origin",
1331 remoteUrl: `git@${host}:me/web.git`,
1332 },
1333 };
1334 yield* provider.getDefaultBranch(input);
1335 yield* provider.createChangeRequest({
1336 ...input,
1337 baseRefName: "main",
1338 headSelector: "me:feature",
1339 title: "PR",
1340 bodyFile,
1341 });
1342 assert.deepStrictEqual(targets, [
1343 `${host}/repos/${expected}`,
1344 `${host}/repos/${expected}/pulls`,
1345 ]);
1346 assert.deepStrictEqual(
1347 yield* provider.createsChangeRequestsIn!({ ...input, repository: "me/web" }),
1348 expected === "me/web",
1349 );
1350 }).pipe(
1351 Effect.provide(layer),
1352 Effect.provideService(HostProcess.Environment, { GH_REPO: envRepository }),
1353 );
1354 },
1355);
1356
1357it.effect("says a GH_REPO naming a renamed remote's current name targets that remote", () => {
1358 // GitHub serves a renamed repository under both names with one id.
1359 const repository = restResponse({
1360 id: 1153130349,
1361 full_name: "octo/new-name",
1362 html_url: "https://github.com/octo/new-name",
1363 ssh_url: "git@github.com:octo/new-name.git",
1364 default_branch: "main",
1365 });
1366 const { layer } = harness({
1367 remotes: remotesOutput(["origin", "git@github.com:octo/old-name.git"]),
1368 resolved: "",
1369 api: { rest: () => Effect.succeed(repository) },
1370 });
1371 return Effect.gen(function* () {
1372 const provider = yield* GitHubSourceControlProvider.make;
1373 const targets = yield* provider.createsChangeRequestsIn!({
1374 cwd: "/repo",
1375 context: {
1376 provider: {
1377 kind: SourceControlProviderKind.make("github"),
1378 name: "GitHub",
1379 baseUrl: "https://github.com",
1380 },
1381 remoteName: "origin",
1382 remoteUrl: "git@github.com:octo/old-name.git",
1383 },
1384 repository: "octo/old-name",
1385 });
1386 assert.isTrue(targets);
1387 }).pipe(
1388 Effect.provide(layer),
1389 Effect.provideService(HostProcess.Environment, { GH_REPO: "octo/new-name" }),
1390 );
1391});
1392
1393it.effect(
1394 "says a GH_REPO naming an unparseable host falls back to the remotes, as creation does",
1395 () => {
1396 const { layer } = harness({
1397 remotes: remotesOutput(["upstream", "git@github.com:acme/web.git"]),
1398 resolved: "",
1399 api: {},
1400 });
1401 return Effect.gen(function* () {
1402 const provider = yield* GitHubSourceControlProvider.make;
1403 const targets = yield* provider.createsChangeRequestsIn!({
1404 cwd: "/repo",
1405 context: {
1406 provider: {
1407 kind: SourceControlProviderKind.make("github"),
1408 name: "GitHub",
1409 baseUrl: "https://github.com",
1410 },
1411 remoteName: "upstream",
1412 remoteUrl: "git@github.com:acme/web.git",
1413 },
1414 repository: "acme/web",
1415 });
1416 assert.isTrue(targets);
1417 }).pipe(
1418 Effect.provide(layer),
1419 Effect.provideService(HostProcess.Environment, { GH_REPO: "bad host/acme/web" }),
1420 );
1421 },
1422);