Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import * as DateTime from "effect/DateTime";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import { ChildProcessSpawner } from "effect/unstable/process";
7
8import * as VcsProcess from "../vcs/VcsProcess.ts";
9import * as GitHubCli from "./GitHubCli.ts";
10import { parseGitHubAuthStatus } from "./gitHubAuthStatus.ts";
11import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
12
13const processResult = (
14 stdout: string,
15 options?: {
16 readonly stderr?: string;
17 readonly exitCode?: ChildProcessSpawner.ExitCode;
18 },
19): VcsProcess.VcsProcessOutput => ({
20 exitCode: options?.exitCode ?? ChildProcessSpawner.ExitCode(0),
21 stdout,
22 stderr: options?.stderr ?? "",
23 stdoutTruncated: false,
24 stderrTruncated: false,
25});
26
27function makeProvider(github: Partial<GitHubCli.GitHubCli["Service"]>) {
28 return GitHubSourceControlProvider.make.pipe(
29 Effect.provide(Layer.mock(GitHubCli.GitHubCli)(github)),
30 );
31}
32
33it.effect("uses the enterprise quota for a current-repository default branch read", () =>
34 Effect.gen(function* () {
35 const provider = yield* GitHubSourceControlProvider.make.pipe(
36 Effect.provide(GitHubCli.layer),
37 Effect.provideService(VcsProcess.VcsProcess, {
38 run: (input) =>
39 Effect.sync(() => {
40 if (input.args[1] !== "rate_limit") return processResult("main");
41 assert.strictEqual(input.args[3], "enterprise.test");
42 return processResult(
43 '{"data":{"rateLimit":{"cost":1,"limit":5000,"remaining":5000,"resetAt":"2099-01-01T00:00:00Z"}}}',
44 );
45 }),
46 }),
47 );
48 const branch = yield* provider.getDefaultBranch({
49 cwd: "/enterprise-repo",
50 context: {
51 provider: { kind: "github", name: "GitHub Enterprise", baseUrl: "https://enterprise.test" },
52 remoteName: "origin",
53 remoteUrl: "https://enterprise.test/acme/web.git",
54 },
55 });
56 assert.strictEqual(branch, "main");
57 }),
58);
59
60it.effect("maps GitHub PR summaries into provider-neutral change requests", () =>
61 Effect.gen(function* () {
62 const provider = yield* makeProvider({
63 getPullRequest: () =>
64 Effect.succeed({
65 number: 42,
66 title: "Add GitHub provider",
67 url: "https://github.com/pingdotgg/t3code/pull/42",
68 baseRefName: "main",
69 headRefName: "feature/source-control",
70 state: "open",
71 isCrossRepository: true,
72 headRepositoryNameWithOwner: "fork/t3code",
73 headRepositoryOwnerLogin: "fork",
74 }),
75 });
76
77 const changeRequest = yield* provider.getChangeRequest({
78 cwd: "/repo",
79 reference: "42",
80 });
81
82 assert.deepStrictEqual(changeRequest, {
83 provider: "github",
84 number: 42,
85 title: "Add GitHub provider",
86 url: "https://github.com/pingdotgg/t3code/pull/42",
87 baseRefName: "main",
88 headRefName: "feature/source-control",
89 state: "open",
90 closedAt: null,
91 mergedAt: null,
92 updatedAt: Option.none(),
93 isCrossRepository: true,
94 headRepositoryNameWithOwner: "fork/t3code",
95 headRepositoryOwnerLogin: "fork",
96 });
97 }),
98);
99
100it.effect("adds safe request context while retaining GitHub CLI causes", () =>
101 Effect.gen(function* () {
102 const cause = new GitHubCli.GitHubPullRequestNotFoundError({
103 command: "gh",
104 cwd: "/repo",
105 cause: new Error("raw upstream detail that should remain in the cause"),
106 });
107 const provider = yield* makeProvider({
108 getPullRequest: () => Effect.fail(cause),
109 });
110
111 const error = yield* provider
112 .getChangeRequest({
113 cwd: "/repo",
114 reference: "https://user:secret@github.com/pingdotgg/t3code/pull/42?token=secret#diff",
115 })
116 .pipe(Effect.flip);
117
118 assert.deepStrictEqual(
119 {
120 provider: error.provider,
121 operation: error.operation,
122 command: error.command,
123 cwd: error.cwd,
124 reference: error.reference,
125 detail: error.detail,
126 },
127 {
128 provider: "github",
129 operation: "getChangeRequest",
130 command: "gh",
131 cwd: "/repo",
132 reference: "https://github.com/pingdotgg/t3code/pull/42",
133 detail: "Pull request not found. Check the PR number or URL and try again.",
134 },
135 );
136 assert.strictEqual(error.cause, cause);
137 assert.equal(error.message.includes("raw upstream detail"), false);
138 }),
139);
140
141it.effect("uses gh json listing for non-open change request state queries", () =>
142 Effect.gen(function* () {
143 let executeArgs: ReadonlyArray<string> = [];
144 const provider = yield* makeProvider({
145 execute: (input) => {
146 executeArgs = input.args;
147 return Effect.succeed(
148 processResult(
149 JSON.stringify([
150 {
151 number: 7,
152 title: "Merged work",
153 url: "https://github.com/pingdotgg/t3code/pull/7",
154 baseRefName: "main",
155 headRefName: "feature/merged",
156 state: "merged",
157 mergedAt: "2026-01-01T00:00:00Z",
158 updatedAt: "2026-01-02T00:00:00.000Z",
159 },
160 ]),
161 ),
162 );
163 },
164 });
165
166 const changeRequests = yield* provider.listChangeRequests({
167 cwd: "/repo",
168 headSelector: "feature/merged",
169 state: "all",
170 limit: 10,
171 });
172
173 assert.deepStrictEqual(executeArgs, [
174 "pr",
175 "list",
176 "--head",
177 "feature/merged",
178 "--state",
179 "all",
180 "--limit",
181 "10",
182 "--json",
183 "number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
184 ]);
185 assert.strictEqual(changeRequests[0]?.provider, "github");
186 assert.strictEqual(changeRequests[0]?.state, "merged");
187 assert.strictEqual(changeRequests[0]?.mergedAt, "2026-01-01T00:00:00Z");
188 assert.deepStrictEqual(
189 changeRequests[0]?.updatedAt,
190 Option.some(DateTime.makeUnsafe("2026-01-02T00:00:00.000Z")),
191 );
192 }),
193);
194
195it.effect("treats empty non-open change request listing output as no results", () =>
196 Effect.gen(function* () {
197 const provider = yield* makeProvider({
198 execute: () => Effect.succeed(processResult("")),
199 });
200
201 const changeRequests = yield* provider.listChangeRequests({
202 cwd: "/repo",
203 headSelector: "feature/empty",
204 state: "all",
205 limit: 10,
206 });
207
208 assert.deepStrictEqual(changeRequests, []);
209 }),
210);
211
212it.effect("creates GitHub PRs through provider-neutral input names", () =>
213 Effect.gen(function* () {
214 let createInput: Parameters<GitHubCli.GitHubCli["Service"]["createPullRequest"]>[0] | null =
215 null;
216 const provider = yield* makeProvider({
217 createPullRequest: (input) => {
218 createInput = input;
219 return Effect.void;
220 },
221 });
222
223 yield* provider.createChangeRequest({
224 cwd: "/repo",
225 baseRefName: "main",
226 headSelector: "owner:feature/provider",
227 title: "Provider PR",
228 bodyFile: "/tmp/body.md",
229 });
230
231 assert.deepStrictEqual(createInput, {
232 cwd: "/repo",
233 baseBranch: "main",
234 headSelector: "owner:feature/provider",
235 title: "Provider PR",
236 bodyFile: "/tmp/body.md",
237 });
238 }),
239);
240
241it("accepts active authenticated GitHub accounts when another account fails", () => {
242 const auth = GitHubSourceControlProvider.discovery.parseAuth(
243 processResult(
244 JSON.stringify({
245 hosts: {
246 "github.com": [
247 {
248 state: "success",
249 active: true,
250 host: "github.com",
251 login: "active-user",
252 tokenSource: "keyring",
253 gitProtocol: "ssh",
254 },
255 {
256 state: "error",
257 active: false,
258 host: "github.com",
259 login: "stale-user",
260 tokenSource: "keyring",
261 gitProtocol: "ssh",
262 error: "The token in keyring is invalid.",
263 },
264 ],
265 },
266 }),
267 ),
268 );
269
270 assert.deepStrictEqual(
271 {
272 status: auth.status,
273 account: auth.account,
274 host: auth.host,
275 },
276 {
277 status: "authenticated",
278 account: Option.some("active-user"),
279 host: Option.some("github.com"),
280 },
281 );
282});
283
284it("parses GitHub auth JSON from stdout when stderr has warnings", () => {
285 const auth = GitHubSourceControlProvider.discovery.parseAuth(
286 processResult(
287 JSON.stringify({
288 hosts: {
289 "github.com": [
290 {
291 state: "success",
292 active: true,
293 host: "github.com",
294 login: "active-user",
295 tokenSource: "keyring",
296 gitProtocol: "ssh",
297 },
298 ],
299 },
300 }),
301 { stderr: "warning: ignored diagnostic from gh\n" },
302 ),
303 );
304
305 assert.deepStrictEqual(
306 {
307 status: auth.status,
308 account: auth.account,
309 host: auth.host,
310 },
311 {
312 status: "authenticated",
313 account: Option.some("active-user"),
314 host: Option.some("github.com"),
315 },
316 );
317});
318
319it("parses GitHub auth status accounts by host and active state", () => {
320 assert.deepStrictEqual(
321 parseGitHubAuthStatus(
322 JSON.stringify({
323 hosts: {
324 "github.com": [
325 {
326 state: "success",
327 active: true,
328 host: "github.com",
329 login: "active-user",
330 tokenSource: "keyring",
331 gitProtocol: "ssh",
332 },
333 {
334 state: "error",
335 active: false,
336 host: "github.com",
337 login: "stale-user",
338 tokenSource: "keyring",
339 gitProtocol: "ssh",
340 },
341 ],
342 "github.example.test": [
343 {
344 state: "success",
345 active: false,
346 host: "github.example.test",
347 login: "enterprise-user",
348 tokenSource: "keyring",
349 gitProtocol: "ssh",
350 },
351 ],
352 },
353 }),
354 ).accounts,
355 [
356 {
357 host: "github.com",
358 account: "active-user",
359 authenticated: true,
360 active: true,
361 error: null,
362 },
363 {
364 host: "github.com",
365 account: "stale-user",
366 authenticated: false,
367 active: false,
368 error: null,
369 },
370 {
371 host: "github.example.test",
372 account: "enterprise-user",
373 authenticated: true,
374 active: false,
375 error: null,
376 },
377 ],
378 );
379});
380
381it("reports unauthenticated when GitHub JSON has accounts but none are valid", () => {
382 const auth = GitHubSourceControlProvider.discovery.parseAuth(
383 processResult(
384 JSON.stringify({
385 hosts: {
386 "github.com": [
387 {
388 state: "error",
389 active: true,
390 host: "github.com",
391 login: "stale-user",
392 tokenSource: "keyring",
393 gitProtocol: "ssh",
394 error: "The token in keyring is invalid.",
395 },
396 ],
397 },
398 }),
399 ),
400 );
401
402 assert.deepStrictEqual(
403 {
404 status: auth.status,
405 host: auth.host,
406 detail: auth.detail,
407 },
408 {
409 status: "unauthenticated",
410 host: Option.some("github.com"),
411 detail: Option.some("The token in keyring is invalid."),
412 },
413 );
414});
415
416it("reports an update hint instead of unauthenticated when gh predates --json", () => {
417 const auth = GitHubSourceControlProvider.discovery.parseAuth(
418 processResult("", {
419 stderr: "unknown flag: --json\n\nUsage: gh auth status [flags]\n",
420 exitCode: ChildProcessSpawner.ExitCode(1),
421 }),
422 );
423
424 assert.strictEqual(auth.status, "unknown");
425 assert.match(
426 Option.getOrElse(auth.detail, () => ""),
427 /2\.81\.0/,
428 );
429});
430
431for (const kind of ["pull", "issues"]) {
432 it.effect(`resolves ${kind} subjects on the linked host without using the checkout`, () =>
433 Effect.gen(function* () {
434 const provider = yield* makeProvider({
435 execute: (input) => {
436 assert.deepStrictEqual(input.args, [
437 "api",
438 "--hostname",
439 "github.com",
440 "repos/owner/repo/issues/42",
441 "--jq",
442 "{title, body}",
443 ]);
444 assert.strictEqual(input.maxOutputBytes, 32_000);
445 assert.strictEqual(input.timeoutMs, 3_000);
446 return Effect.succeed({
447 exitCode: ChildProcessSpawner.ExitCode(0),
448 stdout: JSON.stringify({ title: "Pairing expiry", body: "Preserve remote access" }),
449 stderr: "",
450 stdoutTruncated: false,
451 stderrTruncated: false,
452 });
453 },
454 });
455 const lookup = provider.resolveLink?.({
456 cwd: "/unrelated",
457 url: new URL(`https://github.com/owner/repo/${kind}/42`),
458 });
459 assert.ok(lookup);
460 assert.deepStrictEqual(yield* lookup, {
461 title: "Pairing expiry",
462 body: "Preserve remote access",
463 });
464 assert.strictEqual(
465 provider.resolveLink?.({
466 cwd: "/unrelated",
467 url: new URL("https://github.com/owner/repo"),
468 }),
469 undefined,
470 );
471 }),
472 );
473}
474
475for (const stage of ["read", "decode"] as const) {
476 it.effect(`retains the ${stage} failure without exposing its raw contents`, () =>
477 Effect.gen(function* () {
478 const cause = new GitHubCli.GitHubCliCommandError({
479 command: "gh",
480 cwd: "/repo",
481 cause: new Error("private response text"),
482 });
483 const provider = yield* makeProvider({
484 execute: () =>
485 stage === "read"
486 ? Effect.fail(cause)
487 : Effect.succeed({
488 exitCode: ChildProcessSpawner.ExitCode(0),
489 stdout: "private response text",
490 stderr: "",
491 stdoutTruncated: false,
492 stderrTruncated: false,
493 }),
494 });
495 const lookup = provider.resolveLink?.({
496 cwd: "/repo",
497 url: new URL("https://github.com/owner/repo/issues/42"),
498 });
499 assert.ok(lookup);
500 const error = yield* Effect.flip(lookup);
501 assert.strictEqual(error.operation, stage === "read" ? "resolveLink" : "resolveLink.decode");
502 assert.strictEqual(error.detail, "The linked subject could not be read.");
503 assert.notInclude(error.message, "private response text");
504 if (stage === "read") assert.strictEqual(error.cause, cause);
505 else assert.propertyVal(error.cause, "_tag", "SchemaError");
506 }),
507 );
508}