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

ForgejoSourceControlProvider.test.ts

1,326 lines47.9 KB

1import { SourceControlProviderKind } from "@t3tools/contracts";
2import { assert, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Schema from "effect/Schema";
8import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
9import * as HttpClient from "effect/http/HttpClient";
10import * as HttpClientRequest from "effect/http/HttpClientRequest";
11import * as HttpClientResponse from "effect/http/HttpClientResponse";
12import { VcsProcessSpawnError } from "@t3tools/contracts";
13import { firstNonEmptyLine } from "@t3tools/source-control-core/server/discovery";
14import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
15​
16import * as ForgejoCli from "./ForgejoCli.ts";
17import * as ForgejoPullRequestProvider from "./ForgejoPullRequestProvider.ts";
18import * as ForgejoSourceControlProvider from "./ForgejoSourceControlProvider.ts";
19​
20const processOutput = TestSourceControlHost.processOutput;
21​
22const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
23const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
24​
25const requestJson = (request: HttpClientRequest.HttpClientRequest): unknown => {
26 assert.strictEqual(request.body._tag, "Uint8Array");
27 return request.body._tag === "Uint8Array"
28 ? decodeJson(new TextDecoder().decode(request.body.body))
29 : undefined;
30};
31const encodeJsonEffect = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
32​
33const requiredChecksPullRequest = {
34 number: 7,
35 title: "Required checks",
36 body: "",
37 html_url: "https://forgejo.test/acme/web/pulls/7",
38 user: { login: "maria" },
39 state: "open",
40 merged: false,
41 head: { ref: "feature", sha: "head", repo: null },
42 base: { ref: "release/1.x", sha: "base", repo: null },
43 created_at: "2026-10-12T00:00:00Z",
44 updated_at: "2026-10-12T00:00:00Z",
45 closed_at: null,
46 merged_at: null,
47 labels: [],
48};
49const requiredChecksStatuses = [
50 ["ci/required-build", "success"],
51 ["ci/optional-lint", "failure"],
52].map(([context, status]) => ({
53 context,
54 status,
55 description: null,
56 target_url: null,
57 updated_at: "2026-10-12T00:00:00Z",
58}));
59​
60const requiredChecksInput = {
61 cwd: "/repo",
62 repository: "acme/web",
63 host: "forgejo.test",
64 number: 7,
65};
66const requiredChecksLayer = (
67 branch: Effect.Effect<unknown, ForgejoCli.ForgejoCliError>,
68 statuses = requiredChecksStatuses,
69) =>
70 Layer.mock(ForgejoCli.ForgejoCli)({
71 api: (input) => {
72 const [path, query] = input.path.split("?");
73 const respond = (response: unknown) =>
74 encodeJsonEffect(response).pipe(Effect.orDie, Effect.map(processOutput));
75 switch (path) {
76 case "repos/acme/web/pulls/7":
77 return respond(requiredChecksPullRequest);
78 case "repos/acme/web/statuses/head":
79 return respond(new URLSearchParams(query).get("page") === "1" ? statuses : []);
80 case "repos/acme/web/branches/release/1.x":
81 return Effect.flatMap(branch, respond);
82 case "repos/acme/web":
83 return respond({ full_name: "acme/web", permissions: { push: true, admin: false } });
84 case "user":
85 return respond({ login: "maria" });
86 default:
87 return Effect.die(`Unexpected Forgejo request: ${input.path}`);
88 }
89 },
90 });
91​
92it.effect.each([
93 ["ci/required-deploy", true],
94 ["test-*", true],
95 ["ci/[ab]", false],
96] as const)("keeps missing required pattern %s pending (supported: %s)", ([missing, supported]) =>
97 Effect.gen(function* () {
98 const provider = yield* ForgejoPullRequestProvider.make;
99 const readChecks = provider.getChangeRequestChecks;
100 if (readChecks === undefined) return yield* Effect.die("checks read missing");
101 const summary = yield* readChecks(requiredChecksInput);
102 const detail = yield* provider.getChangeRequest(requiredChecksInput);
103 for (const checks of [summary.checks, detail.checks]) {
104 assert.deepStrictEqual(
105 checks.map((check) => [check.name, check.status, check.required]),
106 supported
107 ? [
108 ["ci/optional-lint", "failure", undefined],
109 ["ci/required-build", "success", true],
110 [missing, "pending", true],
111 ]
112 : [
113 ["ci/required-build", "success", undefined],
114 ["ci/optional-lint", "success", undefined],
115 [missing, "pending", undefined],
116 ],
117 );
118 if (!supported) {
119 assert.strictEqual(
120 checks.at(-1)?.description,
121 "Required check pattern cannot be evaluated.",
122 );
123 }
124 }
125 }).pipe(
126 Effect.provide(
127 requiredChecksLayer(
128 Effect.succeed({
129 name: "release/1.x",
130 protected: true,
131 enable_status_check: true,
132 status_check_contexts: ["ci/required-*", missing, missing],
133 }),
134 supported
135 ? requiredChecksStatuses
136 : requiredChecksStatuses.map((status) => ({ ...status, status: "success" })),
137 ),
138 ),
139 ),
140);
141​
142// regression: #18775 a failed branch-protection read surfaces; only 403/404 are treated as no policy
143it.effect.each([
144 ["rate limit", { reason: "rate-limit", httpStatus: 429 }, "rate-limited"],
145 ["authentication failure", { reason: "authentication", httpStatus: 401 }, "unauthenticated"],
146 ["network failure", {}, "failed"],
147] as const)("propagates branch metadata %s", ([detail, fields, reason]) => {
148 const cause = new ForgejoCli.ForgejoCliError({ command: "fj", cwd: "/repo", detail, ...fields });
149 return Effect.gen(function* () {
150 const provider = yield* ForgejoPullRequestProvider.make;
151 const readChecks = provider.getChangeRequestChecks;
152 if (readChecks === undefined) return yield* Effect.die("checks read missing");
153 for (const read of [readChecks, provider.getChangeRequest]) {
154 const error = yield* read(requiredChecksInput).pipe(Effect.flip);
155 assert.strictEqual(error.reason, reason);
156 assert.strictEqual(error.cause, cause);
157 }
158 }).pipe(Effect.provide(requiredChecksLayer(Effect.fail(cause))));
159});
160​
161it.effect("opens Forgejo Actions check links on the pull request's server", () =>
162 Effect.gen(function* () {
163 const provider = yield* ForgejoPullRequestProvider.make;
164 const read = provider.getChangeRequestChecks;
165 if (read === undefined) return yield* Effect.die("checks read missing");
166 const result = yield* read({
167 cwd: "/repo",
168 repository: "acme/web",
169 host: "forgejo.test",
170 number: 1,
171 });
172 assert.deepStrictEqual(
173 result.checks.map((check) => [check.name, check.url]),
174 [
175 ["actions", "https://forgejo.test/git/acme/web/actions/runs/7/jobs/2"],
176 ["external", "https://ci.example/build/9"],
177 ["none", null],
178 ],
179 );
180 }).pipe(
181 Effect.provide(
182 Layer.mock(ForgejoCli.ForgejoCli)({
183 api: (input) => {
184 const status = (context: string, target_url: string | null) => ({
185 context,
186 status: "success",
187 description: null,
188 target_url,
189 updated_at: "2026-10-11T00:00:00Z",
190 });
191 const body = input.path.endsWith("branches/main")
192 ? {}
193 : input.path.endsWith("pulls/1")
194 ? {
195 number: 1,
196 title: "Checks",
197 body: "",
198 html_url: "https://forgejo.test/git/acme/web/pulls/1",
199 user: null,
200 state: "open",
201 merged: false,
202 head: { ref: "feature", sha: "head", repo: null },
203 base: { ref: "main", sha: "base", repo: null },
204 created_at: "2026-10-11T00:00:00Z",
205 updated_at: "2026-10-11T00:00:00Z",
206 closed_at: null,
207 merged_at: null,
208 labels: [],
209 }
210 : input.path.endsWith("page=1")
211 ? [
212 // Forgejo includes any sub-path mount in the relative links it reports.
213 status("actions", "/git/acme/web/actions/runs/7/jobs/2"),
214 status("external", "https://ci.example/build/9"),
215 status("none", null),
216 ]
217 : [];
218 return encodeJsonEffect(body).pipe(Effect.orDie, Effect.map(processOutput));
219 },
220 }),
221 ),
222 ),
223);
224​
225it.effect.each([
226 ["Ready", false, true, false, "mergeable"],
227 ["Draft", true, false, true, "unknown"],
228 ["WIP: Legacy draft", undefined, false, true, "unknown"],
229 ["WIP: Explicitly ready", false, false, false, "unknown"],
230] as const)(
231 "reads Forgejo mergeability for %s (draft=%s, mergeable=%s) across list, summary and detail",
232 ([title, draft, mergeable, isDraft, mergeability]) => {
233 const pr = {
234 number: 42,
235 title,
236 body: "",
237 html_url: "https://forgejo.test/maria/project/pulls/42",
238 user: { login: "maria" },
239 state: "open",
240 merged: false,
241 ...(draft === undefined ? {} : { draft }),
242 ...(mergeable === undefined ? {} : { mergeable }),
243 head: { ref: "feature", sha: "head", repo: null },
244 base: { ref: "main", sha: "base", repo: null },
245 created_at: "2026-09-16T00:00:00Z",
246 updated_at: "2026-09-16T00:00:00Z",
247 closed_at: null,
248 merged_at: null,
249 labels: [],
250 };
251 return Effect.gen(function* () {
252 const provider = yield* ForgejoPullRequestProvider.make;
253 const readSummary = provider.getChangeRequestSummary;
254 if (readSummary === undefined) return yield* Effect.die("summary read missing");
255 const input = { cwd: "/repo", repository: "maria/project", host: "forgejo.test", number: 42 };
256 const list = yield* provider.listChangeRequests({
257 ...input,
258 state: "open",
259 involvement: "all",
260 viewer: "maria",
261 limit: 10,
262 });
263 const summary = yield* readSummary(input);
264 const detail = yield* provider.getChangeRequest(input);
265 assert.strictEqual(list.items.length, 1);
266 assert.strictEqual(detail.headSha, "head");
267 for (const result of [list.items[0]!, summary, detail]) {
268 assert.strictEqual(result.mergeability, mergeability);
269 assert.strictEqual(result.isDraft, isDraft);
270 }
271 }).pipe(
272 Effect.provide(
273 Layer.mock(ForgejoCli.ForgejoCli)({
274 api: (input) => {
275 const [path, query] = input.path.split("?");
276 let response: unknown;
277 switch (path) {
278 case "repos/maria/project/pulls":
279 response = new URLSearchParams(query).get("page") === "1" ? [pr] : [];
280 break;
281 case "repos/maria/project/pulls/42":
282 response = pr;
283 break;
284 case "repos/maria/project":
285 response = { full_name: "maria/project", permissions: { push: true, admin: true } };
286 break;
287 case "user":
288 response = pr.user;
289 break;
290 case "repos/maria/project/statuses/head":
291 response = [];
292 break;
293 case "repos/maria/project/branches/main":
294 response = { name: "main", protected: false };
295 break;
296 default:
297 return Effect.die(`Unexpected Forgejo request: ${input.path}`);
298 }
299 return encodeJsonEffect(response).pipe(Effect.orDie, Effect.map(processOutput));
300 },
301 }),
302 ),
303 );
304 },
305);
306​
307it.effect("gives Forgejo identities the browser URL of the login that serves them", () =>
308 Effect.gen(function* () {
309 const provider = yield* ForgejoSourceControlProvider.make;
310 const refine = provider.refineRepositoryIdentity;
311 assert.isDefined(refine);
312 const identity = (remoteUrl: string, provider?: string) => ({
313 canonicalKey: "forge.test/team/repo",
314 locator: { source: "git-remote" as const, remoteName: "origin", remoteUrl },
315 rootPath: "/repo",
316 ...(provider === undefined ? {} : { provider }),
317 });
318 const served = (baseUrl: string) => () =>
319 Effect.succeed({
320 provider: {
321 kind: SourceControlProviderKind.make("forgejo"),
322 name: "Forgejo / Gitea",
323 baseUrl,
324 },
325 remoteName: "origin",
326 remoteUrl: "",
327 });
328​
329 assert.deepStrictEqual(
330 yield* refine!({
331 identity: identity("http://forge.test:3000/git/team/repo.git"),
332 resolveContext: served("http://forge.test:3000/git/"),
333 }),
334 {
335 ...identity("http://forge.test:3000/git/team/repo.git"),
336 provider: SourceControlProviderKind.make("forgejo"),
337 webUrl: "http://forge.test:3000/git/team/repo",
338 },
339 );
340 assert.strictEqual(
341 (yield* refine!({
342 identity: identity("ssh://git@ssh.forge.test/team/repo.git"),
343 resolveContext: served("http://forge.test:3000/git"),
344 })).webUrl,
345 "http://forge.test:3000/git/team/repo",
346 );
347 const github = identity("https://github.com/team/repo.git", "github");
348 assert.strictEqual(
349 yield* refine!({ identity: github, resolveContext: () => Effect.die("not asked") }),
350 github,
351 );
352 const unserved = identity("http://forge.test:3000/team/repo.git");
353 assert.strictEqual(
354 yield* refine!({ identity: unserved, resolveContext: () => Effect.succeed(null) }),
355 unserved,
356 );
357 }).pipe(
358 Effect.provide(
359 Layer.mergeAll(
360 Layer.succeed(FileSystem.FileSystem, FileSystem.makeNoop({})),
361 TestSourceControlHost.layer(),
362 Layer.mock(ForgejoCli.ForgejoCli)({}),
363 ),
364 ),
365 ),
366);
367​
368it.effect("loads Forgejo pull request references from files and commits views", () =>
369 Effect.gen(function* () {
370 const provider = yield* ForgejoSourceControlProvider.make;
371 for (const reference of [
372 "42",
373 "#42",
374 "https://forgejo.test/maria/project/pulls/42",
375 "https://forgejo.test/maria/project/pulls/42/",
376 "https://forgejo.test/maria/project/pulls/42/files?w=1#diff-1",
377 "http://forgejo.test:3000/git/maria/project/pulls/42/commits",
378 ]) {
379 const result = yield* provider.getChangeRequest({ cwd: "/repo", reference });
380 assert.strictEqual(result.number, 42);
381 assert.strictEqual(result.title, "Forgejo view reference");
382 assert.strictEqual(result.headSha, "head");
383 }
384 const invalid = yield* provider
385 .getChangeRequest({
386 cwd: "/repo",
387 reference: "https://forgejo.test/maria/project/pulls/42invalid/files",
388 })
389 .pipe(Effect.result);
390 assert.strictEqual(invalid._tag, "Failure");
391 }).pipe(
392 Effect.provide(
393 Layer.mergeAll(
394 Layer.succeed(FileSystem.FileSystem, FileSystem.makeNoop({})),
395 TestSourceControlHost.layer({ process: {} }),
396 Layer.mock(ForgejoCli.ForgejoCli)({
397 resolveRepository: () =>
398 Effect.succeed({
399 login: "work",
400 repository: "maria/project",
401 baseUrl: "https://forgejo.test",
402 }),
403 api: (input) => {
404 assert.strictEqual(input.path, "repos/maria/project/pulls/42");
405 return encodeJsonEffect({
406 number: 42,
407 title: "Forgejo view reference",
408 html_url: "https://forgejo.test/maria/project/pulls/42",
409 state: "open",
410 merged: false,
411 base: { ref: "main", sha: "base", repo: null },
412 head: { ref: "feature", sha: "head", repo: null },
413 }).pipe(Effect.orDie, Effect.map(processOutput));
414 },
415 }),
416 ),
417 ),
418 ),
419);
420​
421it.effect(
422 "loads Forgejo reactions on comments, reviews and inline threads and resolves review mutations",
423 () => {
424 const user = { login: "maria" };
425 const review = {
426 id: 8,
427 body: "review body",
428 user,
429 state: "COMMENT",
430 submitted_at: "2026-09-12T00:00:00Z",
431 html_url: "https://forgejo.test/maria/project/pulls/2#issuecomment-37",
432 comments_count: 1,
433 };
434 const comment = { id: 12, body: "ordinary", user, created_at: review.submitted_at };
435 const responses: Record<string, unknown> = {
436 user,
437 "repos/maria/project/issues/2/comments": [comment],
438 "repos/maria/project/pulls/2/reviews": [review],
439 "repos/maria/project/pulls/2/reviews/8": review,
440 "repos/maria/project/pulls/2/reviews/9": { ...review, id: 9, html_url: "" },
441 "repos/maria/project/pulls/2/commits": [],
442 "repos/maria/project/issues/2/reactions": [],
443 "repos/maria/project/pulls/2/reviews/8/comments": [
444 {
445 ...comment,
446 id: 38,
447 body: "inline",
448 path: "file.ts",
449 position: 1,
450 original_position: 1,
451 commit_id: "head",
452 original_commit_id: "head",
453 resolver: null,
454 },
455 ],
456 "repos/maria/project/issues/comments/12/reactions": [{ content: "+1", user }],
457 "repos/maria/project/issues/comments/37/reactions": [{ content: "heart", user }],
458 "repos/maria/project/issues/comments/38/reactions": [
459 { content: "rocket", user: { login: "reviewer" } },
460 ],
461 };
462 const writes: ForgejoCli.ForgejoApiInput[] = [];
463 let reactionReads = 0;
464 return Effect.gen(function* () {
465 const provider = yield* ForgejoPullRequestProvider.make;
466 const input = { cwd: "/repo", repository: "maria/project", host: "forgejo.test", number: 2 };
467 const activity = yield* provider.getChangeRequestActivity(input);
468 assert.deepStrictEqual(
469 activity.comments.map((entry) => ({
470 id: entry.id,
471 kind: entry.kind,
472 reactions: entry.reactions,
473 })),
474 [
475 {
476 id: "12",
477 kind: "issue-comment",
478 reactions: [{ content: "thumbs-up", count: 1, actors: [], viewerHasReacted: true }],
479 },
480 {
481 id: "review:8",
482 kind: "review",
483 reactions: [{ content: "heart", count: 1, actors: [], viewerHasReacted: true }],
484 },
485 {
486 id: "38",
487 kind: "review-comment",
488 reactions: [
489 { content: "rocket", count: 1, actors: ["reviewer"], viewerHasReacted: false },
490 ],
491 },
492 ],
493 );
494 const inlineComment = activity.comments[2];
495 assert.ok(inlineComment);
496 assert.deepStrictEqual(activity.reviewThreads[0]?.comments, [inlineComment]);
497 for (const reacted of [true, false]) {
498 yield* provider.setReaction({ ...input, subjectId: "review:8", content: "heart", reacted });
499 yield* provider.setReaction({ ...input, subjectId: "38", content: "rocket", reacted });
500 }
501 assert.deepStrictEqual(
502 writes.map(({ path, method, body }) => ({ path, method, body })),
503 [
504 {
505 path: "repos/maria/project/issues/comments/37/reactions",
506 method: "POST",
507 body: { content: "heart" },
508 },
509 {
510 path: "repos/maria/project/issues/comments/38/reactions",
511 method: "POST",
512 body: { content: "rocket" },
513 },
514 {
515 path: "repos/maria/project/issues/comments/37/reactions",
516 method: "DELETE",
517 body: { content: "heart" },
518 },
519 {
520 path: "repos/maria/project/issues/comments/38/reactions",
521 method: "DELETE",
522 body: { content: "rocket" },
523 },
524 ],
525 );
526 const missing = yield* provider
527 .setReaction({ ...input, subjectId: "review:9", content: "heart", reacted: true })
528 .pipe(Effect.result);
529 assert.strictEqual(missing._tag, "Failure");
530 if (missing._tag === "Failure") assert.include(missing.failure.detail, "comment ID");
531 assert.strictEqual(writes.length, 4);
532 responses["repos/maria/project/pulls/2/reviews/8/comments"] = Array.from(
533 { length: 501 },
534 (_, index) => ({
535 ...comment,
536 id: 1000 + index,
537 path: "file.ts",
538 position: 1,
539 original_position: 1,
540 commit_id: "head",
541 original_commit_id: "head",
542 resolver: null,
543 }),
544 );
545 for (let index = 0; index < 500; index++) {
546 responses[`repos/maria/project/issues/comments/${1000 + index}/reactions`] = [];
547 }
548 reactionReads = 0;
549 const bounded = yield* provider.getChangeRequestActivity(input);
550 assert.strictEqual(bounded.reviewThreads.length, 500);
551 assert.strictEqual(
552 bounded.comments.filter((entry) => entry.kind === "review-comment").length,
553 500,
554 );
555 assert.strictEqual(bounded.commentsTruncated, true);
556 assert.strictEqual(reactionReads, 502);
557 }).pipe(
558 Effect.provide(
559 Layer.mock(ForgejoCli.ForgejoCli)({
560 api: (input) => {
561 if (input.method) {
562 writes.push(input);
563 return Effect.succeed(processOutput("{}"));
564 }
565 const path = input.path.split("?")[0]!;
566 if (/\/issues\/comments\/\d+\/reactions$/.test(path)) reactionReads++;
567 assert.ok(Object.hasOwn(responses, path), `Unexpected Forgejo request: ${path}`);
568 const page = Number(new URLSearchParams(input.path.split("?")[1]).get("page"));
569 return encodeJsonEffect(page > 1 ? [] : responses[path]).pipe(
570 Effect.orDie,
571 Effect.map(processOutput),
572 );
573 },
574 }),
575 ),
576 );
577 },
578);
579​
580it.effect("discovers Forgejo accounts and retains the server port", () =>
581 Effect.gen(function* () {
582 const auth = ForgejoSourceControlProvider.discovery.parseAuth(
583 processOutput(
584 yield* encodeJsonEffect([
585 {
586 name: "work",
587 url: "http://forgejo.local:3000",
588 ssh_host: "git.forgejo.local",
589 user: "maria",
590 default: "true",
591 valid: "true",
592 },
593 ]),
594 ),
595 );
596 assert.deepStrictEqual(
597 firstNonEmptyLine("\u001b[1mtea version 0.16.0\u001b[0m\n"),
598 Option.some("tea version 0.16.0"),
599 );
600 assert.strictEqual(auth.status, "authenticated");
601 assert.deepStrictEqual(auth.account, Option.some("maria"));
602 assert.deepStrictEqual(auth.host, Option.some("forgejo.local:3000"));
603 const revoked = ForgejoSourceControlProvider.discovery.parseAuth(
604 processOutput(
605 encodeJson([
606 {
607 name: "work",
608 url: "http://forgejo.local:3000",
609 user: "maria",
610 default: "true",
611 valid: "false",
612 },
613 ]),
614 ),
615 );
616 assert.strictEqual(revoked.status, "unauthenticated");
617 const refined = ForgejoSourceControlProvider.discovery.refineUnknownRemote({
618 cwd: "/repo",
619 context: {
620 provider: {
621 kind: SourceControlProviderKind.make("unknown"),
622 name: "git.forgejo.local",
623 baseUrl: "https://git.forgejo.local",
624 },
625 remoteName: "origin",
626 remoteUrl: "git@git.forgejo.local:maria/project.git",
627 },
628 auth: processOutput(
629 yield* encodeJsonEffect([
630 {
631 name: "work",
632 url: "http://forgejo.local:3000",
633 ssh_host: "git.forgejo.local",
634 user: "maria",
635 default: "true",
636 },
637 ]),
638 ),
639 });
640 assert.deepStrictEqual(refined, {
641 kind: SourceControlProviderKind.make("forgejo"),
642 name: "Forgejo / Gitea",
643 baseUrl: "http://forgejo.local:3000",
644 });
645 }),
646);
647​
648it.effect("does not choose a default Forgejo login across ambiguous SSH server ports", () =>
649 Effect.gen(function* () {
650 const logins = ForgejoCli.parseForgejoLogins(
651 yield* encodeJsonEffect([
652 {
653 name: "one",
654 url: "http://forgejo.local:3000",
655 ssh_host: "forgejo.local",
656 user: "maria",
657 default: "true",
658 },
659 {
660 name: "two",
661 url: "http://forgejo.local:4000",
662 ssh_host: "forgejo.local",
663 user: "maria",
664 default: "false",
665 },
666 ]),
667 );
668 const remote = ForgejoCli.parseForgejoRemote("git@forgejo.local:maria/project.git");
669 assert.isNotNull(remote);
670 assert.deepStrictEqual(
671 ForgejoCli.parseForgejoRemote("forgejo.local:maria/project.git"),
672 remote,
673 );
674 assert.isUndefined(ForgejoCli.matchForgejoLogin(logins, remote!));
675 assert.strictEqual(
676 ForgejoCli.matchForgejoLogin(logins, remote!, "forgejo.local:4000")?.name,
677 "two",
678 );
679 assert.isUndefined(ForgejoCli.matchForgejoLogin(logins, remote!, "other.local:4000"));
680 const alias = ForgejoCli.parseForgejoRemote("git@ssh.forgejo.local:maria/project.git");
681 assert.isNotNull(alias);
682 assert.isUndefined(ForgejoCli.matchForgejoLogin(logins, alias!, "forgejo.local:4000"));
683 const refined = ForgejoSourceControlProvider.discovery.refineUnknownRemote({
684 cwd: "/repo",
685 context: {
686 provider: {
687 kind: SourceControlProviderKind.make("unknown"),
688 name: "Forgejo",
689 baseUrl: "https://forgejo.local",
690 },
691 remoteName: "origin",
692 remoteUrl: "git@forgejo.local:maria/project.git",
693 requestedHost: "forgejo.local:4000",
694 },
695 auth: processOutput(yield* encodeJsonEffect(logins)),
696 });
697 assert.strictEqual(refined?.baseUrl, "http://forgejo.local:4000");
698 const https = ForgejoCli.parseForgejoRemote("http://forgejo.local:4000/maria/project.git");
699 assert.isNotNull(https);
700 assert.strictEqual(ForgejoCli.matchForgejoLogin(logins, https!)?.name, "two");
701 const hostOnly = ForgejoCli.parseForgejoRemote("http://forgejo.local:4000");
702 assert.strictEqual(
703 ForgejoCli.matchForgejoLogin(logins, hostOnly!, undefined, true)?.name,
704 "two",
705 );
706 const mounted = logins.map((login) => ({
707 ...login,
708 url: `http://forgejo.local:4000/${login.name}`,
709 }));
710 assert.isUndefined(ForgejoCli.matchForgejoLogin(mounted, hostOnly!, undefined, true));
711 }),
712);
713​
714it.effect("rejects HTTP failures even when tea exits successfully", () =>
715 Effect.gen(function* () {
716 const cli = yield* ForgejoCli.make;
717 const result = yield* cli
718 .api({
719 cwd: "/repo",
720 repository: "http://forgejo.local:3000/maria/project",
721 path: "repos/maria/project/pulls/42",
722 method: "PATCH",
723 body: { state: "closed" },
724 })
725 .pipe(Effect.result);
726 assert.strictEqual(result._tag, "Failure");
727 if (result._tag === "Failure")
728 assert.strictEqual(
729 result.failure.detail,
730 "Forgejo repository or pull request was not found.",
731 );
732 }).pipe(
733 Effect.provideService(
734 FileSystem.FileSystem,
735 FileSystem.makeNoop({
736 exists: () => Effect.succeed(false),
737 }),
738 ),
739 Effect.provideService(
740 HttpClient.HttpClient,
741 HttpClient.make(() => {
742 throw new Error("tea must handle its own HTTP request");
743 }),
744 ),
745 Effect.provide(
746 TestSourceControlHost.layer({
747 process: {
748 run: (input) => {
749 if (input.args[0] === "api") {
750 assert.strictEqual(input.stdin, '{"state":"closed"}');
751 assert.include(input.args, "work");
752 assert.include(
753 input.args,
754 "http://forgejo.local:3000/api/v1/repos/maria/project/pulls/42",
755 );
756 }
757 return Effect.succeed(
758 input.args[0] === "login"
759 ? processOutput(
760 encodeJson([
761 {
762 name: "work",
763 url: "http://forgejo.local:3000",
764 ssh_host: "forgejo.local",
765 user: "maria",
766 default: "true",
767 },
768 ]),
769 )
770 : processOutput('{"message":"not found"}', { stderr: "HTTP/1.1 404 Not Found\n" }),
771 );
772 },
773 },
774 }),
775 ),
776 ),
777);
778​
779it.effect("routes mounted Forgejo repositories without repeating the mount in API paths", () =>
780 Effect.gen(function* () {
781 const cli = yield* ForgejoCli.make;
782 const viewer = yield* cli.api({ cwd: "/upstream-only", host: "code.test", path: "user" });
783 assert.strictEqual(viewer.stdout, "[]");
784 const mountedRepository = yield* cli.resolveRepository({
785 cwd: "/upstream-only",
786 host: "code.test",
787 repository: "maria/project",
788 });
789 assert.strictEqual(mountedRepository.baseUrl, "https://code.test/forgejo");
790 assert.strictEqual(mountedRepository.repository, "maria/project");
791 for (const path of [
792 "repos/forgejo/maria/project/pulls?state=open",
793 "repos/forgejo/maria/project",
794 "repos/reviewer/project/contents/file.ts",
795 ]) {
796 const result = yield* cli.api({
797 cwd: "/repo",
798 repository: "forgejo/maria/project",
799 context: {
800 provider: {
801 kind: SourceControlProviderKind.make("forgejo"),
802 name: "Forgejo",
803 baseUrl: "https://code.test/forgejo",
804 },
805 remoteName: "origin",
806 remoteUrl: "https://code.test/forgejo/maria/project.git",
807 },
808 path,
809 });
810 assert.strictEqual(result.stdout, "[]");
811 }
812 const sameOwnerAsMount = yield* cli.resolveRepository({
813 cwd: "/repo",
814 repository: "forgejo/project",
815 context: {
816 provider: {
817 kind: SourceControlProviderKind.make("forgejo"),
818 name: "Forgejo",
819 baseUrl: "https://code.test/forgejo",
820 },
821 remoteName: "origin",
822 remoteUrl: "ssh://git@code.test/forgejo/project.git",
823 },
824 });
825 assert.strictEqual(sameOwnerAsMount.command, "tea");
826 assert.strictEqual(sameOwnerAsMount.repository, "forgejo/project");
827 }).pipe(
828 Effect.provideService(
829 FileSystem.FileSystem,
830 FileSystem.makeNoop({
831 exists: () => Effect.succeed(true),
832 readFileString: () =>
833 Effect.succeed(
834 encodeJson({
835 hosts: { "code.test/forgejo": { type: "Application", token: "test-token" } },
836 }),
837 ),
838 }),
839 ),
840 Effect.provideService(
841 HttpClient.HttpClient,
842 HttpClient.make(() => {
843 throw new Error("tea must handle its own HTTP request");
844 }),
845 ),
846 Effect.provide(
847 TestSourceControlHost.layer({
848 process: {
849 run: (input) => {
850 if (input.command === "git")
851 return Effect.succeed(
852 processOutput("", { exitCode: ChildProcessSpawner.ExitCode(2) }),
853 );
854 if (input.args[0] === "login")
855 return Effect.succeed(
856 processOutput(
857 encodeJson([
858 {
859 name: "mounted",
860 url: "https://code.test/forgejo",
861 ssh_host: "code.test",
862 user: "maria",
863 default: "true",
864 },
865 ]),
866 ),
867 );
868 const supported = [
869 "https://code.test/forgejo/api/v1/user",
870 "https://code.test/forgejo/api/v1/repos/maria/project/pulls?state=open",
871 "https://code.test/forgejo/api/v1/repos/maria/project",
872 "https://code.test/forgejo/api/v1/repos/reviewer/project/contents/file.ts",
873 ];
874 if (input.args.at(-1)?.endsWith("/user")) assert.notInclude(input.args, "--repo");
875 assert.strictEqual(input.command, "tea");
876 return Effect.succeed(
877 supported.includes(input.args.at(-1) ?? "")
878 ? processOutput("[]", { stderr: "HTTP/1.1 200 OK\n" })
879 : processOutput("{}", { stderr: "HTTP/1.1 404 Not Found\n" }),
880 );
881 },
882 },
883 }),
884 ),
885 ),
886);
887​
888it.effect("prefers fj for HTTP and ported SSH aliases on root servers", () => {
889 const commands: string[] = [];
890 const requests: string[] = [];
891 return Effect.gen(function* () {
892 const cli = yield* ForgejoCli.make;
893 for (const remoteUrl of [
894 "http://forgejo.local:3000/maria/project.git",
895 "ssh://git@ssh.forgejo.local:2222/maria/project.git",
896 "ssh://git@forgejo.local:2222/maria/project.git",
897 ]) {
898 const result = yield* cli.api({
899 cwd: "/repo",
900 repository: "maria/project",
901 context: {
902 provider: {
903 kind: SourceControlProviderKind.make("forgejo"),
904 name: "Forgejo",
905 baseUrl: "http://forgejo.local:3000",
906 },
907 remoteName: "origin",
908 remoteUrl,
909 requestedHost: "forgejo.local:3000",
910 },
911 path: "repos/maria/project/issues/42/comments",
912 method: "POST",
913 body: { body: "verified through fj" },
914 });
915 assert.strictEqual(result.stdout, '{"id":99}');
916 }
917 assert.deepStrictEqual(commands, ["fj"]);
918 assert.deepStrictEqual(requests, [
919 "http://forgejo.local:3000/api/v1/repos/maria/project/issues/42/comments",
920 "http://forgejo.local:3000/api/v1/repos/maria/project/issues/42/comments",
921 "http://forgejo.local:3000/api/v1/repos/maria/project/issues/42/comments",
922 ]);
923 const viewer = yield* cli.api({
924 cwd: "/no-remotes",
925 host: "forgejo.local:3000",
926 path: "user",
927 });
928 assert.strictEqual(viewer.stdout, '{"login":"maria"}');
929 assert.strictEqual(requests.at(-1), "https://forgejo.local:3000/api/v1/user");
930 const upstreamViewer = yield* cli.api({
931 cwd: "/upstream-only",
932 host: "forgejo.local:3000",
933 path: "user",
934 });
935 assert.strictEqual(upstreamViewer.stdout, '{"login":"maria"}');
936 assert.strictEqual(requests.at(-1), "http://forgejo.local:3000/api/v1/user");
937 const upstreamRepository = yield* cli.resolveRepository({
938 cwd: "/upstream-only",
939 host: "forgejo.local:3000",
940 repository: "maria/project",
941 });
942 assert.strictEqual(upstreamRepository.baseUrl, "http://forgejo.local:3000");
943 assert.strictEqual(upstreamRepository.repository, "maria/project");
944 const httpViewer = yield* cli.api({ cwd: "/repo", host: "forgejo.local:3000", path: "user" });
945 assert.strictEqual(httpViewer.stdout, '{"login":"maria"}');
946 assert.strictEqual(requests.at(-1), "http://forgejo.local:3000/api/v1/user");
947 }).pipe(
948 Effect.provideService(
949 FileSystem.FileSystem,
950 FileSystem.makeNoop({
951 exists: () => Effect.succeed(true),
952 readFileString: () =>
953 Effect.succeed(
954 encodeJson({
955 hosts: {
956 "forgejo.local:3000": { type: "Application", token: "test-token" },
957 "forgejo.local:4000": { type: "Application", token: "other-token" },
958 },
959 aliases: { "ssh.forgejo.local:2222": "forgejo.local:3000" },
960 }),
961 ),
962 }),
963 ),
964 Effect.provideService(
965 HttpClient.HttpClient,
966 HttpClient.make((request) => {
967 requests.push(request.url);
968 if (request.url.endsWith("/user")) {
969 assert.strictEqual(request.method, "GET");
970 assert.strictEqual(request.headers.authorization, "token test-token");
971 return Effect.succeed(
972 HttpClientResponse.fromWeb(request, new Response('{"login":"maria"}')),
973 );
974 }
975 assert.strictEqual(request.method, "POST");
976 assert.strictEqual(request.headers.authorization, "token test-token");
977 assert.deepStrictEqual(requestJson(request), { body: "verified through fj" });
978 return Effect.succeed(
979 HttpClientResponse.fromWeb(request, new Response('{"id":99}', { status: 201 })),
980 );
981 }),
982 ),
983 Effect.provide(
984 TestSourceControlHost.layer({
985 process: {
986 run: (input) => {
987 commands.push(input.command);
988 if (input.command === "git")
989 return Effect.succeed(
990 input.cwd === "/no-remotes"
991 ? processOutput("", { exitCode: ChildProcessSpawner.ExitCode(2) })
992 : processOutput(
993 input.cwd === "/upstream-only"
994 ? "upstream\thttp://forgejo.local:3000/maria/project.git (fetch) [blob:none]\nother\thttp://forgejo.local:3000/maria/other.git (fetch) [blob:none]\nunrelated\thttp://other.local:3000/maria/project.git (fetch) [blob:none]"
995 : "origin\thttp://forgejo.local:3000/maria/project.git (fetch)\nother\thttp://forgejo.local:3000/maria/other.git (fetch)\nunrelated\thttp://other.local:3000/maria/project.git (fetch)",
996 ),
997 );
998 assert.strictEqual(input.command, "fj");
999 assert.deepStrictEqual(input.args, [
1000 "--host",
1001 input.cwd === "/no-remotes"
1002 ? "https://forgejo.local:3000"
1003 : "http://forgejo.local:3000",
1004 "whoami",
1005 ]);
1006 return Effect.succeed(processOutput(""));
1007 },
1008 },
1009 }),
1010 ),
1011 );
1012});
1013​
1014it.effect("loads later fj review pages when the server caps pages below the requested size", () => {
1015 const pages: number[] = [];
1016 let issueCommentRequests = 0;
1017 return Effect.gen(function* () {
1018 const cli = yield* ForgejoCli.make;
1019 const provider = yield* ForgejoPullRequestProvider.make.pipe(
1020 Effect.provideService(ForgejoCli.ForgejoCli, cli),
1021 );
1022 const activity = yield* provider.getChangeRequestActivity({
1023 cwd: "/repo",
1024 repository: "maria/project",
1025 host: "forgejo.test",
1026 number: 42,
1027 });
1028 assert.strictEqual(activity.commentCount, 42);
1029 assert.strictEqual(activity.comments.at(-1)?.id, "review:41");
1030 assert.strictEqual(activity.commentsTruncated, false);
1031 assert.deepStrictEqual(pages, [1, 2, 3]);
1032 assert.strictEqual(issueCommentRequests, 1);
1033 }).pipe(
1034 Effect.provideService(
1035 FileSystem.FileSystem,
1036 FileSystem.makeNoop({
1037 exists: () => Effect.succeed(true),
1038 readFileString: () =>
1039 Effect.succeed(
1040 encodeJson({ hosts: { "forgejo.test": { type: "Application", token: "test-token" } } }),
1041 ),
1042 }),
1043 ),
1044 Effect.provideService(
1045 HttpClient.HttpClient,
1046 HttpClient.make((request) => {
1047 const url = new URL(request.url);
1048 if (url.pathname === "/api/v1/repos/maria/project/issues/42/comments") {
1049 issueCommentRequests++;
1050 return Effect.succeed(
1051 HttpClientResponse.fromWeb(
1052 request,
1053 new Response(
1054 encodeJson([
1056 id: 100,
1057 body: "Unpaginated issue comment",
1058 user: { login: "maria" },
1059 created_at: "2026-09-13T00:00:00Z",
1060 },
1061 ]),
1062 ),
1063 ),
1064 );
1066 if (url.pathname.endsWith("/reviews")) {
1067 const page = Number(url.searchParams.get("page"));
1068 pages.push(page);
1069 assert.ok(page >= 1 && page <= 3);
1070 const reviews = Array.from({ length: page < 3 ? 20 : 1 }, (_, index) => ({
1071 id: (page - 1) * 20 + index + 1,
1072 body: "Review from a capped page",
1073 user: { login: "maria" },
1074 state: "COMMENT",
1075 submitted_at: "2026-09-13T00:00:00Z",
1076 comments_count: 0,
1077 }));
1078 return Effect.succeed(
1079 HttpClientResponse.fromWeb(
1080 request,
1081 new Response(encodeJson(reviews), {
1082 headers:
1083 page === 2
1084 ? {}
1085 : {
1086 Link:
1087 page === 1
1088 ? `<${url.origin}${url.pathname}?limit=50&page=2>; rel="next"`
1089 : `<${url.origin}${url.pathname}?limit=50&page=1>; rel="prev"`,
1090 },
1091 }),
1092 ),
1093 );
1095 return Effect.succeed(
1096 HttpClientResponse.fromWeb(
1097 request,
1098 new Response(encodeJson(url.pathname === "/api/v1/user" ? { login: "maria" } : [])),
1099 ),
1100 );
1101 }),
1102 ),
1103 Effect.provide(
1104 TestSourceControlHost.layer({
1105 process: {
1106 run: (input) => {
1107 if (input.command === "git") {
1108 assert.deepStrictEqual(input.args, ["remote", "-v"]);
1109 return Effect.succeed(
1110 processOutput("origin\thttps://forgejo.test/maria/project.git (fetch)"),
1111 );
1113 assert.strictEqual(input.command, "fj");
1114 assert.deepStrictEqual(input.args, ["--host", "https://forgejo.test", "whoami"]);
1115 return Effect.succeed(processOutput(""));
1116 },
1117 },
1118 }),
1119 ),
1120 );
1121});
1122​
1123it.effect("handles fj mutation statuses without retrying failures or reading absent bodies", () =>
1124 Effect.gen(function* () {
1125 for (const status of [204, 205, 302, 401, 403, 404, 429, 500]) {
1126 let writes = 0;
1127 yield* Effect.gen(function* () {
1128 const cli = yield* ForgejoCli.make;
1129 const result = yield* cli
1130 .api({
1131 cwd: "/repo",
1132 repository: "https://forgejo.local/maria/project",
1133 path: "repos/maria/project/issues/42/comments",
1134 method: "POST",
1135 body: { body: "only once" },
1136 })
1137 .pipe(Effect.result);
1138 assert.strictEqual(result._tag, status < 300 ? "Success" : "Failure");
1139 if (result._tag === "Success") assert.strictEqual(result.success.stdout, "");
1140 if (result._tag === "Failure") {
1141 assert.strictEqual(result.failure.command, "fj");
1142 assert.strictEqual(result.failure.httpStatus, status);
1144 assert.strictEqual(writes, 1);
1145 }).pipe(
1146 Effect.provideService(
1147 FileSystem.FileSystem,
1148 FileSystem.makeNoop({
1149 exists: () => Effect.succeed(true),
1150 readFileString: () =>
1151 Effect.succeed(
1152 encodeJson({
1153 hosts: {
1154 "forgejo.local": { type: "Application", token: "test-token" },
1155 },
1156 }),
1157 ),
1158 }),
1159 ),
1160 Effect.provideService(
1161 HttpClient.HttpClient,
1162 HttpClient.make((request) => {
1163 writes++;
1164 assert.strictEqual(
1165 request.url,
1166 "https://forgejo.local/api/v1/repos/maria/project/issues/42/comments",
1167 );
1168 return Effect.succeed(
1169 HttpClientResponse.fromWeb(
1170 request,
1171 new Response(status < 300 ? null : "", {
1172 status,
1173 headers: { location: "https://other.local/" },
1174 }),
1175 ),
1176 );
1177 }),
1178 ),
1179 Effect.provide(
1180 TestSourceControlHost.layer({
1181 process: {
1182 run: (input) => {
1183 assert.strictEqual(
1184 input.command,
1185 "fj",
1186 "a failed mutation must never switch accounts or CLI",
1187 );
1188 return Effect.succeed(processOutput(""));
1189 },
1190 },
1191 }),
1192 ),
1193 );
1195 }),
1197​
1198it.effect(
1199 "discovers fj first and retains configured authentication failures instead of switching accounts",
1200 () =>
1201 Effect.gen(function* () {
1202 for (const scenario of ["authenticated", "revoked", "missing", "invalid-storage"] as const) {
1203 const commands: string[] = [];
1204 yield* Effect.gen(function* () {
1205 const spec = yield* ForgejoSourceControlProvider.makeDiscovery;
1206 assert.strictEqual(spec.type, "managed-cli");
1207 if (spec.type !== "managed-cli") return;
1208 const result = yield* spec.probe("/repo");
1209 assert.strictEqual(result.executable, scenario === "missing" ? "tea" : "fj");
1210 assert.strictEqual(
1211 result.auth.status,
1212 scenario === "revoked"
1213 ? "unauthenticated"
1214 : scenario === "invalid-storage"
1215 ? "unknown"
1216 : "authenticated",
1217 );
1218 if (scenario !== "revoked" && scenario !== "invalid-storage")
1219 assert.deepStrictEqual(result.auth.host, Option.some("forgejo.local:3000"));
1220 assert.deepStrictEqual(
1221 result.auth.account,
1222 scenario === "authenticated" || scenario === "missing"
1223 ? Option.some("maria")
1224 : Option.none(),
1225 );
1226 assert.strictEqual(
1227 commands.some((command) => command.startsWith("tea ")),
1228 scenario === "missing",
1229 );
1230 assert.include(commands, "fj version");
1231 }).pipe(
1232 Effect.provide(
1233 Layer.mergeAll(
1234 Layer.mock(ForgejoCli.ForgejoCli)({
1235 getAccount: (input) => {
1236 assert.strictEqual(scenario, "authenticated");
1237 assert.deepStrictEqual(input, {
1238 cwd: "/repo",
1239 baseUrl: "http://forgejo.local:3000",
1240 });
1241 return Effect.succeed("maria");
1242 },
1243 listLogins: (input) => {
1244 assert.strictEqual(
1245 input.remoteUrl,
1246 "http://forgejo.local:3000/maria/project.git",
1247 );
1248 if (scenario === "invalid-storage")
1249 return Effect.fail(
1250 new ForgejoCli.ForgejoCliError({
1251 command: "fj",
1252 cwd: input.cwd,
1253 reason: "authentication",
1254 detail: "fj authentication storage is invalid.",
1255 }),
1256 );
1257 return Effect.succeed([
1259 name: "forgejo.local:3000",
1260 url: "http://forgejo.local:3000",
1261 user: "",
1262 default: "false",
1263 },
1264 ]);
1265 },
1266 }),
1267 TestSourceControlHost.layer({
1268 process: {
1269 run: (input) => {
1270 commands.push(`${input.command} ${input.args.join(" ")}`);
1271 if (input.command === "git")
1272 return Effect.succeed(
1273 processOutput("http://forgejo.local:3000/maria/project.git\n"),
1274 );
1275 if (input.command === "fj") {
1276 if (scenario === "missing")
1277 return Effect.fail(
1278 new VcsProcessSpawnError({
1279 operation: input.operation,
1280 command: input.command,
1281 cwd: input.cwd,
1282 cause: new Error("fj not found"),
1283 }),
1284 );
1285 if (input.args[0] === "version")
1286 return Effect.succeed(processOutput("fj 0.10.0"));
1287 if (scenario === "invalid-storage") {
1288 assert.deepStrictEqual(input.args, ["auth", "list"]);
1289 return Effect.succeed(processOutput(""));
1291 assert.deepStrictEqual(input.args, [
1292 "--host",
1293 "http://forgejo.local:3000",
1294 "whoami",
1295 ]);
1296 return Effect.succeed(
1297 processOutput("", {
1298 exitCode: ChildProcessSpawner.ExitCode(scenario === "revoked" ? 1 : 0),
1299 }),
1300 );
1302 assert.strictEqual(input.command, "tea");
1303 return Effect.succeed(
1304 input.args[0] === "--version"
1305 ? processOutput("tea version 0.16.0")
1306 : processOutput(
1307 encodeJson([
1309 name: "work",
1310 url: "http://forgejo.local:3000",
1311 user: "maria",
1312 default: "true",
1313 valid: "true",
1314 },
1315 ]),
1316 ),
1317 );
1318 },
1319 },
1320 }),
1321 ),
1322 ),
1323 );
1325 }),