Public: anyone can read this; the crew can change it.

`forge runs` lists what the crew is doing on the repository of the folder you are in: running and recent runs, with state, agent and cost #7367

Parked opened this
Closed without merging

mason/forge:mason/7353-forge-runs-lists-what-the-crew-is-doing → main 5 commits fork 2 threads · 2 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
10 files changed +459 −19
README.md +6
@@ -311,6 +311,7 @@ forge sync --ff # fast-forward clean repos, and only those
311311 forge pin owner/name # ask the workbench to keep this one here
312312 forge ls # what is here, and how stale
313313 forge open owner/name --web # the page, in a browser
314 forge runs # what the crew is doing on this folder's repo
314315 forge asks # what waits on you, most important first
315316 forge asks --repo owner/name # only that repository's; --json for the API's answer
316317 ```
@@ -326,6 +327,11 @@ and left exactly as you left it.
326327 `origin` was edited to anywhere else is fetched without the token, and its row
327328 says `no token sent`.
328329
330 `forge runs` reads the repository this folder's `origin` points at (or
331 `--repo owner/name`) and prints its last ten runs: state, agent, `#N`, title,
332 age and cost. `--json` prints the forge's rows unchanged, each carrying
333 `agent`, `number` and `title` beside the run's own fields.
334
329335 `forge` with no arguments opens the local UI on the same runtime as the SSH
330336 one: the library of clones, then a lazygit-shaped working-tree screen —
331337 `space` stages, `enter` opens the hunks, `s` stages one, `c` commits, `P`
src/cli/api.ts +22
@@ -191,6 +191,28 @@ export class ForgeApi {
191191 );
192192 }
193193
194 /**
195 * A repository's runs, newest first, exactly as the forge lists them —
196 * `forge runs --json` prints these rows unchanged, so nothing is dropped.
197 */
198 async runs(
199 owner: string,
200 name: string,
201 limit: number,
202 ): Promise<ApiResult<Record<string, unknown>[]>> {
203 const out = await this.call<{ items?: unknown }>(
204 `/api/v1/repos/${encode(owner)}/${encode(name)}/runs?limit=${limit}`,
205 );
206 if (!out.ok) return out;
207 const items = out.value.items;
208 if (!Array.isArray(items)) return ok([]);
209 return ok(
210 items.filter(
211 (x): x is Record<string, unknown> => typeof x === "object" && x !== null,
212 ),
213 );
214 }
215
194216 /**
195217 * What waits on the user, most consequential first (`GET /api/v1/asks`).
196218 * A row of a kind this client has never heard of is kept, not dropped: it
src/cli/args.ts +27
@@ -86,6 +86,33 @@ export function parseDuration(text: string | undefined): number | undefined {
8686 }
8787 }
8888
89 /**
outdated

This was parseRepoRef's doc comment, and it is now left above repoFromRemote's doc block (two JSDoc blocks in a row; parseRepoRef has none). Move it back to just above export function parseRepoRef.

90 * `owner/name` from a git remote URL — `https://host/o/n.git`,
91 * `ssh://git@host:2222/o/n.git` or `git@host:o/n.git`: the last two path
92 * segments, `.git` dropped. Anything else is undefined, never a guess.
93 */
94 export function repoFromRemote(
95 url: string | null | undefined,
96 ): { owner: string; name: string } | undefined {
97 if (url === null || url === undefined) return undefined;
98 const text = url.trim();
99 let path: string;
100 const scp = /^[^/@:]+@[^/:]+:(.+)$/.exec(text);
101 if (scp !== null) path = scp[1]!;
102 else {
103 try {
104 path = new URL(text).pathname;
105 } catch {
106 return undefined;
107 }
108 }
109 const parts = path.replace(/\/+$/, "").split("/");
110 const name = parts.pop()?.replace(/\.git$/, "");
111 const owner = parts.pop();
112 if (owner === undefined || name === undefined) return undefined;
113 return parseRepoRef(`${owner}/${name}`);
114 }
115
89116 /** `owner/name`, rejected as a pair rather than guessed at. */
90117 export function parseRepoRef(
91118 text: string | undefined,
src/cli/main.ts +95 −1
@@ -7,6 +7,7 @@
77 * forge sync clone what is missing, fetch the rest, report
88 * forge status the same report without touching the network
99 * forge asks what waits on you, most important first
10 * forge runs what the crew is doing on this folder's repo
1011 *
1112 * Everything here is a thin shell around three modules: `api.ts` talks to the
1213 * workbench, `sync.ts` decides what should be on disk, `report.ts` prints it.
@@ -14,7 +15,13 @@
1415 * an exit code — so a script can branch on the result without parsing text.
1516 */
1617
17 import { parseArgs, parseDuration, parseRepoRef, type Args } from "./args.ts";
18 import {
19 parseArgs,
20 parseDuration,
21 parseRepoRef,
22 repoFromRemote,
23 type Args,
24 } from "./args.ts";
1825 import { ForgeApi, type Ask } from "./api.ts";
1926 import {
2027 clearConfig,
@@ -36,6 +43,7 @@ import {
3643 type RepoReport,
3744 type SyncReport,
3845 } from "./sync.ts";
46 import { remoteUrl } from "../git/local.ts";
3947 import { G } from "../tui/term/screen.ts";
4048 import { trackText } from "../tui/local/common.ts";
4149 import { displayWidth, pad, truncate } from "../tui/term/width.ts";
@@ -101,6 +109,8 @@ export async function main(argv: readonly string[]): Promise<number> {
101109 return openRepo(out, args);
102110 case "asks":
103111 return asks(out, args);
112 case "runs":
113 return runs(out, args);
104114 case "ui":
105115 return openTui(out, args);
106116 default:
@@ -130,6 +140,9 @@ function usage(out: Out): void {
130140 out.line(
131141 b(" forge asks") + " [--repo owner/name] [--json]",
132142 );
143 out.line(
144 b(" forge runs") + " [--repo owner/name] [--json]",
145 );
133146 out.line();
134147 out.line(
135148 out.paint(` config ${configPath()} root ${rootDir()}`, out.c.faint),
@@ -494,6 +507,87 @@ function onlyRepo(raw: unknown, repo: string): unknown {
494507 };
495508 }
496509
510 // ── runs ─────────────────────────────────────────────────────────────────
511
512 const RUNS_SHOWN = 10;
513
514 /**
515 * What the crew is doing here: the last runs of the repository this folder
516 * is a clone of (its `origin`), or of `--repo owner/name`.
517 */
518 async function runs(out: Out, args: Args): Promise<number> {
519 const named = args.value("repo");
520 const ref =
521 named === undefined
522 ? repoFromRemote(await remoteUrl(process.cwd()))
523 : parseRepoRef(named);
524 if (ref === undefined) {
525 out.err(
526 named === undefined
527 ? "forge runs: this folder has no origin naming owner/name — pass --repo owner/name"
528 : "forge runs: --repo expects owner/name",
529 );
530 return EXIT.usage;
531 }
532 const loaded = await requireConfig(out);
533 if (typeof loaded === "number") return loaded;
534 const api = new ForgeApi(loaded.url, loaded.token);
535 const result = await api.runs(ref.owner, ref.name, RUNS_SHOWN);
536 if (!result.ok) {
537 out.err(`forge runs: ${result.error.message}`);
538 return result.error.status === 401 ? EXIT.notConfigured : EXIT.failed;
539 }
540 if (args.flag("json")) {
541 out.line(JSON.stringify(result.value));
542 return EXIT.ok;
543 }
544 if (result.value.length === 0) {
545 out.line(`no runs on ${ref.owner}/${ref.name} yet`);
546 return EXIT.ok;
547 }
548 out.table(
549 [
550 { header: "STATE" },
551 { header: "AGENT", max: 20 },
552 { header: "#", align: "right" },
553 { header: "TITLE", max: 56 },
554 { header: "AGE", align: "right" },
555 { header: "COST", align: "right" },
556 ],
557 result.value.map((r) => {
558 const state = text(r["state"]);
559 const number = r["number"];
560 const cost = r["costUsd"];
561 return [
562 cell(state, stateColor(out, state)),
563 cell(text(r["agent"]) || text(r["kind"]), out.c.fg),
564 cell(typeof number === "number" ? `#${number}` : "", out.c.mutedFg),
565 cell(text(r["title"]) || text(r["summary"]), out.c.fg),
566 cell(age(r["createdAt"]), out.c.faint),
567 cell(typeof cost === "number" && cost > 0 ? `$${cost.toFixed(2)}` : "", out.c.mutedFg),
568 ];
569 }),
570 );
571 return EXIT.ok;
572 }
573
574 function stateColor(out: Out, state: string): Out["c"]["fg"] {
575 if (state === "running") return out.c.accent;
576 if (state === "ok") return out.c.success;
577 if (state === "failed") return out.c.danger;
578 if (state === "queued") return out.c.attn;
579 return out.c.mutedFg;
580 }
581
582 function text(value: unknown): string {
583 return typeof value === "string" ? value : "";
584 }
585
586 function age(value: unknown): string {
587 const when = typeof value === "string" ? new Date(value) : null;
588 return when === null || Number.isNaN(when.getTime()) ? "" : since(when);
589 }
590
497591 // ── the terminal UI ──────────────────────────────────────────────────────
498592
499593 async function openTui(out: Out, args: Args): Promise<number> {
src/contract/openapi/routes/getApiV1ReposOwnerNameRuns.ts +1 −1
@@ -1,3 +1,3 @@
11 import { REPO, type Route } from "../shared.ts";
22
3 export const route: Route = { method: "get", path: `${REPO}/runs`, summary: "List a repository's runs, newest first: { items, next_cursor }; kind deploy or agent, env an environment name, limit 1 to 200 (default 50), cursor a run id; a stranger's runs carry no cost, turns, agent session or node", auth: false, query: { kind: "string", env: "string", limit: "integer", cursor: "string" } };
3 export const route: Route = { method: "get", path: `${REPO}/runs`, summary: "List a repository's runs, newest first: { items, next_cursor }, each row naming its agent, number and title; kind deploy or agent, env an environment name, limit 1 to 200 (default 50), cursor a run id; a stranger's runs carry no cost, turns, agent session or node", auth: false, query: { kind: "string", env: "string", limit: "integer", cursor: "string" } };
src/core/run_labels.ts added +52
@@ -0,0 +1,52 @@
1 /**
2 * What a run is called: who worked it, which issue or pull it is about, and
3 * that issue's title. One place, so the runs page (`web/pages/runs.ts`) and
4 * the API's runs list — and so `forge runs` — cannot drift on it. Both
5 * lookups are one grouped read for a whole page of runs.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { getIssuesByIds, type Issue } from "./issues.ts";
10 import type { Run } from "./runs.ts";
11 import { getUsersByIds, type User } from "./users.ts";
12
13 export interface LabelledRun extends Run {
14 /** The agent's username for an agent run; whoever triggered it otherwise. */
15 readonly agent: string | null;
16 /** The issue or pull number, or a preview's pull from its env name. */
17 readonly number: number | null;
18 readonly title: string | null;
19 }
20
21 /** The pull a preview environment is for, from its name; production has none. */
22 export function envNumber(env: string): number | undefined {
23 if (!env.startsWith("pull-")) return undefined;
24 const n = Number(env.slice(5));
25 return Number.isInteger(n) && n > 0 ? n : undefined;
26 }
27
28 /** Every actor the runs name, in one read. */
29 export function runActors(db: Database, runs: readonly Run[]): Map<string, User> {
30 return getUsersByIds(db, runs.map((run) => run.actorId ?? "").filter(Boolean));
31 }
32
33 /** Every pull or issue the runs are about, in one read. */
34 export function runIssues(db: Database, runs: readonly Run[]): Map<string, Issue> {
35 return getIssuesByIds(db, runs.map((run) => run.issueId ?? "").filter(Boolean));
36 }
37
38 /** The runs as the API lists them: each row with its agent, number and title. */
39 export function labelRuns(db: Database, runs: readonly Run[]): LabelledRun[] {
40 const users = runActors(db, runs);
41 const issues = runIssues(db, runs);
42 return runs.map((run) => {
43 const issue = run.issueId === null ? undefined : issues.get(run.issueId);
44 const actor = run.actorId === null ? undefined : users.get(run.actorId);
45 return {
46 ...run,
47 agent: actor?.username ?? null,
48 number: issue?.number ?? envNumber(run.env) ?? null,
49 title: issue?.title ?? null,
50 };
51 });
52 }
src/http/api.ts +5 −1
@@ -209,6 +209,7 @@ import {
209209 type User,
210210 } from "../core/users.ts";
211211 import { isPinned } from "../core/pins.ts";
212 import { labelRuns } from "../core/run_labels.ts";
212213 import { diffCommit } from "../git/diff.ts";
213214 import { runGit } from "../git/env.ts";
214215 import { appLimitWords, appsOwnedBy } from "../actions/app_limit.ts";
@@ -4643,7 +4644,10 @@ export function apiRoutes(router: Router<Handler>): void {
46434644 if (!runs.ok) return notFound();
46444645 // Already as this reader may see them (`runForReader`): a stranger's
46454646 // runs carry no cost, turns, agent session or node.
4646 return timePhase(ctx.request, "render", () => json(paged(runs.value, limit, (r) => r.id)));
4647 // Each row names its agent, number and title (`run_labels.ts`).
4648 return timePhase(ctx.request, "render", () =>
4649 json(paged(labelRuns(ctx.app.db, runs.value), limit, (r) => r.id)),
4650 );
46474651 });
46484652
46494653 router.add("GET", "/api/v1/repos/:owner/:name/runs/:id", (ctx) => {
src/web/pages/runs.ts +7 −16
@@ -20,16 +20,17 @@ import {
2020 runLog,
2121 steerRepoRun,
2222 } from "../../actions/runs.ts";
23 import { getIssuesByIds, type Issue } from "../../core/issues.ts";
23 import type { Issue } from "../../core/issues.ts";
2424 import {
2525 canRead,
2626 canSeeOwnerFacts,
2727 getRepoById,
2828 type Repo,
2929 } from "../../core/repos.ts";
30 import { envNumber, runActors, runIssues } from "../../core/run_labels.ts";
3031 import { getRun, type Run, type RunKind } from "../../core/runs.ts";
3132 import { getUsage, issueUsage } from "../../core/usage.ts";
32 import { getUsersByIds, type User } from "../../core/users.ts";
33 import type { User } from "../../core/users.ts";
3334 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
3435 import type { Ctx } from "../../http/context.ts";
3536 import { loadRepo, notFoundPage, repoBase, signInFirst } from "../chrome.ts";
@@ -50,10 +51,6 @@ import {
5051
5152 // ---- words ----
5253
53 /** The pull a preview environment is for, from its name; production has none. */
54 const envNumber = (env: string): number | undefined =>
55 env.startsWith("pull-") ? Number(env.slice(5)) : undefined;
56
5754 /**
5855 * What a run is, in a few words, naming the pull or issue it is about:
5956 * `Deploy production`, `Deploy preview #3 Say hello`, `bot on #1 Do a
@@ -205,20 +202,14 @@ export function durationText(run: Run): string | undefined {
205202 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
206203 }
207204
208 /** Every actor the runs name, in one read. */
205 /** Every actor the runs name, in one read (`core/run_labels.ts`). */
209206 export function actorsFor(ctx: Ctx, runs: readonly Run[]): Map<string, User> {
210 return getUsersByIds(
211 ctx.app.db,
212 runs.map((run) => run.actorId ?? "").filter(Boolean),
213 );
207 return runActors(ctx.app.db, runs);
214208 }
215209
216 /** Every pull or issue the runs are about, in one read. */
210 /** Every pull or issue the runs are about, in one read (`core/run_labels.ts`). */
217211 export function issuesFor(ctx: Ctx, runs: readonly Run[]): Map<string, Issue> {
218 return getIssuesByIds(
219 ctx.app.db,
220 runs.map((run) => run.issueId ?? "").filter(Boolean),
221 );
212 return runIssues(ctx.app.db, runs);
222213 }
223214
224215 /** The run's title, with both grouped reads resolved. */
test/api-runs-labels.test.ts added +75
@@ -0,0 +1,75 @@
1 /**
2 * The API's runs list names each row's agent, number and title (#7353), so
3 * `forge runs` answers in one request; the rest of the row is unchanged.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { createIssue } from "../src/core/issues.ts";
12 import { createRun } from "../src/core/runs.ts";
13 import { createSession } from "../src/core/sessions.ts";
14 import { createUser } from "../src/core/users.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17
18 quietLogs();
19
20 let dataDir: string;
21 let app: App;
22 let servers: Servers;
23 let cookie = "";
24 let issueNumber = 0;
25
26 const cells = process.env["FORGE_CELLS"];
27
28 beforeAll(async () => {
29 process.env["FORGE_CELLS"] = "off";
30 dataDir = await mkdtemp(join(tmpdir(), "forge-api-runs-labels-"));
31 app = createApp({ dataDir, port: 0 });
32 servers = await serve(app);
33 const made = await createUser(app.db, {
34 origin: "seed",
35 trusted: true,
36 username: "alice",
37 email: "[email protected]",
38 password: "a-good-passphrase",
39 adminIfFirst: true,
40 });
41 if (!made.ok) throw new Error(String(made.error));
42 const alice = made.value;
43 cookie = `forge_session=${createSession(app.db, alice.id).token}`;
44 const repo = await createRepo(app, alice, { name: "r", visibility: "public" });
45 if (!repo.ok) throw new Error(String(repo.error));
46 const made2 = createIssue(app.db, { repoId: repo.value.id, authorId: alice.id, title: "Say hello" });
47 if (!made2.ok) throw new Error(String(made2.error));
48 const issue = made2.value;
49 issueNumber = issue.number;
50 createRun(app.db, { repoId: repo.value.id, kind: "deploy", env: "production" });
51 createRun(app.db, { repoId: repo.value.id, kind: "deploy", env: "pull-41" });
52 createRun(app.db, { repoId: repo.value.id, kind: "agent", issueId: issue.id, actorId: alice.id });
53 });
54 afterAll(async () => {
55 await servers.stop();
56 app.close();
57 if (cells === undefined) delete process.env["FORGE_CELLS"];
58 else process.env["FORGE_CELLS"] = cells;
59 await rm(dataDir, { recursive: true, force: true });
60 });
61
62 test("each run row carries agent, number and title beside its own fields", async () => {
63 const res = await fetch(`${servers.url}/api/v1/repos/alice/r/runs`, { headers: { cookie } });
64 expect(res.status).toBe(200);
65 const rows = ((await res.json()) as { items: Record<string, unknown>[] }).items;
66 const labels = rows.map((r) => [r["kind"], r["agent"], r["number"], r["title"]]);
67 expect(labels).toContainEqual(["agent", "alice", issueNumber, "Say hello"]);
68 expect(labels).toContainEqual(["deploy", null, 41, null]);
69 expect(labels).toContainEqual(["deploy", null, null, null]);
70 for (const r of rows) {
71 expect(typeof r["id"]).toBe("string");
72 expect(typeof r["state"]).toBe("string");
73 expect(typeof r["createdAt"]).toBe("string");
74 }
75 });
test/cli-runs.test.ts added +169
@@ -0,0 +1,169 @@
1 /**
2 * `forge runs` (#7353): the CLI as a shell runs it — a process, an
3 * environment, a folder — against a fake forge that records what it was
4 * asked and answers the runs list.
5 */
6
7 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { repoFromRemote } from "../src/cli/args.ts";
12 import { gitClientEnv } from "./helpers/git-client.ts";
13
14 const CLI = new URL("../src/cli/main.ts", import.meta.url).pathname;
15
16 const minute = 60_000;
17 const ROWS = [
18 {
19 id: "r1",
20 kind: "agent",
21 state: "running",
22 agent: "mason",
23 number: 7353,
24 title: "forge runs lists what the crew is doing",
25 summary: "",
26 costUsd: 1.234,
27 createdAt: new Date(Date.now() - 3 * minute).toISOString(),
28 },
29 {
30 id: "r2",
31 kind: "check",
32 state: "failed",
33 agent: "alice",
34 number: 12,
35 title: null,
36 summary: "check failed in 9s",
37 costUsd: 0,
38 createdAt: new Date(Date.now() - 2 * 60 * minute).toISOString(),
39 },
40 ];
41
42 let server: ReturnType<typeof Bun.serve>;
43 let base = "";
44 let dir = "";
45 const asked: string[] = [];
46
47 beforeAll(async () => {
48 server = Bun.serve({
49 port: 0,
50 fetch(req) {
51 const url = new URL(req.url);
52 asked.push(`${url.pathname}${url.search}`);
53 if (req.headers.get("authorization") === "Bearer stale")
54 return Response.json({ error: "unauthorized", message: "token expired" }, { status: 401 });
55 if (url.pathname === "/api/v1/repos/alice/app/runs")
56 return Response.json({ items: ROWS, next_cursor: null });
57 if (url.pathname === "/api/v1/repos/alice/empty/runs")
58 return Response.json({ items: [], next_cursor: null });
59 return Response.json({ error: "not_found", message: "not found" }, { status: 404 });
60 },
61 });
62 base = `http://127.0.0.1:${server.port}`;
63 dir = await mkdtemp(join(tmpdir(), "forge-cli-runs-"));
64 const git = (args: string[]) =>
65 Bun.spawnSync(["git", ...args], { cwd: dir, env: gitClientEnv() });
66 git(["init", "-q"]);
67 git(["remote", "add", "origin", `${base}/alice/app.git`]);
68 });
69
70 afterAll(async () => {
71 server.stop(true);
72 await rm(dir, { recursive: true, force: true });
73 });
74
75 async function forge(
76 args: string[],
77 env: Record<string, string> = {},
78 ): Promise<{ code: number; out: string; err: string }> {
79 const proc = Bun.spawn(["bun", CLI, "runs", ...args], {
80 cwd: dir,
81 env: {
82 PATH: process.env["PATH"] ?? "",
83 HOME: dir,
84 FORGE_CONFIG_DIR: join(dir, ".config"),
85 FORGE_KEYCHAIN: "0",
86 FORGE_URL: base,
87 FORGE_TOKEN: "t",
88 ...gitClientEnv(),
89 ...env,
90 },
91 stdout: "pipe",
92 stderr: "pipe",
93 });
94 const [out, err, code] = await Promise.all([
95 new Response(proc.stdout).text(),
96 new Response(proc.stderr).text(),
97 proc.exited,
98 ]);
99 return { code, out, err };
100 }
101
102 test("the folder's origin names the repository, and the last 10 are asked for", async () => {
103 asked.length = 0;
104 const got = await forge([]);
105 expect(got.code).toBe(0);
106 expect(asked).toEqual(["/api/v1/repos/alice/app/runs?limit=10"]);
107 });
108
109 test("rows print in aligned columns: state, agent, #N, title, age, cost — no colour into a pipe", async () => {
110 const got = await forge(["--repo", "alice/app"]);
111 expect(got.code).toBe(0);
112 expect(got.out).not.toContain("\x1b[");
113 const lines = got.out.trimEnd().split("\n");
114 expect(lines).toHaveLength(3);
115 expect(lines[0]).toMatch(/^STATE\s+AGENT\s+#\s+TITLE\s+AGE\s+COST$/);
116 expect(lines[1]).toMatch(/^running\s+mason\s+#7353\s+forge runs lists what the crew is doing\s+3m\s+\$1\.23$/);
117 // No title: the run's own summary says what it was; no cost, no column text.
118 expect(lines[2]).toMatch(/^failed\s+alice\s+#12\s+check failed in 9s\s+2h$/);
119 // Aligned: every row's title starts where the header's does.
120 const at = lines[0]!.indexOf("TITLE");
121 expect(lines[1]!.indexOf("forge runs")).toBe(at);
122 expect(lines[2]!.indexOf("check failed")).toBe(at);
123 });
124
125 test("--json prints the API's rows unchanged", async () => {
126 const got = await forge(["--repo", "alice/app", "--json"]);
127 expect(got.code).toBe(0);
128 expect(JSON.parse(got.out)).toEqual(ROWS);
129 });
130
131 test("an empty list says so", async () => {
132 const got = await forge(["--repo", "alice/empty"]);
133 expect(got.code).toBe(0);
134 expect(got.out).toBe("no runs on alice/empty yet\n");
135 });
136
137 test("an unknown repository prints the API's words and fails", async () => {
138 const got = await forge(["--repo", "alice/nope"]);
139 expect(got.code).toBe(1);
140 expect(got.err).toBe("forge runs: not found\n");
141 expect(got.out).toBe("");
142 });
143
144 test("a refused token, or no sign-in at all, exits as not configured", async () => {
145 const stale = await forge(["--repo", "alice/app"], { FORGE_TOKEN: "stale" });
146 expect(stale.code).toBe(3);
147 expect(stale.err).toBe("forge runs: token expired\n");
148 const none = await forge(["--repo", "alice/app"], { FORGE_URL: "", FORGE_TOKEN: "" });
149 expect(none.code).toBe(3);
150 expect(none.err).toContain("not signed in");
151 });
152
153 test("a bad --repo is a usage error, before any request", async () => {
154 asked.length = 0;
155 const got = await forge(["--repo", "nope"]);
156 expect(got.code).toBe(2);
157 expect(asked).toEqual([]);
158 });
159
160 test("a remote URL names owner/name in every spelling git takes", () => {
161 const want = { owner: "alice", name: "app" };
162 expect(repoFromRemote("https://forge.example/alice/app.git")).toEqual(want);
163 expect(repoFromRemote("https://forge.example/alice/app")).toEqual(want);
164 expect(repoFromRemote("ssh://[email protected]:2222/alice/app.git")).toEqual(want);
165 expect(repoFromRemote("[email protected]:alice/app.git")).toEqual(want);
166 expect(repoFromRemote("https://forge.example/app.git")).toBeUndefined();
167 expect(repoFromRemote("not a url")).toBeUndefined();
168 expect(repoFromRemote(null)).toBeUndefined();
169 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs