@lizard-build/cli 4.0.94 → 4.0.95

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,473 @@
1
+ import chalk from "chalk";
2
+ import { Command } from "commander";
3
+ import { execFileSync } from "node:child_process";
4
+ import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { api, APIError, getRequestToken } from "../lib/api.js";
7
+ import { fail, isJSONMode, printJSON, table, timeAgo } from "../lib/format.js";
8
+
9
+ /**
10
+ * `lizard gha`: run a repository's GitHub Actions jobs on Lizard runners.
11
+ *
12
+ * One rule for people and agents alike: run `lizard gha`, do the one thing it says, run it
13
+ * again. Every answer is worked out from scratch (the platform's /api/gha/status plus the
14
+ * workflow files in this checkout), so it is always safe to repeat, and nothing waits for a
15
+ * browser. Not ready is an answer, not a failure: the exit code is 0 unless something broke
16
+ * (`--require-ready` makes not-ready exit 1, for CI).
17
+ */
18
+
19
+ type Actor = "user" | "org_owner" | "agent" | "none";
20
+ interface Next { actor: Actor; say: string; url?: string; command?: string; confirm?: boolean }
21
+ interface Size { name: string; label: string; vcpus: number; memoryGb: number; pricePerHour: number }
22
+ interface Status {
23
+ state: string;
24
+ verdict: "READY" | "NOT_READY" | "BLOCKED";
25
+ message: string;
26
+ next: Next;
27
+ repo: string;
28
+ lizardAccount: string | null;
29
+ installationId: number | null;
30
+ trial: { maxSize: string } | null;
31
+ sizes: Size[];
32
+ recentJobs: { id: string; workflow: string | null; job: string; status: string; conclusion: string | null; url: string | null; createdAt: number }[];
33
+ }
34
+ interface PreviewFile {
35
+ path: string;
36
+ changed: boolean;
37
+ text?: string;
38
+ error?: string;
39
+ moves: { job: string; from: string | null; to: string }[];
40
+ kept: { job: string; runsOn: string | null; reason: string }[];
41
+ already: { job: string; label: string }[];
42
+ unknownLabels: { job: string; label: string }[];
43
+ }
44
+ interface Preview { files: PreviewFile[]; trial: { maxSize: string; capped: string[]; message: string | null } | null; sizes: Size[] }
45
+
46
+ // ── The repository ─────────────────────────────────────────────────────
47
+
48
+ const REPO_RE = /^[A-Za-z0-9-]{1,39}\/[A-Za-z0-9._-]{1,100}$/;
49
+
50
+ function git(args: string[], cwd = process.cwd()): string | null {
51
+ try {
52
+ return execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
53
+ } catch {
54
+ return null;
55
+ }
56
+ }
57
+
58
+ /** owner/name from a GitHub remote URL (https, ssh or git@), or null. */
59
+ export function repoFromRemote(url: string): string | null {
60
+ const m = url.trim().match(/github\.com[:/]+([A-Za-z0-9-]{1,39})\/([A-Za-z0-9._-]{1,100}?)(?:\.git)?\/?$/);
61
+ return m ? `${m[1]}/${m[2]}` : null;
62
+ }
63
+
64
+ interface RepoContext { repo: string; root: string | null; fromFlag: boolean }
65
+
66
+ function resolveRepo(flag?: string): RepoContext {
67
+ const root = git(["rev-parse", "--show-toplevel"]);
68
+ if (flag) {
69
+ if (!REPO_RE.test(flag)) fail(`--repo must look like owner/name (got "${flag}")`, 1, "BAD_REPO");
70
+ // The local files are only this repository's when the checkout is that repository.
71
+ const here = root ? repoFromRemote(git(["remote", "get-url", "origin"], root) ?? "") : null;
72
+ return { repo: flag, root: here && here.toLowerCase() === flag.toLowerCase() ? root : null, fromFlag: true };
73
+ }
74
+ if (!root) {
75
+ fail("This isn't a git repository. Run `lizard gha` inside your repository, or pass --repo owner/name.", 1, "NOT_A_REPO");
76
+ }
77
+ const remotes = (git(["remote"], root) ?? "").split("\n").filter(Boolean);
78
+ const order = ["origin", ...remotes.filter((r) => r !== "origin")];
79
+ for (const r of order) {
80
+ const repo = repoFromRemote(git(["remote", "get-url", r], root) ?? "");
81
+ if (repo) return { repo, root, fromFlag: false };
82
+ }
83
+ return fail("This repository has no GitHub remote. Push it to a GitHub organization first, or pass --repo owner/name.", 1, "NO_GITHUB_REMOTE");
84
+ }
85
+
86
+ /** A command to show, carrying --repo when the user gave one. */
87
+ function cmd(base: string, ctx: RepoContext): string {
88
+ return ctx.fromFlag && base.startsWith("lizard gha") ? `${base} --repo ${ctx.repo}` : base;
89
+ }
90
+
91
+ function readWorkflows(root: string): { path: string; text: string }[] {
92
+ const dir = path.join(root, ".github", "workflows");
93
+ if (!existsSync(dir)) return [];
94
+ return readdirSync(dir)
95
+ .filter((f) => /\.ya?ml$/.test(f))
96
+ .sort()
97
+ .slice(0, 50)
98
+ .map((f) => ({ path: `.github/workflows/${f}`, text: readFileSync(path.join(dir, f), "utf8") }));
99
+ }
100
+
101
+ /**
102
+ * Is this checkout behind GitHub with different workflow files there? Then the local files say
103
+ * nothing about what runs: GitHub runs what's on the branch. Fetches the branch's upstream first
104
+ * (10 s at most; offline just uses what was last fetched).
105
+ */
106
+ function outOfDate(root: string): { behind: number; upstream: string } | null {
107
+ const upstream = git(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"], root);
108
+ if (!upstream) return null;
109
+ const [remote, ...rest] = upstream.split("/");
110
+ try {
111
+ execFileSync("git", ["fetch", "--quiet", remote, rest.join("/")], { cwd: root, stdio: "ignore", timeout: 10_000 });
112
+ } catch { /* offline: compare with what we have */ }
113
+ const behind = Number(git(["rev-list", "--count", `HEAD..${upstream}`], root) ?? "0");
114
+ if (!behind) return null;
115
+ try {
116
+ execFileSync("git", ["diff", "--quiet", "HEAD", upstream, "--", ".github/workflows"], { cwd: root, stdio: "ignore" });
117
+ return null; // same workflow files: the local ones are accurate
118
+ } catch {
119
+ return { behind, upstream };
120
+ }
121
+ }
122
+
123
+ function workflowsUncommitted(root: string): boolean {
124
+ const out = git(["status", "--porcelain", "--", ".github/workflows"], root);
125
+ return !!out && out.length > 0;
126
+ }
127
+
128
+ // ── Talking to the platform ────────────────────────────────────────────
129
+
130
+ async function getStatus(ctx: RepoContext): Promise<Status> {
131
+ try {
132
+ const s = await api.get<Status>(`/api/gha/status?repo=${encodeURIComponent(ctx.repo)}`);
133
+ if (s.next.command) s.next.command = cmd(s.next.command, ctx);
134
+ return s;
135
+ } catch (e) {
136
+ if (e instanceof APIError && e.status === 401 && (getRequestToken() ?? "").startsWith("liz_")) {
137
+ fail("Setting up GitHub Actions needs your own login, not an API key. Run `lizard login` (or unset LIZARD_TOKEN) and try again.", 2, "API_KEY_NOT_ALLOWED");
138
+ }
139
+ if (e instanceof APIError && e.status === 403) {
140
+ fail("This API key is limited to a project or workspace, and GitHub Actions setup is account-wide. Run `lizard login` and try again.", 2, "SCOPED_KEY_NOT_ALLOWED");
141
+ }
142
+ throw e;
143
+ }
144
+ }
145
+
146
+ async function getPreview(files: { path: string; text: string }[], opts: { size?: string; jobs?: Record<string, string>; cache?: boolean; docker?: boolean }): Promise<Preview> {
147
+ return api.post<Preview>("/api/gha/preview", { files, size: opts.size, jobs: opts.jobs, cache: !!opts.cache, docker: !!opts.docker });
148
+ }
149
+
150
+ // ── Working out the whole picture ──────────────────────────────────────
151
+
152
+ interface Report extends Status {
153
+ /** Present once the organization is ready: what this checkout's workflows still need. */
154
+ workflows?: {
155
+ toMove: { file: string; job: string; from: string | null; to: string }[];
156
+ onLizard: { file: string; job: string; label: string }[];
157
+ notMovable: { file: string; job: string; runsOn: string | null; reason: string }[];
158
+ unknownLabels: { file: string; job: string; label: string }[];
159
+ errors: { file: string; error: string }[];
160
+ uncommitted: boolean;
161
+ };
162
+ }
163
+
164
+ async function report(ctx: RepoContext): Promise<Report> {
165
+ const s: Report = await getStatus(ctx);
166
+ if (s.verdict !== "READY") return s;
167
+ if (!ctx.root) {
168
+ // Another repository than this checkout: only the platform's side is known.
169
+ s.next = { actor: "agent", say: `${s.repo} is connected. Run this inside a checkout of ${s.repo} to move its workflows.`, command: "lizard gha migrate --dry-run" };
170
+ return s;
171
+ }
172
+ const stale = outOfDate(ctx.root);
173
+ if (stale) {
174
+ s.state = "CHECKOUT_OUT_OF_DATE";
175
+ s.verdict = "NOT_READY";
176
+ s.message = `${s.repo} is connected, but this checkout is ${stale.behind} commit${stale.behind === 1 ? "" : "s"} behind ${stale.upstream} and its workflow files differ, so they don't show what GitHub runs.`;
177
+ s.next = { actor: "agent", confirm: true, say: "Update this checkout first so its workflow files match GitHub (git pull), then check again.", command: `git pull && ${cmd("lizard gha", ctx)}` };
178
+ return s;
179
+ }
180
+ const files = readWorkflows(ctx.root);
181
+ if (!files.length) {
182
+ s.state = "NO_WORKFLOWS";
183
+ s.message = `${s.repo} is connected, but this checkout has no workflow files in .github/workflows.`;
184
+ s.next = { actor: "agent", say: "Add a GitHub Actions workflow with `runs-on: lizard-medium-ubuntu-2404` (or move an existing one here), then run `lizard gha` again.", command: cmd("lizard gha", ctx) };
185
+ return s;
186
+ }
187
+ const p = await getPreview(files, {});
188
+ const w: NonNullable<Report["workflows"]> = { toMove: [], onLizard: [], notMovable: [], unknownLabels: [], errors: [], uncommitted: workflowsUncommitted(ctx.root) };
189
+ for (const f of p.files) {
190
+ if (f.error) w.errors.push({ file: f.path, error: f.error });
191
+ for (const m of f.moves) w.toMove.push({ file: f.path, ...m });
192
+ for (const a of f.already) w.onLizard.push({ file: f.path, ...a });
193
+ for (const k of f.kept) w.notMovable.push({ file: f.path, ...k });
194
+ for (const u of f.unknownLabels) w.unknownLabels.push({ file: f.path, ...u });
195
+ }
196
+ s.workflows = w;
197
+
198
+ if (w.unknownLabels.length) {
199
+ const u = w.unknownLabels[0];
200
+ s.state = "UNKNOWN_LABEL";
201
+ s.verdict = "NOT_READY";
202
+ s.message = `${u.file} asks for "${u.label}", which isn't a Lizard runner, so that job would wait forever.`;
203
+ s.next = { actor: "agent", say: `Change runs-on to one of: ${s.sizes.map((z) => z.label).join(", ")}. Or run \`lizard gha migrate\` to fix it for you.`, command: cmd("lizard gha migrate --dry-run", ctx) };
204
+ } else if (w.toMove.length) {
205
+ s.state = "NEEDS_MIGRATION";
206
+ s.message = `${s.repo} is connected. ${w.toMove.length} job${w.toMove.length === 1 ? "" : "s"} still run${w.toMove.length === 1 ? "s" : ""} on GitHub's runners.`;
207
+ s.next = { actor: "agent", say: "Preview the change, then apply it. It only edits runs-on lines in .github/workflows; nothing on GitHub changes until you commit and push.", command: cmd("lizard gha migrate --dry-run", ctx) };
208
+ } else if (w.onLizard.length && w.uncommitted) {
209
+ s.state = "NOT_PUSHED";
210
+ s.message = "The workflows here use Lizard runners, but the change isn't committed yet.";
211
+ s.next = { actor: "agent", say: `Commit and push the changes in .github/workflows (or open a pull request) the way you normally would: the next run uses Lizard runners. Afterwards, \`${cmd("lizard gha", ctx)}\` confirms the first job ran.` };
212
+ } else if (w.onLizard.length && !s.recentJobs.length) {
213
+ s.state = "WAITING_FOR_FIRST_RUN";
214
+ s.message = "The workflows use Lizard runners. No job has run on Lizard yet.";
215
+ s.next = { actor: "agent", say: "Make sure the change is pushed to GitHub. Jobs show up here as soon as a workflow runs.", command: cmd("lizard gha jobs", ctx) };
216
+ } else if (w.onLizard.length) {
217
+ const j = s.recentJobs[0];
218
+ s.state = "ACTIVE";
219
+ s.message = `${s.repo} runs on Lizard. Last job: ${j.job} (${j.conclusion ?? j.status}, ${timeAgo(j.createdAt)}).`;
220
+ s.next = { actor: "none", say: "All set: GitHub Actions jobs for this repository run on Lizard runners.", command: cmd("lizard gha jobs", ctx) };
221
+ } else {
222
+ s.state = "NOTHING_TO_MOVE";
223
+ s.message = "None of this repository's jobs can move to Lizard runners (only Linux jobs on GitHub-hosted or sized runners can).";
224
+ s.next = { actor: "none", say: "Nothing to do. macOS, Windows and expression-based jobs stay where they are." };
225
+ }
226
+ return s;
227
+ }
228
+
229
+ // ── Printing ───────────────────────────────────────────────────────────
230
+
231
+ const VERDICT_TEXT: Record<Report["verdict"], string> = {
232
+ READY: chalk.green("✓ Ready"),
233
+ NOT_READY: chalk.yellow("● Not ready yet"),
234
+ BLOCKED: chalk.red("✗ Can't continue"),
235
+ };
236
+
237
+ const WHO: Record<Actor, string> = {
238
+ user: "What you need to do",
239
+ org_owner: "What an owner of the GitHub organization needs to do",
240
+ agent: "Next step",
241
+ none: "Status",
242
+ };
243
+
244
+ function money(n: number): string {
245
+ return `$${n.toFixed(4).replace(/0+$/, "").replace(/\.$/, "")}/h`;
246
+ }
247
+
248
+ function printReport(r: Report) {
249
+ const lines: string[] = [];
250
+ lines.push(chalk.bold(`GitHub Actions on Lizard · ${r.repo}`));
251
+ lines.push("");
252
+ lines.push(`${VERDICT_TEXT[r.verdict]}: ${r.message}`);
253
+ if (r.workflows) {
254
+ const w = r.workflows;
255
+ if (w.toMove.length) {
256
+ lines.push("");
257
+ lines.push(chalk.dim("Jobs that would move:"));
258
+ for (const m of w.toMove) lines.push(` ${m.file} ${chalk.bold(m.job)} ${m.from ?? "?"} → ${chalk.cyan(m.to)}`);
259
+ }
260
+ if (w.onLizard.length && (r.state === "ACTIVE" || r.state === "WAITING_FOR_FIRST_RUN" || r.state === "NOT_PUSHED")) {
261
+ lines.push("");
262
+ lines.push(chalk.dim("On Lizard runners:"));
263
+ for (const a of w.onLizard) lines.push(` ${a.file} ${chalk.bold(a.job)} ${chalk.cyan(a.label)}`);
264
+ }
265
+ if (w.notMovable.length) {
266
+ lines.push("");
267
+ lines.push(chalk.dim("Staying where they are:"));
268
+ for (const k of w.notMovable) lines.push(chalk.dim(` ${k.file} ${k.job} (${k.runsOn ?? "no runs-on"}: ${k.reason})`));
269
+ }
270
+ for (const e of w.errors) lines.push(chalk.yellow(` ${e.file}: ${e.error}`));
271
+ }
272
+ lines.push("");
273
+ lines.push(chalk.bold((r.next.confirm ? "Needs your OK" : WHO[r.next.actor]) + ":"));
274
+ lines.push(" " + r.next.say);
275
+ if (r.next.url) lines.push(" " + chalk.cyan(r.next.url));
276
+ if (r.next.command && r.next.actor !== "none") {
277
+ lines.push("");
278
+ lines.push((r.next.confirm ? "If yes, run: " : r.next.url || r.next.actor === "user" || r.next.actor === "org_owner" ? "Then run: " : "Run: ") + chalk.cyan(r.next.command));
279
+ }
280
+ if (r.verdict === "READY" && r.sizes?.length && (r.state === "NEEDS_MIGRATION")) {
281
+ lines.push("");
282
+ lines.push(chalk.dim("Runner sizes (billed per second while a job runs): " + r.sizes.map((s) => `${s.name} ${s.vcpus} vCPU/${s.memoryGb} GB ${money(s.pricePerHour)}`).join(" · ")));
283
+ if (r.trial) lines.push(chalk.dim("Your account hasn't paid yet, so only small runners are available until you add credit."));
284
+ }
285
+ console.log(lines.join("\n"));
286
+ }
287
+
288
+ /** For agents: one line saying how to act on `next`. */
289
+ function howToUse(n: Next): string {
290
+ if (n.confirm) return "Ask the user first: show them next.say. Run next.command only if they agree.";
291
+ if (n.actor === "user" || n.actor === "org_owner") {
292
+ return "A person has to do this. Show the user next.say and next.url exactly as written, wait until they say it's done, then run next.command.";
293
+ }
294
+ if (n.actor === "agent" && n.command) return "You can do this yourself: run next.command.";
295
+ if (n.actor === "agent") return "You can do this yourself: next.say says what.";
296
+ return "Nothing left to do. Tell the user next.say.";
297
+ }
298
+
299
+ function jsonOut(r: Report) {
300
+ printJSON({ ...r, howToUse: howToUse(r.next) });
301
+ }
302
+
303
+ function finish(r: Report, requireReady: boolean) {
304
+ if (isJSONMode()) jsonOut(r); else printReport(r);
305
+ if (requireReady && r.verdict !== "READY") process.exitCode = 1;
306
+ }
307
+
308
+ // ── Commands ───────────────────────────────────────────────────────────
309
+
310
+ function parseJobSizes(values: string[] | undefined): Record<string, string> | undefined {
311
+ if (!values?.length) return undefined;
312
+ const out: Record<string, string> = {};
313
+ for (const v of values) {
314
+ const m = v.match(/^([^=]+)=(small|medium|large)$/);
315
+ if (!m) fail(`--job must look like build=large (got "${v}"). Sizes: small, medium, large.`, 1, "BAD_JOB_SIZE");
316
+ out[m[1]] = m[2];
317
+ }
318
+ return out;
319
+ }
320
+
321
+ export function registerGha(program: Command) {
322
+ const gha = program
323
+ .command("gha")
324
+ .description("Run this repository's GitHub Actions jobs on Lizard runners: shows where setup stands and the one next step")
325
+ .option("--repo <owner/name>", "GitHub repository (default: this checkout's GitHub remote)")
326
+ .option("--require-ready", "Exit 1 unless the repository is ready (for CI)")
327
+ .addHelpText("after", `
328
+ How it works:
329
+ Run \`lizard gha\`, do the one thing it says, then run it again. It never waits:
330
+ steps that happen in a browser print a link and the command to run afterwards.
331
+
332
+ lizard gha where setup stands + the next step
333
+ lizard gha connect connect the GitHub organization to your Lizard account
334
+ lizard gha migrate switch runs-on in .github/workflows to Lizard runners
335
+ lizard gha jobs recent jobs on Lizard runners
336
+
337
+ Runners: lizard-small-ubuntu-2404 (2 vCPU), lizard-medium-ubuntu-2404 (4 vCPU),
338
+ lizard-large-ubuntu-2404 (8 vCPU), billed per second. GitHub organizations only.`)
339
+ .action(async (opts: { repo?: string; requireReady?: boolean }) => {
340
+ const ctx = resolveRepo(opts.repo);
341
+ finish(await report(ctx), !!opts.requireReady);
342
+ });
343
+
344
+ gha
345
+ .command("connect")
346
+ .description("Connect this repository's GitHub organization to your Lizard account (your account pays for its runners)")
347
+ .option("--repo <owner/name>", "GitHub repository (default: this checkout's GitHub remote)")
348
+ .action(async (opts: { repo?: string }, c: Command) => {
349
+ const ctx = resolveRepo(opts.repo ?? c.parent?.opts().repo);
350
+ const before = await getStatus(ctx);
351
+ if (before.state === "NOT_CONNECTED" && before.installationId) {
352
+ try {
353
+ await api.post(`/api/gha/installations/${before.installationId}/connect`);
354
+ } catch (e) {
355
+ if (!(e instanceof APIError)) throw e;
356
+ // The platform's reason, then where things stand.
357
+ if (!isJSONMode()) console.log(chalk.yellow(`Couldn't connect: ${e.message}`) + "\n");
358
+ }
359
+ finish(await report(ctx), false);
360
+ return;
361
+ }
362
+ // Already connected, or something else comes first: say what.
363
+ finish(await report(ctx), false);
364
+ });
365
+
366
+ gha
367
+ .command("migrate")
368
+ .description("Switch runs-on in this checkout's .github/workflows to Lizard runners (edits files only; commit and push to apply)")
369
+ .option("--repo <owner/name>", "GitHub repository (default: this checkout's GitHub remote)")
370
+ .option("--size <size>", "Runner size for every job that moves: small, medium or large (default: medium for GitHub's standard runners)")
371
+ .option("--job <job=size...>", "Size for one job, e.g. --job build=large (repeatable)")
372
+ .option("--cache", "Also use Lizard's cached checkout and cache actions (faster repeat runs)")
373
+ .option("--docker", "Also use Lizard's Docker build actions (layers stay cached between runs)")
374
+ .option("--dry-run", "Show what would change without writing anything")
375
+ .option("--force", "Edit the files even if the organization isn't set up yet")
376
+ .action(async (opts: { repo?: string; size?: string; job?: string[]; cache?: boolean; docker?: boolean; dryRun?: boolean; force?: boolean }, c: Command) => {
377
+ const ctx = resolveRepo(opts.repo ?? c.parent?.opts().repo);
378
+ if (opts.size && !["small", "medium", "large"].includes(opts.size)) fail("--size must be small, medium or large", 1, "BAD_SIZE");
379
+ if (!ctx.root) fail(`Run this inside a checkout of ${ctx.repo}: it edits the workflow files on disk.`, 1, "NOT_IN_CHECKOUT");
380
+ const status = await getStatus(ctx);
381
+ if (status.verdict !== "READY" && !opts.force) {
382
+ // Jobs moved before the organization is ready would wait for a runner that never comes.
383
+ if (isJSONMode()) {
384
+ jsonOut({ ...status, message: `Not changing any files yet: ${status.message}` });
385
+ } else {
386
+ console.log(chalk.yellow("Not changing any files yet") + chalk.dim(" — jobs moved now would wait for a runner that can't start.") + "\n");
387
+ printReport(status);
388
+ }
389
+ return;
390
+ }
391
+ const stale = opts.force ? null : outOfDate(ctx.root!);
392
+ if (stale) {
393
+ fail(`This checkout is ${stale.behind} commit${stale.behind === 1 ? "" : "s"} behind ${stale.upstream} and its workflow files differ. Run \`git pull\` first, then \`lizard gha migrate\` again (or pass --force to edit these files anyway).`, 1, "CHECKOUT_OUT_OF_DATE");
394
+ }
395
+ const files = readWorkflows(ctx.root!);
396
+ if (!files.length) fail("No workflow files in .github/workflows.", 1, "NO_WORKFLOWS");
397
+ const p = await getPreview(files, { size: opts.size, jobs: parseJobSizes(opts.job), cache: opts.cache, docker: opts.docker });
398
+ const changed = p.files.filter((f) => f.changed && f.text);
399
+ if (!opts.dryRun) for (const f of changed) writeFileSync(path.join(ctx.root!, f.path), f.text!);
400
+
401
+ const moves = p.files.flatMap((f) => f.moves.map((m) => ({ file: f.path, ...m })));
402
+ const kept = p.files.flatMap((f) => f.kept.map((k) => ({ file: f.path, ...k })));
403
+ const errors = p.files.filter((f) => f.error).map((f) => ({ file: f.path, error: f.error! }));
404
+ const next: Next = !changed.length
405
+ ? { actor: "none", say: "Nothing needed changing.", command: cmd("lizard gha", ctx) }
406
+ : opts.dryRun
407
+ ? { actor: "agent", confirm: true, say: `This changes runs-on for ${moves.length} job${moves.length === 1 ? "" : "s"} (listed above) in your workflow files. Apply it?`, command: cmd(`lizard gha migrate${opts.size ? ` --size ${opts.size}` : ""}${(opts.job ?? []).map((j) => ` --job ${j}`).join("")}${opts.cache ? " --cache" : ""}${opts.docker ? " --docker" : ""}`, ctx) }
408
+ : { actor: "agent", say: `Updated ${changed.length === 1 ? "1 workflow file" : `${changed.length} workflow files`}. Commit and push ${changed.length === 1 ? "it" : "them"} (or open a pull request) the way you normally would: the next run uses Lizard runners. Afterwards, \`${cmd("lizard gha", ctx)}\` confirms the first job ran.` };
409
+
410
+ if (isJSONMode()) {
411
+ printJSON({
412
+ repo: ctx.repo, dryRun: !!opts.dryRun, filesChanged: changed.map((f) => f.path), moves, kept, errors,
413
+ trial: p.trial, next,
414
+ howToUse: howToUse(next),
415
+ });
416
+ return;
417
+ }
418
+ console.log(chalk.bold(opts.dryRun ? `Preview — nothing written (${ctx.repo})` : `Updated workflows (${ctx.repo})`));
419
+ console.log("");
420
+ if (moves.length) {
421
+ for (const m of moves) console.log(` ${m.file} ${chalk.bold(m.job)} ${m.from ?? "?"} → ${chalk.cyan(m.to)}`);
422
+ } else {
423
+ console.log(chalk.dim(" No jobs to move."));
424
+ }
425
+ if (kept.length) {
426
+ console.log("");
427
+ console.log(chalk.dim("Staying where they are:"));
428
+ for (const k of kept) console.log(chalk.dim(` ${k.file} ${k.job} (${k.runsOn ?? "no runs-on"}: ${k.reason})`));
429
+ }
430
+ for (const e of errors) console.log(chalk.yellow(` ${e.file}: ${e.error}`));
431
+ if (p.trial?.message) console.log("\n" + chalk.yellow(p.trial.message));
432
+ console.log("");
433
+ console.log(chalk.bold(next.confirm ? "Needs your OK:" : "Next step:"));
434
+ console.log(" " + next.say);
435
+ if (next.command && next.actor !== "none") console.log("\n" + (next.confirm ? "If yes, run: " : "Run: ") + chalk.cyan(next.command));
436
+ });
437
+
438
+ gha
439
+ .command("jobs")
440
+ .description("Recent GitHub Actions jobs that ran on Lizard runners for this repository")
441
+ .option("--repo <owner/name>", "GitHub repository (default: this checkout's GitHub remote)")
442
+ .option("--all", "Jobs of every repository you connected, not just this one")
443
+ .option("--limit <n>", "How many jobs (default 20)", "20")
444
+ .action(async (opts: { repo?: string; all?: boolean; limit: string }, c: Command) => {
445
+ const repoFlag = opts.repo ?? c.parent?.opts().repo;
446
+ const ctx = opts.all && !repoFlag ? null : resolveRepo(repoFlag);
447
+ const limit = Math.min(200, Math.max(1, Number(opts.limit) || 20));
448
+ const { jobs } = await api.get<{ jobs: any[] }>(`/api/gha/jobs?limit=200`);
449
+ const mine = (ctx ? jobs.filter((j) => String(j.repo).toLowerCase() === ctx.repo.toLowerCase()) : jobs).slice(0, limit);
450
+ if (isJSONMode()) {
451
+ printJSON({
452
+ repo: ctx?.repo ?? null,
453
+ jobs: mine.map((j) => ({ id: j.id, repo: j.repo, workflow: j.workflow, job: j.job, status: j.status, conclusion: j.conclusion, branch: j.branch, url: j.url, runner: j.runner, createdAt: j.createdAt, finishedAt: j.finishedAt, error: j.vmError })),
454
+ ...(mine.length ? {} : { next: { actor: "agent", say: "No jobs on Lizard runners yet. Run `lizard gha` to see what's missing.", command: ctx ? cmd("lizard gha", ctx) : "lizard gha" } }),
455
+ });
456
+ return;
457
+ }
458
+ if (!mine.length) {
459
+ console.log(`No jobs on Lizard runners yet${ctx ? ` for ${ctx.repo}` : ""}. Run ${chalk.cyan(ctx ? cmd("lizard gha", ctx) : "lizard gha")} to see what's missing.`);
460
+ return;
461
+ }
462
+ table(
463
+ ["when", ...(ctx ? [] : ["repo"]), "workflow", "job", "result", "branch"],
464
+ mine.map((j) => [
465
+ timeAgo(j.createdAt), ...(ctx ? [] : [j.repo]), j.workflow ?? "", j.job,
466
+ j.conclusion === "success" ? chalk.green("passed") : j.conclusion === "failure" ? chalk.red("failed") : j.conclusion ? j.conclusion : chalk.yellow(j.status),
467
+ j.branch ?? "",
468
+ ]),
469
+ );
470
+ const failedVm = mine.find((j) => j.vmError);
471
+ if (failedVm) console.log("\n" + chalk.yellow(`A runner failed to start for ${failedVm.job}: ${failedVm.vmError}`));
472
+ });
473
+ }
package/src/index.ts CHANGED
@@ -68,6 +68,7 @@ import { registerConfig } from "./commands/config.js";
68
68
  import { registerDocs } from "./commands/docs.js";
69
69
  import { registerDomain } from "./commands/domain.js";
70
70
  import { registerEvents } from "./commands/events.js";
71
+ import { registerGha } from "./commands/gha.js";
71
72
  import { registerGit } from "./commands/git.js";
72
73
  import { registerInit } from "./commands/init.js";
73
74
  import { registerKeys } from "./commands/keys.js";
@@ -168,6 +169,7 @@ registerConfig(program);
168
169
  registerDocs(program);
169
170
  registerDomain(program);
170
171
  registerEvents(program);
172
+ registerGha(program);
171
173
  registerGit(program);
172
174
  registerInit(program);
173
175
  registerKeys(program);
@@ -5,7 +5,7 @@ import { join, dirname } from "node:path";
5
5
  import os from "node:os";
6
6
  import { spawn } from "node:child_process";
7
7
 
8
- export const CURRENT_VERSION = "4.0.94";
8
+ export const CURRENT_VERSION = "4.0.95";
9
9
  const RELEASES_API = "https://api.github.com/repos/lizard-build/lizard-cli/releases/latest";
10
10
  const RELEASE_BASE = "https://github.com/lizard-build/lizard-cli/releases/latest/download";
11
11
 
@@ -0,0 +1,17 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { repoFromRemote } from "../../src/commands/gha.js";
3
+
4
+ describe("repoFromRemote", () => {
5
+ it.each([
6
+ ["git@github.com:acme/api.git", "acme/api"],
7
+ ["https://github.com/acme/api.git", "acme/api"],
8
+ ["https://github.com/acme/api", "acme/api"],
9
+ ["ssh://git@github.com/acme/my.repo.git", "acme/my.repo"],
10
+ ["https://x-access-token:abc@github.com/acme/api.git", "acme/api"],
11
+ ])("%s", (url, want) => expect(repoFromRemote(url)).toBe(want));
12
+
13
+ it("ignores other hosts", () => {
14
+ expect(repoFromRemote("git@gitlab.com:acme/api.git")).toBeNull();
15
+ expect(repoFromRemote("https://lizard.build/git/acme/api.git")).toBeNull();
16
+ });
17
+ });