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 * as GitHubGraphQlBudget from "./githubGraphQlBudget.ts";
11import { parseGitHubAuthStatus } from "./gitHubAuthStatus.ts";
12import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
13
14const processResult = (
15 stdout: string,
16 options?: {
17 readonly stderr?: string;
18 readonly exitCode?: ChildProcessSpawner.ExitCode;
19 },
20): VcsProcess.VcsProcessOutput => ({
21 exitCode: options?.exitCode ?? ChildProcessSpawner.ExitCode(0),
22 stdout,
23 stderr: options?.stderr ?? "",
24 stdoutTruncated: false,
25 stderrTruncated: false,
26});
27
28function makeProvider(github: Partial<GitHubCli.GitHubCli["Service"]>) {
29 return GitHubSourceControlProvider.make.pipe(
30 Effect.provide(Layer.mock(GitHubCli.GitHubCli)(github)),
31 );
32}
33
34it.effect("uses the enterprise quota for a current-repository default branch read", () =>
35 Effect.gen(function* () {
36 // github.com is out of quota; the enterprise read must not be priced against it.
37 const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;
38 yield* budget.observe(
39 "github.com",
40 '{"data":{"rateLimit":{"cost":1,"limit":5000,"remaining":0,"resetAt":"2099-01-01T00:00:00Z"}}}',
41 );
42 const provider = yield* GitHubSourceControlProvider.make;
43 const branch = yield* provider.getDefaultBranch({
44 cwd: "/enterprise-repo",
45 context: {
46 provider: { kind: "github", name: "GitHub Enterprise", baseUrl: "https://enterprise.test" },
47 remoteName: "origin",
48 remoteUrl: "https://enterprise.test/acme/web.git",
49 },
50 });
51 assert.strictEqual(branch, "main");
52 }).pipe(
53 Effect.provide(GitHubCli.layer),
54 Effect.provideService(VcsProcess.VcsProcess, {
55 run: () => Effect.succeed(processResult("main")),
56 }),
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("lists change request history through the batched head lookup", () =>
142 Effect.gen(function* () {
143 let lookup: Parameters<GitHubCli.GitHubCli["Service"]["listPullRequestsByHead"]>[0] | null =
144 null;
145 const provider = yield* makeProvider({
146 listPullRequestsByHead: (input) => {
147 lookup = input;
148 return Effect.succeed([
149 {
150 number: 7,
151 title: "Merged work",
152 url: "https://enterprise.test/acme/web/pull/7",
153 baseRefName: "main",
154 headRefName: "feature/merged",
155 state: "merged",
156 mergedAt: "2026-01-01T00:00:00Z",
157 updatedAt: Option.some(DateTime.makeUnsafe("2026-01-02T00:00:00.000Z")),
158 },
159 ]);
160 },
161 });
162
163 const changeRequests = yield* provider.listChangeRequests({
164 cwd: "/repo",
165 context: {
166 provider: { kind: "github", name: "GitHub Enterprise", baseUrl: "https://enterprise.test" },
167 remoteName: "origin",
168 remoteUrl: "https://enterprise.test/acme/web.git",
169 },
170 headSelector: "feature/merged",
171 state: "all",
172 limit: 10,
173 });
174
175 assert.deepStrictEqual(lookup, {
176 cwd: "/repo",
177 headSelector: "feature/merged",
178 state: "all",
179 limit: 10,
180 rateLimitHost: "enterprise.test",
181 });
182 assert.strictEqual(changeRequests[0]?.provider, "github");
183 assert.strictEqual(changeRequests[0]?.state, "merged");
184 assert.strictEqual(changeRequests[0]?.mergedAt, "2026-01-01T00:00:00Z");
185 assert.deepStrictEqual(
186 changeRequests[0]?.updatedAt,
187 Option.some(DateTime.makeUnsafe("2026-01-02T00:00:00.000Z")),
188 );
189 }),
190);
191
192it.effect("creates GitHub PRs through provider-neutral input names", () =>
193 Effect.gen(function* () {
194 let createInput: Parameters<GitHubCli.GitHubCli["Service"]["createPullRequest"]>[0] | null =
195 null;
196 const provider = yield* makeProvider({
197 createPullRequest: (input) => {
198 createInput = input;
199 return Effect.void;
200 },
201 });
202
203 yield* provider.createChangeRequest({
204 cwd: "/repo",
205 baseRefName: "main",
206 headSelector: "owner:feature/provider",
207 title: "Provider PR",
208 bodyFile: "/tmp/body.md",
209 });
210
211 assert.deepStrictEqual(createInput, {
212 cwd: "/repo",
213 baseBranch: "main",
214 headSelector: "owner:feature/provider",
215 title: "Provider PR",
216 bodyFile: "/tmp/body.md",
217 });
218 }),
219);
220
221it("accepts active authenticated GitHub accounts when another account fails", () => {
222 const auth = GitHubSourceControlProvider.discovery.parseAuth(
223 processResult(
224 JSON.stringify({
225 hosts: {
226 "github.com": [
227 {
228 state: "success",
229 active: true,
230 host: "github.com",
231 login: "active-user",
232 tokenSource: "keyring",
233 gitProtocol: "ssh",
234 },
235 {
236 state: "error",
237 active: false,
238 host: "github.com",
239 login: "stale-user",
240 tokenSource: "keyring",
241 gitProtocol: "ssh",
242 error: "The token in keyring is invalid.",
243 },
244 ],
245 },
246 }),
247 ),
248 );
249
250 assert.deepStrictEqual(
251 {
252 status: auth.status,
253 account: auth.account,
254 host: auth.host,
255 },
256 {
257 status: "authenticated",
258 account: Option.some("active-user"),
259 host: Option.some("github.com"),
260 },
261 );
262});
263
264it("parses GitHub auth JSON from stdout when stderr has warnings", () => {
265 const auth = GitHubSourceControlProvider.discovery.parseAuth(
266 processResult(
267 JSON.stringify({
268 hosts: {
269 "github.com": [
270 {
271 state: "success",
272 active: true,
273 host: "github.com",
274 login: "active-user",
275 tokenSource: "keyring",
276 gitProtocol: "ssh",
277 },
278 ],
279 },
280 }),
281 { stderr: "warning: ignored diagnostic from gh\n" },
282 ),
283 );
284
285 assert.deepStrictEqual(
286 {
287 status: auth.status,
288 account: auth.account,
289 host: auth.host,
290 },
291 {
292 status: "authenticated",
293 account: Option.some("active-user"),
294 host: Option.some("github.com"),
295 },
296 );
297});
298
299it("parses GitHub auth status accounts by host and active state", () => {
300 assert.deepStrictEqual(
301 parseGitHubAuthStatus(
302 JSON.stringify({
303 hosts: {
304 "github.com": [
305 {
306 state: "success",
307 active: true,
308 host: "github.com",
309 login: "active-user",
310 tokenSource: "keyring",
311 gitProtocol: "ssh",
312 },
313 {
314 state: "error",
315 active: false,
316 host: "github.com",
317 login: "stale-user",
318 tokenSource: "keyring",
319 gitProtocol: "ssh",
320 },
321 ],
322 "github.example.test": [
323 {
324 state: "success",
325 active: false,
326 host: "github.example.test",
327 login: "enterprise-user",
328 tokenSource: "keyring",
329 gitProtocol: "ssh",
330 },
331 ],
332 },
333 }),
334 ).accounts,
335 [
336 {
337 host: "github.com",
338 account: "active-user",
339 authenticated: true,
340 active: true,
341 error: null,
342 },
343 {
344 host: "github.com",
345 account: "stale-user",
346 authenticated: false,
347 active: false,
348 error: null,
349 },
350 {
351 host: "github.example.test",
352 account: "enterprise-user",
353 authenticated: true,
354 active: false,
355 error: null,
356 },
357 ],
358 );
359});
360
361it("reports unauthenticated when GitHub JSON has accounts but none are valid", () => {
362 const auth = GitHubSourceControlProvider.discovery.parseAuth(
363 processResult(
364 JSON.stringify({
365 hosts: {
366 "github.com": [
367 {
368 state: "error",
369 active: true,
370 host: "github.com",
371 login: "stale-user",
372 tokenSource: "keyring",
373 gitProtocol: "ssh",
374 error: "The token in keyring is invalid.",
375 },
376 ],
377 },
378 }),
379 ),
380 );
381
382 assert.deepStrictEqual(
383 {
384 status: auth.status,
385 host: auth.host,
386 detail: auth.detail,
387 },
388 {
389 status: "unauthenticated",
390 host: Option.some("github.com"),
391 detail: Option.some("The token in keyring is invalid."),
392 },
393 );
394});
395
396it("reports an update hint instead of unauthenticated when gh predates --json", () => {
397 const auth = GitHubSourceControlProvider.discovery.parseAuth(
398 processResult("", {
399 stderr: "unknown flag: --json\n\nUsage: gh auth status [flags]\n",
400 exitCode: ChildProcessSpawner.ExitCode(1),
401 }),
402 );
403
404 assert.strictEqual(auth.status, "unknown");
405 assert.match(
406 Option.getOrElse(auth.detail, () => ""),
407 /2\.81\.0/,
408 );
409});
410
411it.effect.each(["pull", "issues"])(
412 "resolves %s subjects on the linked host without using the checkout",
413 (kind) =>
414 Effect.gen(function* () {
415 const provider = yield* makeProvider({
416 execute: (input) => {
417 assert.deepStrictEqual(input.args, [
418 "api",
419 "--hostname",
420 "github.com",
421 "repos/owner/repo/issues/42",
422 "--jq",
423 "{title, body}",
424 ]);
425 assert.strictEqual(input.maxOutputBytes, 32_000);
426 assert.strictEqual(input.timeoutMs, 3_000);
427 return Effect.succeed({
428 exitCode: ChildProcessSpawner.ExitCode(0),
429 stdout: JSON.stringify({ title: "Pairing expiry", body: "Preserve remote access" }),
430 stderr: "",
431 stdoutTruncated: false,
432 stderrTruncated: false,
433 });
434 },
435 });
436 const lookup = provider.resolveLink?.({
437 cwd: "/unrelated",
438 url: new URL(`https://github.com/owner/repo/${kind}/42`),
439 });
440 assert.ok(lookup);
441 assert.deepStrictEqual(yield* lookup, {
442 title: "Pairing expiry",
443 body: "Preserve remote access",
444 });
445 assert.strictEqual(
446 provider.resolveLink?.({
447 cwd: "/unrelated",
448 url: new URL("https://github.com/owner/repo"),
449 }),
450 undefined,
451 );
452 }),
453);
454
455it.effect.each(["read", "decode"] as const)(
456 "retains the %s failure without exposing its raw contents",
457 (stage) =>
458 Effect.gen(function* () {
459 const cause = new GitHubCli.GitHubCliCommandError({
460 command: "gh",
461 cwd: "/repo",
462 cause: new Error("private response text"),
463 });
464 const provider = yield* makeProvider({
465 execute: () =>
466 stage === "read"
467 ? Effect.fail(cause)
468 : Effect.succeed({
469 exitCode: ChildProcessSpawner.ExitCode(0),
470 stdout: "private response text",
471 stderr: "",
472 stdoutTruncated: false,
473 stderrTruncated: false,
474 }),
475 });
476 const lookup = provider.resolveLink?.({
477 cwd: "/repo",
478 url: new URL("https://github.com/owner/repo/issues/42"),
479 });
480 assert.ok(lookup);
481 const error = yield* Effect.flip(lookup);
482 assert.strictEqual(error.operation, stage === "read" ? "resolveLink" : "resolveLink.decode");
483 assert.strictEqual(error.detail, "The linked subject could not be read.");
484 assert.notInclude(error.message, "private response text");
485 if (stage === "read") assert.strictEqual(error.cause, cause);
486 else assert.propertyVal(error.cause, "_tag", "SchemaError");
487 }),
488);