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

GitHubSourceControlProvider.test.ts

545 lines15.8 KB

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