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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Plumbing commands: `zfj op <operation>`, one for every operation the//! bindings export, found by looking at the bindings rather than by being//! listed anywhere. A new Forgejo release that adds an operation adds its//! command in the same build.//!//! An operation is a function `name` taking the client first, with a `nameRaw`//! form beside it. Its flags are its params struct's fields; a request body//! arrives on stdin as JSON and is parsed into the operation's model before//! anything is sent. What comes back is written out exactly as Forgejo sent//! it, and also parsed into the model the specification documents, as the//! bindings would parse it -- every plumbing call doubles as a check of the//! bindings against a live instance.
const std = @import("std");const Allocator = std.mem.Allocator;
const zfj = @import("zfj");
const args = @import("args.zig");const Context = @import("Context.zig");const Exit = Context.Exit;
pub const Operation = struct { name: []const u8, run: *const fn (ctx: *Context, words: []const []const u8) anyerror!Exit, help: *const fn (writer: *std.Io.Writer) std.Io.Writer.Error!void, /// What the specification says it does, in a line; empty when it says /// nothing. summary: []const u8, /// Its params, for completing them. spec: args.Spec,};
/// Every operation, in the order the bindings declare them.pub const operations: []const Operation = blk: { @setEvalBranchQuota(1_000_000); var list: []const Operation = &.{}; for (@typeInfo(zfj).@"struct".decl_names) |name| { if (isOperation(name)) list = list ++ .{Operation{ .name = name, .run = Command(name).run, .help = Command(name).help, .summary = Command(name).one_line, .spec = Command(name).spec, }}; } const frozen = list[0..list.len].*; break :blk &frozen;};
fn isOperation(comptime name: []const u8) bool { if (!std.ascii.isLower(name[0])) return false; if (!@hasDecl(zfj, name ++ "Raw")) return false; const info = @typeInfo(@TypeOf(@field(zfj, name))); if (info != .@"fn") return false; const params = info.@"fn".param_types; return params.len >= 1 and params[0] == *zfj.Client;}
pub fn find(name: []const u8) ?Operation { for (operations) |operation| { if (std.mem.eql(u8, operation.name, name)) return operation; } return null;}
/// `zfj op [<operation> [--help | <params>...]]`.pub fn main(ctx: *Context, words: []const []const u8) !Exit { if (words.len == 0 or std.mem.eql(u8, words[0], "--help")) { for (operations) |operation| try ctx.stdout.print("{s}\n", .{operation.name}); return .ok; } const operation = find(words[0]) orelse return ctx.usage("unknown operation '{s}'; `zfj op` lists them", .{words[0]}); for (words[1..]) |word| { if (std.mem.eql(u8, word, "--help")) { try ctx.stdout.print("usage: zfj [<global options>] op {s} [<params>]\n", .{operation.name}); try operation.help(ctx.stdout); return .ok; } } return operation.run(ctx, words[1..]);}
fn Command(comptime name: []const u8) type { return struct { const raw = @field(zfj, name ++ "Raw"); const fn_params = @typeInfo(@TypeOf(raw)).@"fn".param_types;
/// The operation's params struct, or nothing when it has none. const Params = if (fn_params.len >= 2 and isParams(fn_params[1].?)) fn_params[1].? else struct {}; const has_params = fn_params.len >= 2 and isParams(fn_params[1].?);
/// What the operation sends as its request body, if anything. const Body: ?type = switch (fn_params.len - @intFromBool(has_params)) { 1 => null, 2 => fn_params[fn_params.len - 1].?, else => @compileError(name ++ " takes more arguments than a client, params and a body"), };
/// What the response is parsed into, or null when it is not JSON /// there is anything to check: an empty response, or one the /// bindings hand back as bytes. const Response: ?type = blk: { const returned = @typeInfo(@typeInfo(@TypeOf(@field(zfj, name))).@"fn".return_type.?).error_union.payload; if (returned == void) break :blk null; const T = @FieldType(returned, "parsed"); const Value = @FieldType(T, "value"); if (Value == []const u8) break :blk null; break :blk Value; };
fn isParams(comptime T: type) bool { const params_name = [_]u8{std.ascii.toUpper(name[0])} ++ name[1..] ++ "Params"; return @hasDecl(zfj, params_name) and @field(zfj, params_name) == T; }
/// What the specification says of the operation. const info: zfj.OperationInfo = @field(zfj.operation_info, name);
/// Whether `--paginate` can follow it: it returns a list, and takes /// the page to return as a param. const paginated = has_params and @hasField(Params, "page") and if (Response) |R| @typeInfo(R) == .pointer and @typeInfo(R).pointer.size == .slice else false;
/// The params' descriptions and allowed values, in field order. const notes = blk: { @setEvalBranchQuota(100_000); const field_names = @typeInfo(Params).@"struct".field_names; var result: [field_names.len]args.Note = undefined; for (field_names, &result) |field_name, *note| { note.* = if (info.param(field_name)) |p| .{ .description = p.description, .allowed = p.allowed } else .{}; } const frozen = result; break :blk &frozen; };
const one_line: []const u8 = blk: { const text = std.mem.trim(u8, info.summary orelse "", " \r\n"); break :blk text[0 .. std.mem.findAny(u8, text, "\r\n") orelse text.len]; };
const spec = args.spec(Params, notes);
fn help(writer: *std.Io.Writer) std.Io.Writer.Error!void { if (info.summary) |summary| try writer.print("\n{s}\n", .{std.mem.trim(u8, summary, " \r\n")}); if (info.description) |description| { const trimmed = std.mem.trim(u8, description, " \r\n"); const same = if (info.summary) |summary| std.mem.eql(u8, trimmed, std.mem.trim(u8, summary, " \r\n")) else false; if (!same and trimmed.len != 0) try writer.print("\n{s}\n", .{trimmed}); } try writer.print("\n{s} {s}\n", .{ @tagName(info.method), info.path }); if (info.deprecated) try writer.writeAll("\nDeprecated.\n"); try writer.writeAll("\nParams:\n"); try args.writeHelp(Params, writer, notes); if (Body) |B| { if (B == []const u8) { try writer.writeAll("\nThe request body is read from stdin as it is.\n"); } else { try writer.print("\nThe request body is read from stdin as JSON, a {s}.\n", .{shortName(@typeName(B))}); } } if (paginated) try writer.writeAll("\nWith --paginate, every page is fetched and the lists are joined into one.\n"); }
fn send(client: *zfj.Client, params: Params, body: if (Body) |B| B else void) !zfj.RawResponse { if (Body != null) { return if (has_params) raw(client, params, body) else raw(client, body); } return if (has_params) raw(client, params) else raw(client); }
/// Parses a successful response into its documented model, as the /// bindings would, and says so when that fails. fn check(ctx: *Context, body: []const u8) Exit { const R = Response orelse return .ok; if (body.len == 0) return .ok; // The same options the bindings parse with, so that what this // reports is what a caller of `name` would meet. const parsed = std.json.parseFromSlice(R, ctx.gpa, body, .{ .ignore_unknown_fields = true }); if (parsed) |p| p.deinit() else |err| return ctx.parseFailure(name, shortName(@typeName(R)), @errorName(err)); return .ok; }
fn run(ctx: *Context, words: []const []const u8) anyerror!Exit { var diagnostic: args.Diagnostic = .{}; var params = (args.parse(Params, ctx.arena, words, .all, &diagnostic) catch |err| switch (err) { error.Usage => return ctx.usage("{s}", .{diagnostic.message()}), else => |e| return e, }).value; if (ctx.global.paginate and !paginated) return ctx.usage("{s} does not return pages of a list, so --paginate cannot follow it", .{name}); loadFiles(ctx, ¶ms) catch |err| switch (err) { error.Usage => return .usage, else => |e| return e, };
const client = ctx.client() catch return .environment;
const body = if (Body) |B| readBody(B, ctx) catch |err| switch (err) { error.Usage => return .usage, else => |e| return e, } else {};
if (!paginated or !ctx.global.paginate) { var response = send(client, params, body) catch |err| return ctx.transport(name, err); defer response.deinit(); if (response.status.class() != .success) return ctx.apiError(name, response.status, response.body); try ctx.stdout.writeAll(response.body); try ctx.stdout.flush(); return check(ctx, response.body); }
// Every page, joined into one list as each arrived. The pages are // asked for through the operation itself, with `page` set to // what the `Link` header names as next, so that each is sent // and checked exactly as the first was. var joined: std.Io.Writer.Allocating = .init(ctx.gpa); defer joined.deinit(); try joined.writer.writeByte('['); var any = false; while (true) { var response = send(client, params, body) catch |err| return ctx.transport(name, err); defer response.deinit(); if (response.status.class() != .success) return ctx.apiError(name, response.status, response.body);
const checked = check(ctx, response.body); if (checked != .ok) return checked; const items = listItems(response.body) orelse { _ = ctx.parseFailure(name, "a JSON array", "NotAnArray"); return .response_mismatch; }; if (items.len != 0) { if (any) try joined.writer.writeByte(','); try joined.writer.writeAll(items); any = true; }
const next = nextPage(response.header("link")) orelse break; // A server that names the page it is on, or an earlier one, // as the next would be followed forever. if (next <= (params.page orelse 1)) break; params.page = next; } try joined.writer.writeAll("]\n"); try ctx.stdout.writeAll(joined.written()); try ctx.stdout.flush(); return .ok; }
/// Reads each file to upload from the path its flag gave: the file /// itself, named for the part after its basename; or with `-`, /// stdin, named after the operation's `name` param if it has one /// and it was given, and otherwise after the param. fn loadFiles(ctx: *Context, params: *Params) anyerror!void { const info_fields = @typeInfo(Params).@"struct"; inline for (info_fields.field_names, info_fields.field_types) |field_name, Field| { const optional = @typeInfo(Field) == .optional; const Value = if (optional) @typeInfo(Field).optional.child else Field; if (comptime args.isFile(Value)) { const slot: ?*Value = if (optional) (if (@field(params, field_name)) |*v| v else null) else &@field(params, field_name); if (slot) |file| { const path = file.filename; if (std.mem.eql(u8, path, "-")) { file.bytes = try ctx.readStdin(); file.filename = field_name; if (@hasField(Params, "name") and @FieldType(Params, "name") == ?[]const u8) { if (@field(params, "name")) |given| file.filename = given; } } else { file.bytes = std.Io.Dir.cwd().readFileAlloc(ctx.io, path, ctx.arena, .unlimited) catch |err| { _ = ctx.usage("cannot read {s} for --{s}: {s}", .{ path, field_name, @errorName(err) }); return error.Usage; }; file.filename = std.fs.path.basename(path); } } } } }
fn readBody(comptime B: type, ctx: *Context) anyerror!B { const text = try ctx.readStdin(); if (B == []const u8) return text; return std.json.parseFromSliceLeaky(B, ctx.arena, text, .{}) catch |err| { _ = ctx.usage("the request body on stdin is not a {s}: {s}", .{ shortName(@typeName(B)), @errorName(err) }); return error.Usage; }; } };}
/// The items of a JSON array, without its brackets: what is joined when the/// pages of a list are made one.pub fn listItems(body: []const u8) ?[]const u8 { const trimmed = std.mem.trim(u8, body, " \t\r\n"); if (trimmed.len < 2 or trimmed[0] != '[' or trimmed[trimmed.len - 1] != ']') return null; return std.mem.trim(u8, trimmed[1 .. trimmed.len - 1], " \t\r\n");}
/// The page a `Link` header names as `rel="next"`, read from that URL's/// `page` query value.pub fn nextPage(link: ?[]const u8) ?i64 { var links = std.mem.splitScalar(u8, link orelse return null, ','); while (links.next()) |entry| { const open = std.mem.findScalar(u8, entry, '<') orelse continue; const close = std.mem.findScalarPos(u8, entry, open, '>') orelse continue; const attributes = entry[close + 1 ..]; if (std.mem.find(u8, attributes, "rel=\"next\"") == null and std.mem.find(u8, attributes, "rel=next") == null) continue; const url = entry[open + 1 .. close]; const query = url[(std.mem.findScalar(u8, url, '?') orelse return null) + 1 ..]; var pairs = std.mem.splitScalar(u8, query, '&'); while (pairs.next()) |pair| { if (std.mem.startsWith(u8, pair, "page=")) return std.fmt.parseInt(i64, pair["page=".len..], 10) catch null; } return null; } return null;}
/// `api.CreateIssueOption` is `CreateIssueOption` to anyone reading.fn shortName(comptime type_name: []const u8) []const u8 { const dot = comptime std.mem.findScalarLast(u8, type_name, '.'); return if (dot) |d| type_name[d + 1 ..] else type_name;}
const testing = std.testing;
test "every operation in the specification is a command" { // Counted from the specification itself, so that this does not have to // change when Forgejo adds an operation -- only when finding them does. const spec = try std.json.parseFromSlice(std.json.Value, testing.allocator, @embedFile("swagger.v1.json"), .{}); defer spec.deinit(); var expected: usize = 0; var paths = spec.value.object.get("paths").?.object.iterator(); while (paths.next()) |path| { var methods = path.value_ptr.object.iterator(); while (methods.next()) |method| { if (method.value_ptr.* == .object and method.value_ptr.object.get("operationId") != null) expected += 1; } } try testing.expectEqual(expected, operations.len);}
test "operations are found by name, and their forms are not operations" { try testing.expect(find("issueGetIssue") != null); try testing.expect(find("renderRawMarkdown") != null); try testing.expect(find("listActionRuns") != null); try testing.expect(find("issueGetIssueRaw") == null); try testing.expect(find("issueGetIssueResult") == null); try testing.expect(find("IssueGetIssue") == null);}
test "an operation knows its params, body and response" { const create = Command("issueCreateIssue"); try testing.expectEqual(zfj.IssueCreateIssueParams, create.Params); try testing.expectEqual(zfj.CreateIssueOption, create.Body.?); try testing.expectEqual(zfj.Issue, create.Response.?);
const version = Command("getVersion"); try testing.expect(!version.has_params); try testing.expect(version.Body == null);
const markdown = Command("renderRawMarkdown"); try testing.expectEqual([]const u8, markdown.Body.?); try testing.expect(markdown.Response == null);
try testing.expect(Command("issueDelete").Response == null); try testing.expectEqual([]const zfj.Issue, Command("issueListIssues").Response.?);}
test "the next page is read from the Link header" { try testing.expectEqual(@as(?i64, 3), nextPage( \\<https://example.org/api/v1/repos/search?limit=2&page=3&q=zig>; rel="next",<https://example.org/api/v1/repos/search?limit=2&page=9&q=zig>; rel="last" )); try testing.expectEqual(@as(?i64, null), nextPage( \\<https://example.org/api/v1/repos/search?page=1>; rel="first",<https://example.org/api/v1/repos/search?page=2>; rel="prev" )); try testing.expectEqual(@as(?i64, null), nextPage(null));}
test "a list's items are what lies between its brackets" { try testing.expectEqualStrings("{\"a\":1},{\"b\":2}", listItems("[{\"a\":1},{\"b\":2}]\n").?); try testing.expectEqualStrings("", listItems(" [ ] ").?); try testing.expect(listItems("{\"ok\":true}") == null);}
test "an operation that returns pages of a list can be paginated" { try testing.expect(Command("issueListIssues").paginated); try testing.expect(Command("repoListBranches").paginated); try testing.expect(!Command("issueGetIssue").paginated); try testing.expect(!Command("getVersion").paginated); try testing.expect(!Command("repoSearch").paginated);}