// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! `zfj`, a command-line tool for Forgejo built on the zfj bindings. //! //! `zfj [] []`. The global options are //! read only ahead of the command, so that nothing the tool claims for itself //! can shadow an operation's params; see //! docs/adr/0003-global-options-before-the-command.md. const std = @import("std"); const Io = std.Io; const build_options = @import("build_options"); const zfj = @import("zfj"); const args = @import("args.zig"); const Context = @import("Context.zig"); const instances = @import("instances.zig"); const issue = @import("issue.zig"); const label = @import("label.zig"); const package = @import("package.zig"); const pr = @import("pr.zig"); const repo = @import("repo.zig"); const runs = @import("run.zig"); const workflow = @import("workflow.zig"); const op = @import("op.zig"); const completion = @import("completion.zig"); /// The words that can follow the global options, as `zfj --help` lists /// them and completion offers them. `run` dispatches the same words. const entries = [_]completion.Entry{ .{ .name = "issue", .synopsis = "issue []", .summary = "work with issues; `zfj issue` lists the commands", .completes = .{ .group = &issue.commands } }, .{ .name = "label", .synopsis = "label []", .summary = "work with labels; `zfj label` lists the commands", .completes = .{ .group = &label.commands } }, .{ .name = "package", .synopsis = "package []", .summary = "upload packages; `zfj package` lists the commands", .completes = .{ .group = &package.commands } }, .{ .name = "pr", .synopsis = "pr []", .summary = "open and read pull requests; `zfj pr` lists them", .completes = .{ .group = &pr.commands } }, .{ .name = "repo", .synopsis = "repo []", .summary = "work with repositories; `zfj repo` lists the commands", .completes = .{ .group = &repo.commands } }, .{ .name = "run", .synopsis = "run []", .summary = "follow the runs of workflows; `zfj run` lists them", .completes = .{ .group = &runs.commands } }, .{ .name = "workflow", .synopsis = "workflow run ", .summary = "start a run of a workflow; `zfj workflow` says more", .completes = .{ .group = &workflow.commands } }, .{ .name = "op", .synopsis = "op [ []]", .summary = "perform one API operation; alone, list them", .completes = .operations }, .{ .name = "login", .synopsis = "login ", .summary = "save a token for an instance, checking it first", .completes = .{ .spec = instances.login_spec } }, .{ .name = "logout", .synopsis = "logout ", .summary = "forget an instance and its token", .completes = .{ .spec = instances.named_spec } }, .{ .name = "instances", .synopsis = "instances", .summary = "list the instances, marking the default with *", .completes = .{ .spec = .{} } }, .{ .name = "default", .synopsis = "default ", .summary = "choose the instance reached when none is named", .completes = .{ .spec = instances.named_spec } }, .{ .name = "completion", .synopsis = "completion ", .summary = "print the completion script for a shell", .completes = .{ .spec = completion.command_spec } }, }; /// What completion says of each global option, in `Context.Global`'s /// field order. const global_notes = [_]args.Note{ .{ .description = "the instance to reach", .complete = .instances }, .{ .description = "when to color output" }, .{ .description = "log each request and response status to stderr" }, .{ .description = "fail when a response does not match its model" }, .{ .description = "follow a list through every page" }, .{ .description = "show the usage" }, .{ .description = "say which zfj this is" }, }; const usage = \\usage: zfj [] [] \\ \\Commands: \\ ++ commands_help ++ "\n" ++ \\Global options, given before the command: \\ --instance the instance to reach (else ZFJ_INSTANCE, else \\ the default) \\ --color when to color output (default: auto) \\ --debug log each request and response status to stderr \\ --strict fail when a response does not match its model \\ --paginate follow a list through every page, printing one list \\ --help show this \\ --version say which zfj this is, and which Forgejo it speaks \\ \\Instances and their tokens are kept in $XDG_CONFIG_HOME/zfj/config.zon. \\FORGEJO_TOKEN, when set, overrides the chosen instance's token; a URL \\that is not a configured instance's is reached anonymously without it. \\ \\Exit status: 0 success, 1 the instance answered with an error, \\2 a usage error, 3 no instance or no answer, 4 (with --strict) a \\response that does not match its documented model, 5 (with \\--exit-status) a run that did not succeed. \\ ; /// The function each command word runs. `entries` lists the same words. const dispatch = .{ .{ "op", op.main }, .{ "issue", issue.main }, .{ "label", label.main }, .{ "package", package.main }, .{ "pr", pr.main }, .{ "repo", repo.main }, .{ "run", runs.main }, .{ "workflow", workflow.main }, .{ "login", instances.login }, .{ "logout", instances.logout }, .{ "instances", instances.instances }, .{ "default", instances.default }, .{ "completion", completion.main }, }; /// The Commands section of the usage, from `entries`. const commands_help = blk: { var text: []const u8 = ""; for (entries) |entry| { const padding = @max(1, 30 - entry.synopsis.len); text = text ++ " " ++ entry.synopsis ++ spaces(padding) ++ entry.summary ++ "\n"; } break :blk text; }; fn spaces(comptime n: usize) []const u8 { const all: [n]u8 = @splat(' '); const frozen = all; return &frozen; } pub fn main(init: std.process.Init) u8 { const arena = init.arena.allocator(); var stdout_buffer: [16 * 1024]u8 = undefined; var stdout_writer: Io.File.Writer = .init(.stdout(), init.io, &stdout_buffer); var stderr_buffer: [1024]u8 = undefined; var stderr_writer: Io.File.Writer = .init(.stderr(), init.io, &stderr_buffer); var ctx: Context = .{ .gpa = init.gpa, .arena = arena, .io = init.io, .environ = init.environ_map, .process_environ = init.minimal.environ, .stdout = &stdout_writer.interface, .stderr = &stderr_writer.interface, .global = .{}, }; defer ctx.deinit(); // A reader that closes the pipe -- `head`, say -- did not want the rest, // so that is no failure of zfj's: it ends quietly and successfully, which // keeps `zfj ... | head` working under `set -o pipefail`. Any other // failure to write, a full disk say, is still reported. const exit = run(&ctx, init.minimal.args) catch |err| switch (err) { error.WriteFailed => if (stdout_writer.err) |write_err| switch (write_err) { error.BrokenPipe => .ok, else => ctx.environment("cannot write the output: {s}", .{@errorName(write_err)}), } else ctx.environment("{s}", .{@errorName(err)}), else => ctx.environment("{s}", .{@errorName(err)}), }; ctx.stdout.flush() catch {}; return @backingInt(exit); } fn run(ctx: *Context, process_args: std.process.Args) !Context.Exit { const argv = try process_args.toSlice(ctx.arena); const words = try ctx.arena.alloc([]const u8, argv.len -| 1); for (words, argv[1..]) |*word, arg| word.* = arg; // Before anything else reads the words, which are a command line being // typed rather than one to run. if (words.len != 0 and std.mem.eql(u8, words[0], "__complete")) return completion.respond(ctx, &entries, comptime args.spec(Context.Global, &global_notes), words[1..]); var diagnostic: args.Diagnostic = .{}; const global = args.parse(Context.Global, ctx.arena, words, .leading, &diagnostic) catch |err| switch (err) { error.Usage => return ctx.usage("{s}", .{diagnostic.message()}), else => |e| return e, }; ctx.global = global.value; if (ctx.global.help) { try ctx.stdout.writeAll(usage); return .ok; } if (ctx.global.version) { try ctx.stdout.writeAll(version_text); return .ok; } if (global.rest == words.len) { try ctx.stderr.writeAll(usage); try ctx.stderr.flush(); return .usage; } const command = words[global.rest]; const rest = words[global.rest + 1 ..]; inline for (dispatch) |entry| { if (std.mem.eql(u8, command, entry[0])) return entry[1](ctx, rest); } if (std.mem.eql(u8, command, "help")) { try ctx.stdout.writeAll(usage); return .ok; } return ctx.usage("unknown command '{s}'; `zfj --help` lists them", .{command}); } /// What `--version` says: zfj's version, and the Forgejo release whose API /// description it was built from. const version_text = "zfj " ++ build_options.version ++ " (Forgejo " ++ zfj.forgejo_version ++ ")\n"; test "--version names zfj's version and the Forgejo it was built for" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); var diagnostics: std.zon.parse.Diagnostics = undefined; const zon = try std.zon.parse.fromSlice(struct { version: []const u8 }, .{ .gpa = std.testing.allocator, .arena = arena.allocator(), .source = @embedFile("build.zig.zon"), .diagnostics = &diagnostics, .ignore_unknown_fields = true, }); const spec = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, @embedFile("swagger.v1.json"), .{}); defer spec.deinit(); const expected = try std.fmt.allocPrint(std.testing.allocator, "zfj {s} (Forgejo {s})\n", .{ zon.version, spec.value.object.get("info").?.object.get("version").?.string, }); defer std.testing.allocator.free(expected); try std.testing.expectEqualStrings(expected, version_text); } test { _ = args; _ = @import("Config.zig"); _ = Context; _ = instances; _ = issue; _ = label; _ = package; _ = pr; _ = repo; _ = runs; _ = workflow; _ = @import("porcelain.zig"); _ = @import("git.zig"); _ = @import("text.zig"); _ = @import("call.zig"); _ = op; _ = completion; } test "every command word dispatched is listed for the usage and completion" { try std.testing.expectEqual(dispatch.len, entries.len); inline for (dispatch) |command| { for (entries) |entry| { if (std.mem.eql(u8, entry.name, command[0])) break; } else return error.Unlisted; } }