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

GitHubSourceControlProvider.test.ts

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