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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Fetches the Forgejo API description and writes it to standard output, where//! the build picks it up and copies it over `api/swagger.v1.json`.//!//! Forgejo keeps the description as `templates/swagger/v1_json.tmpl`, a Go//! template that an instance renders and serves at `/swagger.v1.json`. Taking//! it from a release tag rather than from a running instance is what makes the//! vendored file say which Forgejo it describes: an instance's copy is stamped//! with whatever development build happens to be deployed there.//!//! Only two substitutions stand between the template and plain JSON, and both//! are required to be present. If a future Forgejo introduces a third or//! renames one of these, this fails rather than writing a file with a Go//! template expression left in the middle of it.
const std = @import("std");
const forge = "https://codeberg.org";const repository = "forgejo/forgejo";const template_path = "templates/swagger/v1_json.tmpl";
/// The instance's version string. Set to the release being vendored, which is/// what makes the file self-describing.const version_placeholder = "{{AppVer | JSEscape}}";/// The path an instance is mounted under. Empty for a stock installation,/// which is the only shape the `basePath` in a vendored file can sensibly have.const sub_url_placeholder = "{{AppSubUrl | JSEscape}}";
const log = std.log.scoped(.update_spec);
pub fn main(init: std.process.Init) !u8 { const io = init.io; const gpa = init.gpa;
var arguments = try std.process.Args.Iterator.initAllocator(init.minimal.args, gpa); defer arguments.deinit(); _ = arguments.next(); const requested_tag: ?[]const u8 = arguments.next();
var http: std.http.Client = .{ .allocator = gpa, .io = io }; defer http.deinit();
const tag = if (requested_tag) |requested| try gpa.dupe(u8, requested) else try latestReleaseTag(gpa, &http); defer gpa.free(tag);
// Forgejo tags releases `v16.0.3` and reports itself as `16.0.3`. const version = if (std.mem.startsWith(u8, tag, "v")) tag[1..] else tag;
const url = try std.fmt.allocPrint(gpa, "{s}/{s}/raw/tag/{s}/{s}", .{ forge, repository, tag, template_path }); defer gpa.free(url);
log.info("fetching the Forgejo {s} API description", .{tag}); const template = try get(gpa, &http, url); defer gpa.free(template);
const spec = try render(gpa, template, version); defer gpa.free(spec);
try verify(gpa, spec, version); log.info("{d} bytes describing Forgejo {s}", .{ spec.len, version });
var stdout_buffer: [4096]u8 = undefined; var stdout_file: std.Io.File = .stdout(); var stdout_writer = stdout_file.writer(io, &stdout_buffer); const stdout = &stdout_writer.interface; try stdout.writeAll(spec); try stdout.flush();
return 0;}
/// The newest release Forgejo has published. Forgejo maintains several release/// branches at once, so this is the newest of all of them and not necessarily/// a successor to the version currently vendored -- which is why the build/// takes `-Dforgejo-version` for pinning to a particular one.fn latestReleaseTag(gpa: std.mem.Allocator, http: *std.http.Client) ![]u8 { const url = try std.fmt.allocPrint(gpa, "{s}/api/v1/repos/{s}/releases/latest", .{ forge, repository }); defer gpa.free(url);
const body = try get(gpa, http, url); defer gpa.free(body);
const parsed = try std.json.parseFromSlice(std.json.Value, gpa, body, .{ .ignore_unknown_fields = true }); defer parsed.deinit();
const tag = parsed.value.object.get("tag_name") orelse { log.err("the latest release carries no tag name", .{}); return error.UnexpectedResponse; }; if (tag != .string) { log.err("the latest release's tag name is not a string", .{}); return error.UnexpectedResponse; } return try gpa.dupe(u8, tag.string);}
fn get(gpa: std.mem.Allocator, http: *std.http.Client, url: []const u8) ![]u8 { var body: std.Io.Writer.Allocating = .init(gpa); errdefer body.deinit();
const result = try http.fetch(.{ .location = .{ .url = url }, .method = .GET, .response_writer = &body.writer, }); if (result.status != .ok) { log.err("{s} answered {d} {s}", .{ url, @backingInt(result.status), result.status.phrase() orelse "" }); return error.HttpRequestFailed; }
return try body.toOwnedSlice();}
/// Substitute the template's two placeholders, requiring both to be present.fn render(gpa: std.mem.Allocator, template: []const u8, version: []const u8) ![]u8 { const versioned = try replaceOnce(gpa, template, version_placeholder, version); defer gpa.free(versioned); return try replaceOnce(gpa, versioned, sub_url_placeholder, "");}
/// `std.mem.replaceOwned`, except that a needle which is not there is an error/// rather than a copy of the input. This is the whole safety of rendering the/// template by substitution: the day Forgejo changes one of these, the build/// stops here instead of quietly vendoring a file with a Go template/// expression in it.fn replaceOnce(gpa: std.mem.Allocator, input: []const u8, needle: []const u8, replacement: []const u8) ![]u8 { const occurrences = std.mem.count(u8, input, needle); if (occurrences != 1) { log.err("expected exactly one '{s}' in the template, found {d}", .{ needle, occurrences }); return error.TemplateChanged; } // The caller owns `input` and frees it itself, so this cannot free it. return try std.mem.replaceOwned(u8, gpa, input, needle, replacement);}
/// Check that what came back is the document it claims to be, before it is/// written over the one in the source tree.fn verify(gpa: std.mem.Allocator, spec: []const u8, version: []const u8) !void { const parsed = std.json.parseFromSlice(std.json.Value, gpa, spec, .{}) catch |err| { log.err("the rendered description is not valid JSON: {t}", .{err}); return error.InvalidSpecification; }; defer parsed.deinit();
if (parsed.value != .object) { log.err("the rendered description is not a JSON object", .{}); return error.InvalidSpecification; } const root = parsed.value.object;
try expectString(root, "swagger", "2.0"); try expectString(root, "basePath", "/api/v1");
const info = root.get("info") orelse { log.err("the rendered description has no 'info'", .{}); return error.InvalidSpecification; }; if (info != .object) { log.err("the rendered description's 'info' is not an object", .{}); return error.InvalidSpecification; } try expectString(info.object, "version", version);
// A description with no paths would generate a client with no operations, // which would compile and be entirely useless. const paths = root.get("paths") orelse { log.err("the rendered description has no 'paths'", .{}); return error.InvalidSpecification; }; if (paths != .object or paths.object.count() == 0) { log.err("the rendered description describes no paths", .{}); return error.InvalidSpecification; }}
fn expectString(object: std.json.ObjectMap, key: []const u8, expected: []const u8) !void { const value = object.get(key) orelse { log.err("the rendered description has no '{s}'", .{key}); return error.InvalidSpecification; }; if (value != .string or !std.mem.eql(u8, value.string, expected)) { log.err("expected '{s}' to be \"{s}\"", .{ key, expected }); return error.InvalidSpecification; }}