Something went wrong. Try again.
Zig bindings for all 506 operations of the Forgejo API, generated from its own description, and zfj, a command line built on them.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What the porcelain command groups -- `zfj issue`, `zfj label` -- have in//! common: dispatching a word to a command, parsing its options and//! answering `--help`, finding the repository, collecting a list, and the//! escapes that color a terminal's output.
const std = @import("std");const builtin = @import("builtin");const Io = std.Io;
const zfj = @import("zfj");// Only where it is built in; see build.zig.const openuri = switch (builtin.os.tag) { .linux, .windows => @import("openuri"), else => struct {},};
const args = @import("args.zig");const call = @import("call.zig");const Context = @import("Context.zig");const Exit = Context.Exit;const op = @import("op.zig");
pub const Got = call.Got;
pub const Command = struct { name: []const u8, summary: []const u8, run: *const fn (ctx: *Context, words: []const []const u8) anyerror!Exit, /// What the command takes, for completing it. spec: args.Spec,};
/// Runs the command `words[0]` names out of a group's `commands`, or lists/// them.pub fn dispatch(ctx: *Context, comptime group: []const u8, commands: []const Command, words: []const []const u8) !Exit { if (words.len == 0 or std.mem.eql(u8, words[0], "--help") or std.mem.eql(u8, words[0], "help")) { try ctx.stdout.writeAll("usage: zfj [<global options>] " ++ group ++ " <command> [<arguments>]\n\nCommands:\n"); for (commands) |command| try ctx.stdout.print(" {s: <10}{s}\n", .{ command.name, command.summary }); try ctx.stdout.writeAll("\n`zfj " ++ group ++ " <command> --help` says what a command takes.\n"); return if (words.len == 0) .usage else .ok; } for (commands) |command| { if (std.mem.eql(u8, command.name, words[0])) return command.run(ctx, words[1..]); } return ctx.usage("unknown " ++ group ++ " command '{s}'; `zfj " ++ group ++ "` lists them", .{words[0]});}
/// Parses a command's options, answers `--help` from them, and runs it.pub fn Runner(comptime group: []const u8, comptime Options: type) type { return struct { /// The group's entry for the command called `name`. pub fn command(comptime name: []const u8, comptime summary: []const u8) Command { return .{ .name = name, .summary = summary, .run = run, .spec = comptime args.spec(Options, &Options.notes) }; }
pub fn run(ctx: *Context, words: []const []const u8) anyerror!Exit { for (words) |word| { if (std.mem.eql(u8, word, "--help")) { try ctx.stdout.print("usage: zfj [<global options>] " ++ group ++ " {s}\n\n{s}\n\n", .{ Options.usage, Options.about }); try args.writeHelp(Options, ctx.stdout, &Options.notes); return .ok; } } var diagnostic: args.Diagnostic = .{}; const options = (args.parse(Options, ctx.arena, words, .all, &diagnostic) catch |err| switch (err) { error.Usage => return ctx.usage("{s}", .{diagnostic.message()}), else => |e| return e, }).value; return Options.run(ctx, options); } };}
pub const repo_note: args.Note = .{ .description = "the repository, as <owner>/<repo>; without it, the clone's upstream or origin remote" };pub const json_note: args.Note = .{ .description = "write Forgejo's JSON rather than text for reading" };
/// Where a command is: the repository, and the client to reach it with.pub const Place = struct { client: *zfj.Client, owner: []const u8, repo: []const u8,};
pub fn place(ctx: *Context, repo_flag: ?[]const u8) Context.Failure!Place { const repository = try ctx.repository(repo_flag); const client = ctx.client() catch return error.Environment; return .{ .client = client, .owner = repository.owner, .repo = repository.name };}
/// A list operation's response, or with `--paginate` every page of it,/// joined into one JSON array.pub fn collect( ctx: *Context, comptime name: []const u8, comptime raw: anytype, client: *zfj.Client, params: anytype,) !call.Got([]const u8) { return collectPages(ctx, name, raw, client, params, ctx.global.paginate);}
/// Like `collect`, but following every page whether or not `--paginate`/// was given: for a command that has to see the whole list to be right.pub fn collectAll( ctx: *Context, comptime name: []const u8, comptime raw: anytype, client: *zfj.Client, params: anytype,) !call.Got([]const u8) { return collectPages(ctx, name, raw, client, params, true);}
fn collectPages( ctx: *Context, comptime name: []const u8, comptime raw: anytype, client: *zfj.Client, params: anytype, every: bool,) !call.Got([]const u8) { var joined: Io.Writer.Allocating = .init(ctx.arena); try joined.writer.writeByte('['); var any = false; while (true) { var response = raw(client, params.*) catch |err| return .{ .failed = ctx.transport(name, err) }; defer response.deinit(); if (response.status.class() != .success) return .{ .failed = ctx.apiError(name, response.status, response.body) }; const items = op.listItems(response.body) orelse { _ = ctx.parseFailure(name, "a JSON array", "NotAnArray"); return .{ .failed = .response_mismatch }; }; if (items.len != 0) { if (any) try joined.writer.writeByte(','); try joined.writer.writeAll(items); any = true; } if (!every) break; const next = op.nextPage(response.header("link")) orelse break; if (next <= (params.page orelse 1)) break; params.page = next; } try joined.writer.writeByte(']'); return .{ .ok = joined.written() };}
pub fn writeJson(ctx: *Context, json: []const u8) !Exit { try ctx.stdout.writeAll(std.mem.trimEnd(u8, json, " \t\r\n")); try ctx.stdout.writeByte('\n'); try ctx.stdout.flush(); return .ok;}
/// Opens `url` in `$BROWSER` when that is set, and otherwise in the user's/// chosen browser: through the desktop portal on Linux, falling back to/// `xdg-open` where there is no portal -- over ssh, or on a desktop without/// one -- through `ShellExecuteExW` on Windows, and through `open` on macOS./// A browser started as a command is not waited for, since one started/// fresh may stay in the foreground until it is closed.pub fn openInBrowser(ctx: *Context, url: []const u8) !Exit { try ctx.stderr.print("Opening {s} in your browser.\n", .{url}); try ctx.stderr.flush(); if (ctx.environ.get("BROWSER")) |browser| return spawnBrowser(ctx, browser, url); switch (builtin.os.tag) { .linux, .windows => { const outcome = openuri.open(ctx.io, ctx.gpa, ctx.process_environ, url, .{ .schemes = &.{ "http", "https" }, .activation_token = ctx.environ.get("XDG_ACTIVATION_TOKEN"), }) catch |err| switch (err) { error.PortalUnavailable => return spawnBrowser(ctx, "xdg-open", url), error.OutOfMemory => return error.OutOfMemory, else => return ctx.environment("cannot open {s}: {s}", .{ url, @errorName(err) }), }; switch (outcome) { .opened => {}, .cancelled => { try ctx.stderr.writeAll("The choice of browser was cancelled.\n"); try ctx.stderr.flush(); }, } return .ok; }, .macos => return spawnBrowser(ctx, "open", url), else => return spawnBrowser(ctx, "xdg-open", url), }}
fn spawnBrowser(ctx: *Context, browser: []const u8, url: []const u8) !Exit { const words = try Context.splitCommand(ctx.arena, browser); if (words.len == 0) return ctx.usage("$BROWSER is empty; unset it, or name a browser", .{}); const argv = try std.mem.concat(ctx.arena, []const u8, &.{ words, &.{url} }); _ = std.process.spawn(ctx.io, .{ .argv = argv, .stdin = .ignore, .stdout = .ignore }) catch |err| return ctx.environment("cannot start the browser '{s}': {s}", .{ browser, @errorName(err) }); return .ok;}
/// The first line of a text, for showing in a column.pub fn oneLine(text: []const u8) []const u8 { return text[0 .. std.mem.findAny(u8, text, "\r\n") orelse text.len];}
/// Each word, split at commas, so that `-l a,b` is `-l a -l b`.pub fn splitCommas(ctx: *Context, words: ?[]const []const u8) ![]const []const u8 { var list: std.ArrayList([]const u8) = .empty; for (words orelse &.{}) |word| { var parts = std.mem.splitScalar(u8, word, ','); while (parts.next()) |part| { const trimmed = std.mem.trim(u8, part, " "); if (trimmed.len != 0) try list.append(ctx.arena, trimmed); } } return list.items;}
pub fn writeLabels(writer: *Io.Writer, labels: ?[]const zfj.Label, separator: []const u8) !void { for (labels orelse &.{}, 0..) |label, i| { try writer.print("{s}{s}", .{ if (i == 0) "" else separator, label.name orelse "" }); }}
pub fn login(user: ?zfj.User) []const u8 { return if (user) |u| u.login orelse "someone" else "someone";}
/// The date of an RFC 3339 timestamp.pub fn day(timestamp: ?[]const u8) []const u8 { const t = timestamp orelse return "an unknown day"; return t[0..@min(t.len, 10)];}
/// A comment thread, each comment under a rule naming who wrote it and/// when.pub fn renderComments(writer: *Io.Writer, style: Style, comments: []const zfj.Comment) !void { for (comments) |comment| { try writer.print("\n{s}── {s} commented {s} ──{s}\n", .{ style.dim, login(comment.user), day(comment.created_at), style.reset, }); try writer.print("{s}\n", .{std.mem.trim(u8, comment.body orelse "", " \t\r\n")}); }}
/// An object as Forgejo gave it, with its comment thread, when there is/// one, added as a `comments` key.pub fn writeJsonWithComments(ctx: *Context, object_json: []const u8, comments_json: ?[]const u8) !Exit { return writeJsonWith(ctx, object_json, "comments", comments_json);}
/// An object as Forgejo gave it, with `value_json`, when there is one,/// added under `key`.pub fn writeJsonWith(ctx: *Context, object_json: []const u8, comptime key: []const u8, value_json: ?[]const u8) !Exit { const object = std.mem.trimEnd(u8, object_json, " \t\r\n"); const value = value_json orelse return writeJson(ctx, object); // The object's own JSON, with one key added before it closes. if (object.len < 2 or object[object.len - 1] != '}') return writeJson(ctx, object); const inner = std.mem.trimEnd(u8, object[0 .. object.len - 1], " \t\r\n"); const separator = if (inner.len > 1) "," else ""; try ctx.stdout.print("{s}{s}\"" ++ key ++ "\":{s}}}\n", .{ inner, separator, std.mem.trim(u8, value, " \t\r\n") }); try ctx.stdout.flush(); return .ok;}
pub const Style = struct { bold: []const u8 = "", dim: []const u8 = "", green: []const u8 = "", red: []const u8 = "", yellow: []const u8 = "", magenta: []const u8 = "", reset: []const u8 = "",
pub fn of(ctx: *Context) Style { if (!ctx.colored()) return .{}; return .{ .bold = "\x1b[1m", .dim = "\x1b[2m", .green = "\x1b[32m", .red = "\x1b[31m", .yellow = "\x1b[33m", .magenta = "\x1b[35m", .reset = "\x1b[0m" }; }
pub fn stateColor(style: Style, state: []const u8) []const u8 { if (std.mem.eql(u8, state, "open")) return style.green; if (std.mem.eql(u8, state, "merged")) return style.magenta; return style.red; }};