// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! `zfj run ...`: the runs of a repository's workflows. //! //! Flags are spelled as `gh run`'s are. A run is named by its run number, //! the one the web interface shows, never by the ID the operations take; //! see docs/adr/0005-runs-are-named-by-run-number.md. const std = @import("std"); const Io = std.Io; const datetime = @import("datetime"); const zfj = @import("zfj"); const args = @import("args.zig"); const call = @import("call.zig"); const Context = @import("Context.zig"); const git = @import("git.zig"); const Exit = Context.Exit; const porcelain = @import("porcelain.zig"); const Runner = porcelain.Runner; const place = porcelain.place; const writeJson = porcelain.writeJson; const Style = porcelain.Style; const repo_note = porcelain.repo_note; const json_note = porcelain.json_note; const oneLine = porcelain.oneLine; pub const commands = [_]porcelain.Command{ Runner("run", List).command("list", "list a repository's runs, newest first"), Runner("run", View).command("view", "show a run and its jobs"), Runner("run", Watch).command("watch", "follow a run until it finishes"), Runner("run", Cancel).command("cancel", "cancel a run still waiting or going"), Runner("run", Delete).command("delete", "delete a run that has finished"), }; pub fn main(ctx: *Context, words: []const []const u8) !Exit { return porcelain.dispatch(ctx, "run", &commands, words); } /// What a run or a job can be doing, or how it ended. The values are /// Forgejo's own numbering of them, which its web interface filters by. const Status = enum(u8) { unknown = 0, success = 1, failure = 2, cancelled = 3, skipped = 4, waiting = 5, running = 6, blocked = 7, }; const status_names: []const []const u8 = &.{ "unknown", "success", "failure", "cancelled", "skipped", "waiting", "running", "blocked" }; fn statusColor(style: Style, status: []const u8) []const u8 { const known = std.meta.stringToEnum(Status, status) orelse return ""; return switch (known) { .success => style.green, .failure => style.red, .waiting, .running, .blocked => style.yellow, .cancelled, .skipped, .unknown => style.dim, }; } const List = struct { repo: ?[]const u8 = null, status: ?[]const Status = null, event: ?[]const []const u8 = null, workflow: ?[]const u8 = null, branch: ?[]const u8 = null, commit: ?[]const u8 = null, limit: i64 = 20, page: ?i64 = null, json: bool = false, web: bool = false, pub const short = .{ .R = "repo", .s = "status", .e = "event", .w = "workflow", .b = "branch", .c = "commit", .L = "limit" }; pub const usage = "list [-s ]... [-e ]... [-w ] [-b ] [-c ] [-L ] [--json | --web]"; pub const about = "Lists a repository's runs, newest first, from every branch unless one is named. The global --paginate fetches every page."; pub const notes = [_]args.Note{ repo_note, .{ .description = "only runs with this status; given more than once, runs with any of them", .allowed = status_names }, .{ .description = "only runs started by this event, such as push, pull_request or workflow_dispatch; given more than once, any of them" }, .{ .description = "only runs of this workflow, named by its file, such as test.yaml", .complete = .workflows }, .{ .description = "only runs on this branch" }, .{ .description = "only runs of this commit: a full hash, or inside a clone anything git names one by, such as HEAD" }, .{ .description = "how many to a page (the instance may give fewer)" }, .{ .description = "which page" }, json_note, .{ .description = "open the repository's runs in the browser instead, filtered by --workflow and one --status, the only filters it has" }, }; pub fn run(ctx: *Context, o: List) !Exit { const statuses = o.status orelse &.{}; if (o.web) { if (o.json) return ctx.usage("--web opens the runs in the browser, and takes no --json", .{}); if (o.event != null or o.branch != null or o.commit != null) return ctx.usage("the web interface filters runs only by workflow and status, so --web takes no --event, --branch or --commit", .{}); if (statuses.len > 1) return ctx.usage("the web interface filters runs by one status at a time", .{}); if (statuses.len == 1 and statuses[0] == .unknown) return ctx.usage("the web interface cannot filter runs by the status unknown", .{}); } const at = place(ctx, o.repo) catch |e| return Context.exitFor(e); if (o.web) return openList(ctx, at, o.workflow, if (statuses.len == 1) statuses[0] else null); const names = try ctx.arena.alloc([]const u8, statuses.len); for (statuses, names) |status, *name| name.* = @tagName(status); const commit = if (o.commit) |rev| git.resolveCommit(ctx.arena, ctx.io, rev) orelse rev else null; var params: zfj.ListActionRunsParams = .{ .owner = at.owner, .repo = at.repo, .status = if (names.len == 0) null else names, .event = o.event, .workflow_id = o.workflow, .ref = if (o.branch) |b| try std.fmt.allocPrint(ctx.arena, "refs/heads/{s}", .{b}) else null, .head_sha = commit, .limit = o.limit, .page = o.page, }; const joined = switch (try collectRuns(ctx, at.client, ¶ms, ctx.global.paginate)) { .ok => |ok| ok, .failed => |exit| return exit, }; if (o.json) return writeJson(ctx, joined); return writeRunList(ctx, joined); } }; const run_number_note: args.Note = .{ .description = "the run's number, as the web interface shows it" }; const exit_status_note: args.Note = .{ .description = "exit with status 5 unless the run succeeded" }; const View = struct { number: i64, repo: ?[]const u8 = null, json: bool = false, web: bool = false, @"exit-status": bool = false, log: bool = false, @"log-failed": bool = false, job: ?[]const u8 = null, attempt: ?i64 = null, pub const short = .{ .R = "repo", .w = "web", .j = "job" }; pub const positional: []const []const u8 = &.{"number"}; pub const usage = "view [--json | --web | --log | --log-failed] [-j ] [--attempt ] [--exit-status]"; pub const about = "Shows a run -- its workflow, what started it, its status and how long it took -- and its jobs; with --log, their logs instead."; pub const notes = [_]args.Note{ run_number_note, repo_note, .{ .description = "write Forgejo's JSON for the run, with its jobs as a \"jobs\" list" }, .{ .description = "open the run in the browser instead: $BROWSER, else the system's" }, exit_status_note, .{ .description = "show the log of each job's latest attempt, as far as it has got" }, .{ .description = "show the logs of only the jobs that failed" }, .{ .description = "with --log or --log-failed, only this job, by its name or its ID" }, .{ .description = "with --job, this attempt at it rather than the latest" }, }; pub fn run(ctx: *Context, o: View) !Exit { const logging = o.log or o.@"log-failed"; if (o.web and o.json) return ctx.usage("--web opens the run in the browser, and takes no --json", .{}); if (logging and (o.web or o.json)) return ctx.usage("--log and --log-failed show logs, and take neither --json nor --web", .{}); if (o.job != null and !logging) return ctx.usage("--job chooses whose log to show, so takes --log or --log-failed", .{}); if (o.attempt) |attempt| { if (o.job == null) return ctx.usage("--attempt is an attempt at one job, so takes --job", .{}); if (attempt < 1) return ctx.usage("--attempt counts from 1", .{}); } const at = place(ctx, o.repo) catch |e| return Context.exitFor(e); const found = switch (try findRun(ctx, at, o.number)) { .ok => |ok| ok, .failed => |exit| return exit, }; if (o.web) { const url = found.run.html_url orelse return ctx.environment("Forgejo gave no web address for run {d}", .{o.number}); const opened = try porcelain.openInBrowser(ctx, url); return if (opened == .ok) outcome(found.run, o.@"exit-status") else opened; } const jobs = switch (try listJobs(ctx, at, found.run)) { .ok => |ok| ok, .failed => |exit| return exit, }; const written = if (logging) try writeLogs(ctx, at, o, jobs.jobs) else if (o.json) try porcelain.writeJsonWith(ctx, found.json, "jobs", jobs.json) else written: { var out: Io.Writer.Allocating = .init(ctx.arena); try renderRun(&out.writer, Style.of(ctx), found.run, jobs.jobs); try ctx.page(out.written()); break :written Exit.ok; }; return if (written == .ok) outcome(found.run, o.@"exit-status") else written; } }; /// The jobs `--job` names: those of that name, or failing any, the one /// with that ID. fn jobsNamed(ctx: *Context, jobs: []const zfj.ActionRunJob, name: []const u8) ![]const zfj.ActionRunJob { var named: std.ArrayList(zfj.ActionRunJob) = .empty; for (jobs) |job| if (std.mem.eql(u8, job.name orelse "", name)) try named.append(ctx.arena, job); if (named.items.len != 0) return named.items; const id = std.fmt.parseInt(i64, name, 10) catch return named.items; for (jobs) |job| if (job.id == id) try named.append(ctx.arena, job); return named.items; } /// The logs `view --log` and `--log-failed` show, each under a rule naming /// its job and attempt. A job that has not started has none yet, and is /// said to have none rather than asked for one. fn writeLogs(ctx: *Context, at: porcelain.Place, o: View, jobs: []const zfj.ActionRunJob) !Exit { var chosen = jobs; if (o.job) |name| { chosen = try jobsNamed(ctx, jobs, name); if (chosen.len == 0) { var names: Io.Writer.Allocating = .init(ctx.arena); for (jobs, 0..) |job, i| try names.writer.print("{s}{s}", .{ if (i == 0) "" else ", ", job.name orelse "" }); return ctx.usage("run {d} has no job '{s}'; its jobs are {s}", .{ o.number, name, names.written() }); } if (chosen.len > 1) { var ids: Io.Writer.Allocating = .init(ctx.arena); for (chosen, 0..) |job, i| try ids.writer.print("{s}{d}", .{ if (i == 0) "" else ", ", job.id orelse 0 }); return ctx.usage("run {d} has more than one job named '{s}'; name one by its ID: {s}", .{ o.number, name, ids.written() }); } } if (o.@"log-failed") { var failed: std.ArrayList(zfj.ActionRunJob) = .empty; for (chosen) |job| if (std.mem.eql(u8, job.status orelse "", "failure")) try failed.append(ctx.arena, job); chosen = failed.items; if (chosen.len == 0) { try ctx.stdout.print("No job of run {d} failed.\n", .{o.number}); try ctx.stdout.flush(); return .ok; } } const style = Style.of(ctx); var out: Io.Writer.Allocating = .init(ctx.arena); for (chosen, 0..) |job, i| { const attempt = o.attempt orelse job.attempt orelse 1; try out.writer.print("{s}{s}── {s} (attempt {d}) ──{s}\n", .{ if (i == 0) "" else "\n", style.dim, job.name orelse "", attempt, style.reset }); if (o.attempt == null and !hasLog(job)) { try out.writer.writeAll("no log yet\n"); continue; } var response = zfj.repoGetActionJobLogsRaw(at.client, .{ .owner = at.owner, .repo = at.repo, .job_id = job.id orelse continue, .attempt = o.attempt, }) catch |err| return ctx.transport("repoGetActionJobLogs", err); defer response.deinit(); if (response.status.class() != .success) return ctx.apiError("repoGetActionJobLogs", response.status, response.body); try out.writer.writeAll(response.body); if (response.body.len != 0 and response.body[response.body.len - 1] != '\n') try out.writer.writeByte('\n'); } try ctx.page(out.written()); return .ok; } /// Whether a job has been taken up by a runner, and so has a log. fn hasLog(job: zfj.ActionRunJob) bool { if ((job.task_id orelse 0) == 0) return false; const status = std.meta.stringToEnum(Status, job.status orelse "") orelse return true; return switch (status) { .waiting, .blocked => false, else => true, }; } const Watch = struct { number: i64, repo: ?[]const u8 = null, interval: i64 = 3, @"exit-status": bool = false, pub const short = .{ .R = "repo", .i = "interval" }; pub const positional: []const []const u8 = &.{"number"}; pub const usage = "watch [-i ] [--exit-status]"; pub const about = "Follows a run until it finishes. On a terminal the run and its jobs are redrawn in place; otherwise a line is written each time the run or a job changes status. A run already finished is shown once."; pub const notes = [_]args.Note{ run_number_note, repo_note, .{ .description = "how many seconds to wait between looks at the run" }, exit_status_note, }; pub fn run(ctx: *Context, o: Watch) !Exit { if (o.interval < 1) return ctx.usage("--interval is at least 1 second", .{}); const at = place(ctx, o.repo) catch |e| return Context.exitFor(e); const found = switch (try findRun(ctx, at, o.number)) { .ok => |ok| ok, .failed => |exit| return exit, }; const run_id = found.run.id.?; const redraw = ctx.stdoutIsTty(); const style = Style.of(ctx); // Each look at the run is kept until the next replaces it. var looks: [2]std.heap.ArenaAllocator = .{ .init(ctx.gpa), .init(ctx.gpa) }; defer for (&looks) |*a| a.deinit(); var which: usize = 0; var r = found.run; var drawn_lines: usize = 0; // What was last said of the run and of each job, when not redrawing. var said_run: ?Status = null; var said_jobs: std.AutoHashMapUnmanaged(i64, Status) = .empty; while (true) { const arena = looks[which].allocator(); const jobs = switch (try listJobsInto(ctx, arena, at, run_id)) { .ok => |ok| ok.jobs, .failed => |exit| return exit, }; const done = finished(r.status orelse ""); if (redraw) { var frame: Io.Writer.Allocating = .init(arena); try renderRun(&frame.writer, style, r, jobs); // Back up over the last frame, and clear from there down. if (drawn_lines != 0) try ctx.stdout.print("\x1b[{d}F\x1b[J", .{drawn_lines}); try ctx.stdout.writeAll(frame.written()); drawn_lines = std.mem.count(u8, frame.written(), "\n"); } else { const status = statusOf(r.status); if (said_run != status) { try ctx.stdout.print("run {d}: {s}\n", .{ o.number, @tagName(status) }); said_run = status; } for (jobs) |job| { const job_status = statusOf(job.status); const entry = try said_jobs.getOrPut(ctx.arena, job.id orelse continue); if (entry.found_existing and entry.value_ptr.* == job_status) continue; entry.value_ptr.* = job_status; try ctx.stdout.print("job {s}: {s}\n", .{ job.name orelse "", @tagName(job_status) }); } } try ctx.stdout.flush(); if (done) return outcome(r, o.@"exit-status"); ctx.io.sleep(.fromSeconds(o.interval), .awake) catch return .ok; which = 1 - which; _ = looks[which].reset(.retain_capacity); r = switch (try getRun(ctx, looks[which].allocator(), at, run_id)) { .ok => |ok| ok, .failed => |exit| return exit, }; } } }; fn statusOf(status: ?[]const u8) Status { return std.meta.stringToEnum(Status, status orelse "") orelse .unknown; } /// A run by its ID, kept in `arena`. fn getRun(ctx: *Context, arena: std.mem.Allocator, at: porcelain.Place, run_id: i64) !call.Got(zfj.ActionRun) { var response = zfj.actionRunRaw(at.client, .{ .owner = at.owner, .repo = at.repo, .run_id = run_id }) catch |err| return .{ .failed = ctx.transport("actionRun", err) }; defer response.deinit(); if (response.status.class() != .success) return .{ .failed = ctx.apiError("actionRun", response.status, response.body) }; const r = std.json.parseFromSliceLeaky(zfj.ActionRun, arena, response.body, .{ .ignore_unknown_fields = true, .allocate = .alloc_always, }) catch |err| { _ = ctx.parseFailure("actionRun", "an ActionRun", @errorName(err)); return .{ .failed = .response_mismatch }; }; return .{ .ok = r }; } const Cancel = struct { number: i64, repo: ?[]const u8 = null, pub const short = .{ .R = "repo" }; pub const positional: []const []const u8 = &.{"number"}; pub const usage = "cancel "; pub const about = "Cancels a run's jobs that are waiting or going. A run that has already finished is left as it is."; pub const notes = [_]args.Note{ run_number_note, repo_note }; pub fn run(ctx: *Context, o: Cancel) !Exit { const at = place(ctx, o.repo) catch |e| return Context.exitFor(e); const found = switch (try findRun(ctx, at, o.number)) { .ok => |ok| ok, .failed => |exit| return exit, }; // Forgejo answers a finished run as it does one it cancelled, so // whether there was anything to cancel is told from the run. const status = found.run.status orelse ""; if (finished(status)) { try ctx.stdout.print("Run {d} had already finished: {s}\n", .{ o.number, status }); try ctx.stdout.flush(); return .ok; } if (call.done(ctx, "cancelActionRun", zfj.cancelActionRunRaw(at.client, .{ .owner = at.owner, .repo = at.repo, .run_id = found.run.id.? }))) |exit| return exit; try ctx.stdout.print("Cancelled run {d}\n", .{o.number}); try ctx.stdout.flush(); return .ok; } }; const Delete = struct { number: i64, repo: ?[]const u8 = null, pub const short = .{ .R = "repo" }; pub const positional: []const []const u8 = &.{"number"}; pub const usage = "delete "; pub const about = "Deletes a run that has finished. Forgejo refuses to delete one still waiting or going; cancel it first."; pub const notes = [_]args.Note{ run_number_note, repo_note }; pub fn run(ctx: *Context, o: Delete) !Exit { const at = place(ctx, o.repo) catch |e| return Context.exitFor(e); const found = switch (try findRun(ctx, at, o.number)) { .ok => |ok| ok, .failed => |exit| return exit, }; if (call.done(ctx, "deleteActionRun", zfj.deleteActionRunRaw(at.client, .{ .owner = at.owner, .repo = at.repo, .run_id = found.run.id.? }))) |exit| return exit; try ctx.stdout.print("Deleted run {d}\n", .{o.number}); try ctx.stdout.flush(); return .ok; } }; /// Whether a run or job with this status has ended, and will not change. fn finished(status: []const u8) bool { const known = std.meta.stringToEnum(Status, status) orelse return false; return switch (known) { .success, .failure, .cancelled, .skipped => true, .unknown, .waiting, .running, .blocked => false, }; } /// What `--exit-status` makes of a run: anything but success, including a /// run that has not finished yet, is not a success. fn outcome(r: zfj.ActionRun, exit_status: bool) Exit { if (!exit_status) return .ok; return if (std.mem.eql(u8, r.status orelse "", "success")) .ok else .run_failed; } /// A run, found by its run number: as Forgejo wrote it, and as its model. const Found = struct { json: []const u8, run: zfj.ActionRun, }; /// The run a run number names. Every operation on a run takes its ID, which /// only the list of runs, filtered by run number, gives back; see /// docs/adr/0005-runs-are-named-by-run-number.md. fn findRun(ctx: *Context, at: porcelain.Place, number: i64) !call.Got(Found) { var params: zfj.ListActionRunsParams = .{ .owner = at.owner, .repo = at.repo, .run_number = number, .page = 1, .limit = 1 }; const joined = switch (try collectRuns(ctx, at.client, ¶ms, false)) { .ok => |ok| ok, .failed => |exit| return .{ .failed = exit }, }; const runs = std.json.parseFromSliceLeaky([]const std.json.Value, ctx.arena, joined, .{}) catch unreachable; if (runs.len == 0) return .{ .failed = ctx.notFound("no run {d} in {s}/{s}", .{ number, at.owner, at.repo }) }; const r = std.json.parseFromValueLeaky(zfj.ActionRun, ctx.arena, runs[0], .{ .ignore_unknown_fields = true }) catch |err| { _ = ctx.parseFailure("listActionRuns", "an ActionRun", @errorName(err)); return .{ .failed = .response_mismatch }; }; if (r.id == null) return .{ .failed = ctx.environment("Forgejo gave no ID for run {d}", .{number}) }; return .{ .ok = .{ .json = try std.json.Stringify.valueAlloc(ctx.arena, runs[0], .{}), .run = r } }; } const Jobs = struct { json: []const u8, jobs: []const zfj.ActionRunJob, }; fn listJobs(ctx: *Context, at: porcelain.Place, r: zfj.ActionRun) !call.Got(Jobs) { return listJobsInto(ctx, ctx.arena, at, r.id.?); } /// A run's jobs, kept in `arena`: `run watch` asks again and again, and /// lets go of each answer when it has the next. fn listJobsInto(ctx: *Context, arena: std.mem.Allocator, at: porcelain.Place, run_id: i64) !call.Got(Jobs) { var response = zfj.listActionRunJobsRaw(at.client, .{ .owner = at.owner, .repo = at.repo, .run_id = run_id }) catch |err| return .{ .failed = ctx.transport("listActionRunJobs", err) }; defer response.deinit(); if (response.status.class() != .success) return .{ .failed = ctx.apiError("listActionRunJobs", response.status, response.body) }; const json = try arena.dupe(u8, response.body); const jobs = std.json.parseFromSliceLeaky([]const zfj.ActionRunJob, arena, json, .{ .ignore_unknown_fields = true, .allocate = .alloc_always, }) catch |err| { _ = ctx.parseFailure("listActionRunJobs", "a list of ActionRunJob", @errorName(err)); return .{ .failed = .response_mismatch }; }; return .{ .ok = .{ .json = json, .jobs = jobs } }; } /// A Go `time.Duration`, which counts nanoseconds, as `52m24s`. fn writeDuration(writer: *Io.Writer, nanoseconds: i64) !void { const seconds: u64 = @intCast(@divTrunc(@max(nanoseconds, 0), std.time.ns_per_s)); const hours = seconds / 3600; const minutes = seconds / 60 % 60; if (hours != 0) try writer.print("{d}h", .{hours}); if (hours != 0 or minutes != 0) try writer.print("{d}m", .{minutes}); try writer.print("{d}s", .{seconds % 60}); } fn renderRun(writer: *Io.Writer, style: Style, r: zfj.ActionRun, jobs: []const zfj.ActionRunJob) !void { const status = r.status orelse ""; try writer.print("{s}{s}{s} #{d}\n", .{ style.bold, oneLine(r.title orelse ""), style.reset, r.index_in_repo orelse 0 }); try writer.print("{s}{s}{s} · {s} · {s} · {s}", .{ statusColor(style, status), status, style.reset, r.workflow_id orelse "", eventOf(r), r.prettyref orelse "", }); if (r.commit_sha) |sha| try writer.print(" @ {s}", .{sha[0..@min(sha.len, 10)]}); try writer.writeByte('\n'); var buffer: [16]u8 = undefined; if (happened(r.started)) |started| { try writer.print("Started {s}", .{minute(&buffer, started)}); } else { try writer.print("Created {s}", .{minute(&buffer, r.created)}); } if (r.trigger_user) |user| try writer.print(" by {s}", .{porcelain.login(user)}); if (happened(r.stopped) != null) if (r.duration) |d| { try writer.writeAll(" · took "); try writeDuration(writer, d); }; try writer.writeByte('\n'); if (r.html_url) |url| try writer.print("{s}{s}{s}\n", .{ style.dim, url, style.reset }); if (jobs.len == 0) return; try writer.writeAll("\nJobs:\n"); var name_width: usize = 0; var status_width: usize = 0; for (jobs) |job| { const name: []const u8 = job.name orelse ""; name_width = @max(name_width, name.len); const job_status: []const u8 = job.status orelse ""; status_width = @max(status_width, job_status.len); } for (jobs) |job| { const name: []const u8 = job.name orelse ""; const job_status: []const u8 = job.status orelse ""; try writer.print(" {s}", .{name}); try writer.splatByteAll(' ', name_width - name.len); try writer.print(" {s}{s}{s}", .{ statusColor(style, job_status), job_status, style.reset }); try writer.splatByteAll(' ', status_width - job_status.len); try writer.print(" {s}attempt {d}{s}\n", .{ style.dim, job.attempt orelse 1, style.reset }); } } /// The repository's runs in the web interface, which filters them by /// workflow and by one status, given as Forgejo's number for it. fn openList(ctx: *Context, at: porcelain.Place, workflow: ?[]const u8, status: ?Status) !Exit { var repository = switch (call.result(ctx, "repoGet", zfj.repoGetResult(at.client, .{ .owner = at.owner, .repo = at.repo }))) { .ok => |ok| ok, .failed => |exit| return exit, }; defer repository.deinit(); const html_url = repository.value().html_url orelse return ctx.environment("Forgejo gave no web address for {s}/{s}", .{ at.owner, at.repo }); var url: Io.Writer.Allocating = .init(ctx.arena); try url.writer.print("{s}/actions", .{std.mem.trimEnd(u8, html_url, "/")}); var separator: u8 = '?'; if (workflow) |w| { try url.writer.print("{c}workflow=", .{separator}); try writeQueryComponent(&url.writer, w); separator = '&'; } if (status) |s| try url.writer.print("{c}status={d}", .{ separator, @backingInt(s) }); return porcelain.openInBrowser(ctx, url.written()); } fn writeQueryComponent(writer: *Io.Writer, text: []const u8) !void { for (text) |c| switch (c) { 'A'...'Z', 'a'...'z', '0'...'9', '-', '.', '_', '~' => try writer.writeByte(c), else => try writer.print("%{X:0>2}", .{c}), }; } /// A page of a repository's runs, or with `every` each page until /// Forgejo's `total_count` is reached, as one JSON array. The list is an /// object holding the runs rather than a list, and comes with no `Link` /// header to follow, which is why `porcelain.collect` cannot read it. fn collectRuns(ctx: *Context, client: *zfj.Client, params: *zfj.ListActionRunsParams, every: bool) !call.Got([]const u8) { // Asked for no page, Forgejo ignores the limit and sends every run. if (params.page == null) params.page = 1; var joined: Io.Writer.Allocating = .init(ctx.arena); try joined.writer.writeByte('['); var count: usize = 0; while (true) { var response = zfj.listActionRunsRaw(client, params.*) catch |err| return .{ .failed = ctx.transport("listActionRuns", err) }; defer response.deinit(); if (response.status.class() != .success) return .{ .failed = ctx.apiError("listActionRuns", response.status, response.body) }; const page = std.json.parseFromSliceLeaky(RunPage, ctx.arena, response.body, .{ .ignore_unknown_fields = true, .allocate = .alloc_always, }) catch |err| { _ = ctx.parseFailure("listActionRuns", "a ListActionRunResponse", @errorName(err)); return .{ .failed = .response_mismatch }; }; const runs = page.workflow_runs orelse &.{}; for (runs) |r| { if (count != 0) try joined.writer.writeByte(','); try std.json.Stringify.value(r, .{}, &joined.writer); count += 1; } if (!every or runs.len == 0) break; if (page.total_count) |total| if (count >= total) break; params.page = params.page.? + 1; } try joined.writer.writeByte(']'); return .{ .ok = joined.written() }; } /// `ListActionRunResponse`, with each run kept as Forgejo wrote it. const RunPage = struct { total_count: ?i64 = null, workflow_runs: ?[]const std.json.Value = null, }; /// A timestamp Forgejo gave, or null for the zero time it gives in place /// of one that has not happened: the start of a run still waiting, the end /// of one still going. That is the Unix epoch, or Go's zero time, written /// in the instance's own offset, so it is recognized as an instant at or /// before the epoch rather than by how it is spelled. A timestamp that /// cannot be read is shown as it was given. fn happened(timestamp: ?[]const u8) ?[]const u8 { const t = timestamp orelse return null; const read = datetime.iso8601.parse(t) catch return t; if (read.str.len != t.len or !read.has_offset) return t; if (read.value.toInstant().timestamp <= 0) return null; return t; } /// The event that started a run. Forgejo leaves `event` empty for a run /// started by dispatch, and says so only in `trigger_event`. fn eventOf(r: zfj.ActionRun) []const u8 { if (r.event) |event| if (event.len != 0) return event; return r.trigger_event orelse ""; } /// An RFC 3339 timestamp to the minute, as `2026-10-15 16:50`, in the /// instance's own time zone. fn minute(buffer: *[16]u8, timestamp: ?[]const u8) []const u8 { const t = timestamp orelse return ""; const shown = buffer[0..@min(t.len, buffer.len)]; @memcpy(shown, t[0..shown.len]); if (shown.len > 10 and shown[10] == 'T') shown[10] = ' '; return shown; } /// A list of runs: columns on a terminal, and otherwise one to a line with /// its run number, status, title, workflow, event, branch or tag, and when /// it started, separated by tabs. fn writeRunList(ctx: *Context, json: []const u8) !Exit { const parsed = std.json.parseFromSlice([]const zfj.ActionRun, ctx.gpa, json, .{ .ignore_unknown_fields = true }) catch |err| { _ = ctx.parseFailure("the list", "a list of ActionRun", @errorName(err)); return .response_mismatch; }; defer parsed.deinit(); const runs = parsed.value; var out: Io.Writer.Allocating = .init(ctx.arena); if (!ctx.stdoutIsTty()) { for (runs) |r| { try out.writer.print("{d}\t{s}\t{s}\t{s}\t{s}\t{s}\t{s}\n", .{ r.index_in_repo orelse 0, r.status orelse "", oneLine(r.title orelse ""), r.workflow_id orelse "", eventOf(r), r.prettyref orelse "", happened(r.started) orelse "", }); } try ctx.stdout.writeAll(out.written()); try ctx.stdout.flush(); return .ok; } if (runs.len == 0) { try ctx.stdout.writeAll("No runs.\n"); try ctx.stdout.flush(); return .ok; } const style = Style.of(ctx); var number_width: usize = 0; var status_width: usize = 0; for (runs) |r| { number_width = @max(number_width, std.fmt.count("{d}", .{r.index_in_repo orelse 0})); const status: []const u8 = r.status orelse ""; status_width = @max(status_width, status.len); } for (runs) |r| { const number = r.index_in_repo orelse 0; const status = r.status orelse ""; try out.writer.splatByteAll(' ', number_width - std.fmt.count("{d}", .{number})); try out.writer.print("{s}#{d}{s} {s}{s}{s}", .{ style.bold, number, style.reset, statusColor(style, status), status, style.reset }); try out.writer.splatByteAll(' ', status_width - status.len); try out.writer.print(" {s} {s}{s} · {s} · {s}", .{ oneLine(r.title orelse ""), style.dim, r.workflow_id orelse "", eventOf(r), r.prettyref orelse "", }); var buffer: [16]u8 = undefined; if (happened(r.started)) |started| try out.writer.print(" · {s}", .{minute(&buffer, started)}); try out.writer.print("{s}\n", .{style.reset}); } try ctx.page(out.written()); return .ok; } const testing = std.testing; test "every command compiles" { for (commands) |command| _ = command.run; } test "every command's notes cover its options" { inline for (.{ List, View, Watch, Cancel, Delete }) |Options| { try testing.expectEqual(@typeInfo(Options).@"struct".field_names.len, Options.notes.len); } } test "the status names are the statuses" { const names = @typeInfo(Status).@"enum".field_names; try testing.expectEqual(names.len, status_names.len); for (status_names) |name| try testing.expect(std.meta.stringToEnum(Status, name) != null); } test "a query component escapes all but the unreserved characters" { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try writeQueryComponent(&out.writer, "my build.yaml&x=1"); try testing.expectEqualStrings("my%20build.yaml%26x%3D1", out.written()); } test "the zero time is not a time, in whatever offset it is written" { for ([_][]const u8{ "1970-01-01T00:00:00Z", "1969-12-31T18:00:00-06:00", "1970-01-01T05:30:00+05:30", "0001-01-01T00:00:00Z", "0000-12-31T18:09:24-05:50", }) |zero| try testing.expectEqual(null, happened(zero)); for ([_][]const u8{ "2026-10-17T10:35:12-05:00", "1970-01-01T00:00:01Z", "not a time", "1969-12-31T18:00:00", }) |t| try testing.expectEqualStrings(t, happened(t).?); try testing.expectEqual(null, happened(null)); } test "a time is shown to the minute" { var buffer: [16]u8 = undefined; try testing.expectEqualStrings("2026-10-15 16:50", minute(&buffer, "2026-10-15T16:50:37-05:00")); try testing.expectEqualStrings("", minute(&buffer, null)); } test "a duration is hours, minutes and seconds, leaving out the leading zeros" { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); for ([_]struct { i64, []const u8 }{ .{ 3144 * std.time.ns_per_s, "52m24s" }, .{ 7 * std.time.ns_per_s, "7s" }, .{ 3600 * std.time.ns_per_s, "1h0m0s" }, .{ -1, "0s" }, }) |case| { out.clearRetainingCapacity(); try writeDuration(&out.writer, case[0]); try testing.expectEqualStrings(case[1], out.written()); } } test "a run is shown with its jobs" { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try renderRun(&out.writer, .{}, .{ .index_in_repo = 43, .title = "Version 0.5.0", .status = "success", .workflow_id = "release.yaml", .event = "push", .prettyref = "v0.5.0", .commit_sha = "cf1d198db401a61c2098e51020f073e6d7e7dcd2", .started = "2026-10-15T16:51:47-05:00", .stopped = "2026-10-15T17:44:11-05:00", .duration = 3144 * std.time.ns_per_s, .html_url = "https://example.org/o/r/actions/runs/43", }, &.{ .{ .name = "release", .status = "success", .attempt = 1 }, .{ .name = "winget", .status = "failure", .attempt = 2 }, }); try testing.expectEqualStrings( \\Version 0.5.0 #43 \\success · release.yaml · push · v0.5.0 @ cf1d198db4 \\Started 2026-10-15 16:51 · took 52m24s \\https://example.org/o/r/actions/runs/43 \\ \\Jobs: \\ release success attempt 1 \\ winget failure attempt 2 \\ , out.written()); } test "a run not yet started is shown by when it was made, and a dispatched one by its trigger" { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try renderRun(&out.writer, .{}, .{ .index_in_repo = 3, .title = ".forgejo/workflows/dispatch.yaml", .status = "waiting", .workflow_id = "dispatch.yaml", .event = "", .trigger_event = "workflow_dispatch", .prettyref = "main", .created = "2026-10-17T00:29:10-05:00", .started = "1969-12-31T18:00:00-06:00", .stopped = "1969-12-31T18:00:00-06:00", .duration = 0, }, &.{}); try testing.expectEqualStrings( \\.forgejo/workflows/dispatch.yaml #3 \\waiting · dispatch.yaml · workflow_dispatch · main \\Created 2026-10-17 00:29 \\ , out.written()); } test "--exit-status passes only a run that succeeded" { try testing.expectEqual(Exit.ok, outcome(.{ .status = "success" }, true)); try testing.expectEqual(Exit.run_failed, outcome(.{ .status = "failure" }, true)); try testing.expectEqual(Exit.run_failed, outcome(.{ .status = "running" }, true)); try testing.expectEqual(Exit.ok, outcome(.{ .status = "failure" }, false)); } test "a job is named by its name, or failing that its ID" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var ctx: Context = undefined; ctx.arena = arena.allocator(); const jobs: []const zfj.ActionRunJob = &.{ .{ .id = 7, .name = "build" }, .{ .id = 8, .name = "test" }, .{ .id = 9, .name = "test" }, .{ .id = 10, .name = "8" }, }; try testing.expectEqual(@as(usize, 1), (try jobsNamed(&ctx, jobs, "build")).len); try testing.expectEqual(@as(usize, 2), (try jobsNamed(&ctx, jobs, "test")).len); // A name wins over an ID that reads the same. try testing.expectEqual(@as(?i64, 10), (try jobsNamed(&ctx, jobs, "8"))[0].id); try testing.expectEqual(@as(?i64, 9), (try jobsNamed(&ctx, jobs, "9"))[0].id); try testing.expectEqual(@as(usize, 0), (try jobsNamed(&ctx, jobs, "deploy")).len); } test "a job has a log once a runner has taken it up" { try testing.expect(!hasLog(.{ .status = "waiting", .task_id = 0 })); try testing.expect(!hasLog(.{ .status = "blocked", .task_id = 0 })); try testing.expect(hasLog(.{ .status = "running", .task_id = 12 })); try testing.expect(hasLog(.{ .status = "failure", .task_id = 12 })); // Cancelled before a runner took it up. try testing.expect(!hasLog(.{ .status = "cancelled", .task_id = 0 })); }