feat: output rendering (JSON/XML/human helpers); musl default build with libc for localtime (M5 part 1)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Daniel SamsonandClaude Sonnet 5.5 committed 2026-10-17 13:36:29 +01:00
1 parent 0d91b0490a
commit bd4e585ed8
4 files changed
+620 -135

No files matched your search

+585
View File
@@ -0,0 +1,585 @@
//! Structured output for the CLI: a small value tree (`Node`) rendered as JSON (Jackson layout)
//! or XML, plus helpers for human-readable output (sizes, ages, local timestamps, colour).
const std = @import("std");
const builtin = @import("builtin");
const Io = std.Io;
const Allocator = std.mem.Allocator;
const jsonpretty = @import("jsonpretty.zig");
const jobjson = @import("jobjson.zig");
const timestamp = @import("timestamp.zig");
const Job = @import("job.zig").Job;
const Instant = @import("job.zig").Instant;
pub const Format = enum {
human,
json,
xml,
/// Case-insensitive, like barn's `--output`.
pub fn parse(text: []const u8) ?Format {
inline for (@typeInfo(Format).@"enum".fields) |f| {
if (std.ascii.eqlIgnoreCase(text, f.name)) return @field(Format, f.name);
}
return null;
}
};
pub const Node = union(enum) {
null,
boolean: bool,
int: i64,
float: f64,
string: []const u8,
list: []const Node,
map: []const Entry,
/// Rendered with the shared job JSON layout (and barn's `<job>` XML shape).
job: Job,
pub const Entry = struct { key: []const u8, value: Node };
pub fn str(s: []const u8) Node {
return .{ .string = s };
}
pub fn optStr(s: ?[]const u8) Node {
return if (s) |v| .{ .string = v } else .null;
}
pub fn num(n: anytype) Node {
return .{ .int = @intCast(n) };
}
};
/// Collects map entries; `done` returns the node.
pub const MapBuilder = struct {
arena: Allocator,
entries: std.ArrayList(Node.Entry) = .empty,
pub fn init(arena: Allocator) MapBuilder {
return .{ .arena = arena };
}
pub fn put(self: *MapBuilder, key: []const u8, value: Node) Allocator.Error!void {
try self.entries.append(self.arena, .{ .key = key, .value = value });
}
pub fn done(self: *MapBuilder) Allocator.Error!Node {
return .{ .map = try self.entries.toOwnedSlice(self.arena) };
}
};
// -- JSON ------------------------------------------------------------------------------
pub fn writeNodeJson(w: *jsonpretty.Writer, node: Node) !void {
switch (node) {
.null => try w.@"null"(),
.boolean => |b| try w.boolean(b),
.int => |n| try w.int(n),
.float => |f| try w.float(f),
.string => |s| try w.string(s),
.list => |items| {
try w.beginArray();
for (items) |i| try writeNodeJson(w, i);
try w.endArray();
},
.map => |entries| {
try w.beginObject();
for (entries) |e| {
try w.key(e.key);
try writeNodeJson(w, e.value);
}
try w.endObject();
},
.job => |j| try jobjson.writeJob(w, j),
}
}
pub fn renderJson(out: *Io.Writer, node: Node) !void {
var w = jsonpretty.Writer.init(out);
try writeNodeJson(&w, node);
try out.writeByte('\n');
}
// -- XML -------------------------------------------------------------------------------
const xml_header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
fn xmlEscape(out: *Io.Writer, text: []const u8) !void {
for (text) |c| switch (c) {
'&' => try out.writeAll("&amp;"),
'<' => try out.writeAll("&lt;"),
'>' => try out.writeAll("&gt;"),
'"' => try out.writeAll("&quot;"),
'\'' => try out.writeAll("&apos;"),
else => try out.writeByte(c),
};
}
/// `camelCase` -> `camel_case` (names already in snake_case pass through).
fn writeSnake(out: *Io.Writer, name: []const u8) !void {
for (name, 0..) |c, i| {
if (std.ascii.isUpper(c)) {
if (i > 0) try out.writeByte('_');
try out.writeByte(std.ascii.toLower(c));
} else try out.writeByte(c);
}
}
fn itemName(key: []const u8) []const u8 {
if (std.mem.eql(u8, key, "command")) return "arg";
if (std.mem.eql(u8, key, "cleaned")) return "job";
if (key.len > 1 and key[key.len - 1] == 's') return key[0 .. key.len - 1];
return "item";
}
fn indent(out: *Io.Writer, depth: usize) !void {
for (0..depth) |_| try out.writeAll(" ");
}
fn xmlTime(out: *Io.Writer, t: Instant) !void {
var buf: [timestamp.max_len]u8 = undefined;
try out.writeAll(timestamp.format(&buf, t));
}
fn xmlLeaf(out: *Io.Writer, depth: usize, name: []const u8, comptime fmt: []const u8, args: anytype) !void {
try indent(out, depth);
try out.print("<{s}>", .{name});
try out.print(fmt, args);
try out.print("</{s}>\n", .{name});
}
/// Barn's `<job>` element: optional fields are omitted, state is lowercase.
fn xmlJob(out: *Io.Writer, job: Job, depth: usize) !void {
try indent(out, depth);
try out.writeAll("<job>\n");
const d = depth + 1;
try indent(out, d);
try out.writeAll("<id>");
try xmlEscape(out, job.id);
try out.writeAll("</id>\n");
try xmlLeaf(out, d, "state", "{s}", .{job.state.lower()});
try indent(out, d);
try out.writeAll("<command>\n");
for (job.command) |arg| {
try indent(out, d + 1);
try out.writeAll("<arg>");
try xmlEscape(out, arg);
try out.writeAll("</arg>\n");
}
try indent(out, d);
try out.writeAll("</command>\n");
if (job.tag) |t| {
try indent(out, d);
try out.writeAll("<tag>");
try xmlEscape(out, t);
try out.writeAll("</tag>\n");
}
try xmlJobTime(out, d, "created_at", job.created_at);
if (job.started_at) |t| try xmlJobTime(out, d, "started_at", t);
if (job.finished_at) |t| try xmlJobTime(out, d, "finished_at", t);
if (job.exit_code) |c| switch (c) {
.code => |n| try xmlLeaf(out, d, "exit_code", "{d}", .{n}),
.symbol => |s| {
try indent(out, d);
try out.writeAll("<exit_code>");
try xmlEscape(out, s);
try out.writeAll("</exit_code>\n");
},
};
if (job.err) |e| {
try indent(out, d);
try out.writeAll("<error>");
try xmlEscape(out, e);
try out.writeAll("</error>\n");
}
if (job.pid) |p| try xmlLeaf(out, d, "pid", "{d}", .{p});
if (job.heartbeat) |t| try xmlJobTime(out, d, "heartbeat", t);
if (job.retry_count > 0) try xmlLeaf(out, d, "retry_count", "{d}", .{job.retry_count});
if (job.retry_at) |t| try xmlJobTime(out, d, "retry_at", t);
try xmlLeaf(out, d, "load_level", "{s}", .{job.load_level.lower()});
try indent(out, depth);
try out.writeAll("</job>\n");
}
fn xmlJobTime(out: *Io.Writer, depth: usize, name: []const u8, t: Instant) !void {
try indent(out, depth);
try out.print("<{s}>", .{name});
try xmlTime(out, t);
try out.print("</{s}>\n", .{name});
}
fn xmlValue(out: *Io.Writer, name: []const u8, node: Node, depth: usize) anyerror!void {
switch (node) {
.null => {
try indent(out, depth);
try out.writeByte('<');
try writeSnake(out, name);
try out.writeAll("/>\n");
},
.job => |j| try xmlJob(out, j, depth),
.boolean, .int, .float, .string => {
try indent(out, depth);
try out.writeByte('<');
try writeSnake(out, name);
try out.writeByte('>');
switch (node) {
.boolean => |b| try out.writeAll(if (b) "true" else "false"),
.int => |n| try out.print("{d}", .{n}),
.float => |f| try out.print("{d}", .{f}),
.string => |s| try xmlEscape(out, s),
else => unreachable,
}
try out.writeAll("</");
try writeSnake(out, name);
try out.writeAll(">\n");
},
.list => |items| {
try indent(out, depth);
try out.writeByte('<');
try writeSnake(out, name);
if (items.len == 0) return out.writeAll("/>\n");
try out.writeAll(">\n");
for (items) |i| try xmlValue(out, itemName(name), i, depth + 1);
try indent(out, depth);
try out.writeAll("</");
try writeSnake(out, name);
try out.writeAll(">\n");
},
.map => |entries| {
try indent(out, depth);
try out.writeByte('<');
try writeSnake(out, name);
try out.writeAll(">\n");
for (entries) |e| try xmlValue(out, e.key, e.value, depth + 1);
try indent(out, depth);
try out.writeAll("</");
try writeSnake(out, name);
try out.writeAll(">\n");
},
}
}
/// Renders a document. A bare job becomes `<job>`, a list `<results>`, anything else `<result>`.
pub fn renderXml(out: *Io.Writer, node: Node) !void {
try out.writeAll(xml_header);
switch (node) {
.job => |j| try xmlJob(out, j, 0),
.list => |items| {
if (items.len == 0) return out.writeAll("<results/>\n");
try out.writeAll("<results>\n");
for (items) |i| try xmlValue(out, "item", i, 1);
try out.writeAll("</results>\n");
},
else => try xmlValue(out, "result", node, 0),
}
}
pub fn render(out: *Io.Writer, format: Format, node: Node) !void {
switch (format) {
.json => try renderJson(out, node),
.xml => try renderXml(out, node),
.human => unreachable, // commands print human output themselves
}
}
/// Error output in the selected format (barn: `{"error":true,"message":...}`, `<error>`).
pub fn renderError(out: *Io.Writer, format: Format, color: Color, message: []const u8, cause: ?[]const u8) !void {
switch (format) {
.human => {
try out.print("{f}{s}\n", .{ color.wrap("Error: ", .red_bold), message });
if (cause) |c| try out.print("{f}{s}\n", .{ color.wrap("Cause: ", .yellow), c });
},
.json => {
var w = jsonpretty.Writer.init(out);
try w.beginObject();
try w.field("error", .boolean, true);
try w.field("message", .string, message);
if (cause) |c| try w.field("cause", .string, c);
try w.endObject();
try out.writeByte('\n');
},
.xml => {
try out.writeAll(xml_header);
try out.writeAll("<error>\n <message>");
try xmlEscape(out, message);
try out.writeAll("</message>\n");
if (cause) |c| {
try out.writeAll(" <cause>");
try xmlEscape(out, c);
try out.writeAll("</cause>\n");
}
try out.writeAll("</error>\n");
},
}
}
// -- human helpers ---------------------------------------------------------------------
pub const Style = enum { reset, bold, red, green, yellow, cyan, red_bold };
pub const Color = struct {
enabled: bool = false,
fn code(style: Style) []const u8 {
return switch (style) {
.reset => "\x1b[0m",
.bold => "\x1b[1m",
.red => "\x1b[31m",
.green => "\x1b[32m",
.yellow => "\x1b[33m",
.cyan => "\x1b[36m",
.red_bold => "\x1b[31m\x1b[1m",
};
}
/// Wraps `text` in escape codes when colour is on. Returns a formatter-friendly value.
pub fn wrap(self: Color, text: []const u8, style: Style) Wrapped {
return .{ .text = text, .style = style, .on = self.enabled };
}
pub const Wrapped = struct {
text: []const u8,
style: Style,
on: bool,
pub fn format(self: Wrapped, w: *Io.Writer) Io.Writer.Error!void {
if (self.on) try w.writeAll(code(self.style));
try w.writeAll(self.text);
if (self.on) try w.writeAll(code(.reset));
}
};
};
/// `1023 B`, `1.5 KB`, `2.0 MB`, `1.25 GB` (usage output).
pub fn formatBytes(buf: []u8, bytes: u64) []const u8 {
if (bytes < 1024) return std.fmt.bufPrint(buf, "{d} B", .{bytes}) catch "?";
const kb = @as(f64, @floatFromInt(bytes)) / 1024.0;
if (kb < 1024) return std.fmt.bufPrint(buf, "{d:.1} KB", .{kb}) catch "?";
const mb = kb / 1024.0;
if (mb < 1024) return std.fmt.bufPrint(buf, "{d:.1} MB", .{mb}) catch "?";
return std.fmt.bufPrint(buf, "{d:.2} GB", .{mb / 1024.0}) catch "?";
}
/// `512 B`, `3 KB`, `7 MB`, `1.5 GB` (clean output; integer division like barn).
pub fn formatSize(buf: []u8, bytes: u64) []const u8 {
if (bytes < 1024) return std.fmt.bufPrint(buf, "{d} B", .{bytes}) catch "?";
if (bytes < 1024 * 1024) return std.fmt.bufPrint(buf, "{d} KB", .{bytes / 1024}) catch "?";
if (bytes < 1024 * 1024 * 1024) return std.fmt.bufPrint(buf, "{d} MB", .{bytes / (1024 * 1024)}) catch "?";
return std.fmt.bufPrint(buf, "{d:.1} GB", .{@as(f64, @floatFromInt(bytes)) / (1024.0 * 1024.0 * 1024.0)}) catch "?";
}
/// `5s ago`, `3m ago`, `2h ago`, `4d ago`, `in the future`.
pub fn relativeTime(buf: []u8, seconds: i64) []const u8 {
if (seconds < 0) return "in the future";
if (seconds < 60) return std.fmt.bufPrint(buf, "{d}s ago", .{seconds}) catch "?";
if (seconds < 3600) return std.fmt.bufPrint(buf, "{d}m ago", .{@divFloor(seconds, 60)}) catch "?";
if (seconds < 86400) return std.fmt.bufPrint(buf, "{d}h ago", .{@divFloor(seconds, 3600)}) catch "?";
return std.fmt.bufPrint(buf, "{d}d ago", .{@divFloor(seconds, 86400)}) catch "?";
}
/// `42 seconds`, `5 minutes`, `2 hours, 3 minutes`, `1 days, 4 hours` (service uptime).
pub fn formatUptime(buf: []u8, seconds: i64) []const u8 {
const s = @max(seconds, 0);
if (s < 60) return std.fmt.bufPrint(buf, "{d} seconds", .{s}) catch "?";
if (s < 3600) return std.fmt.bufPrint(buf, "{d} minutes", .{@divFloor(s, 60)}) catch "?";
if (s < 86400) return std.fmt.bufPrint(buf, "{d} hours, {d} minutes", .{ @divFloor(s, 3600), @divFloor(@mod(s, 3600), 60) }) catch "?";
return std.fmt.bufPrint(buf, "{d} days, {d} hours", .{ @divFloor(s, 86400), @divFloor(@mod(s, 86400), 3600) }) catch "?";
}
/// `42 hours old` / `3 days old` (clean output).
pub fn formatAge(buf: []u8, seconds: i64) []const u8 {
const hours = @divFloor(@max(seconds, 0), 3600);
if (hours < 24) return std.fmt.bufPrint(buf, "{d} hours old", .{hours}) catch "?";
const days = @divFloor(hours, 24);
return std.fmt.bufPrint(buf, "{d} day{s} old", .{ days, if (days != 1) "s" else "" }) catch "?";
}
const CTm = extern struct {
tm_sec: c_int,
tm_min: c_int,
tm_hour: c_int,
tm_mday: c_int,
tm_mon: c_int,
tm_year: c_int,
tm_wday: c_int,
tm_yday: c_int,
tm_isdst: c_int,
tm_gmtoff: c_long,
tm_zone: ?[*:0]const u8,
};
extern "c" fn localtime_r(timep: *const i64, result: *CTm) ?*CTm;
/// `yyyy-MM-dd HH:mm:ss` in the system time zone (UTC on platforms without `localtime_r`).
pub fn formatLocal(buf: *[19]u8, t: Instant) []const u8 {
const secs: i64 = @intCast(@divFloor(t, std.time.ns_per_s));
var year: i64 = undefined;
var parts: [5]i64 = undefined; // month, day, hour, minute, second
if (builtin.os.tag == .windows or builtin.os.tag == .wasi) {
const es = std.time.epoch.EpochSeconds{ .secs = @intCast(secs) };
const yd = es.getEpochDay().calculateYearDay();
const md = yd.calculateMonthDay();
const ds = es.getDaySeconds();
year = yd.year;
parts = .{ md.month.numeric(), md.day_index + 1, ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute() };
} else {
var tm: CTm = undefined;
if (localtime_r(&secs, &tm) == null) return "-";
year = @as(i64, tm.tm_year) + 1900;
parts = .{ tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec };
}
// Unsigned on purpose: width/fill on a signed integer prints a leading '+'.
const y: u32 = @intCast(year);
var p: [5]u32 = undefined;
for (parts, &p) |v, *slot| slot.* = @intCast(v);
return std.fmt.bufPrint(buf, "{d:0>4}-{d:0>2}-{d:0>2} {d:0>2}:{d:0>2}:{d:0>2}", .{ y, p[0], p[1], p[2], p[3], p[4] }) catch "-";
}
// -- tests -----------------------------------------------------------------------------
fn expectRender(comptime renderFn: anytype, args: anytype, expected: []const u8) !void {
var aw: Io.Writer.Allocating = .init(std.testing.allocator);
defer aw.deinit();
try @call(.auto, renderFn, .{&aw.writer} ++ args);
try std.testing.expectEqualStrings(expected, aw.written());
}
test "Format.parse is case-insensitive" {
try std.testing.expectEqual(Format.json, Format.parse("JSON").?);
try std.testing.expectEqual(Format.xml, Format.parse("Xml").?);
try std.testing.expect(Format.parse("yaml") == null);
}
test "JSON rendering of maps, lists and nulls" {
const node: Node = .{ .map = &.{
.{ .key = "status", .value = Node.str("running") },
.{ .key = "running", .value = .{ .boolean = true } },
.{ .key = "pid", .value = Node.num(17474) },
.{ .key = "tag", .value = .null },
.{ .key = "codes", .value = .{ .list = &.{ Node.num(1), Node.num(2) } } },
.{ .key = "jobs", .value = .{ .map = &.{.{ .key = "total", .value = Node.num(2) }} } },
} };
try expectRender(renderJson, .{node},
\\{
\\ "status" : "running",
\\ "running" : true,
\\ "pid" : 17474,
\\ "tag" : null,
\\ "codes" : [ 1, 2 ],
\\ "jobs" : {
\\ "total" : 2
\\ }
\\}
\\
);
}
test "XML rendering: snake_case names, nested maps, lists, nulls, escaping" {
const node: Node = .{ .map = &.{
.{ .key = "jobId", .value = Node.str("a<b&c") },
.{ .key = "summary", .value = .{ .map = &.{
.{ .key = "sampleCount", .value = Node.num(3) },
.{ .key = "gpu", .value = .null },
} } },
.{ .key = "samples", .value = .{ .list = &.{ Node.num(1), Node.num(2) } } },
.{ .key = "errors", .value = .{ .list = &.{} } },
} };
try expectRender(renderXml, .{node},
\\<?xml version="1.0" encoding="UTF-8"?>
\\<result>
\\ <job_id>a&lt;b&amp;c</job_id>
\\ <summary>
\\ <sample_count>3</sample_count>
\\ <gpu/>
\\ </summary>
\\ <samples>
\\ <sample>1</sample>
\\ <sample>2</sample>
\\ </samples>
\\ <errors/>
\\</result>
\\
);
}
test "XML job follows barn's element shape" {
const job: Job = .{
.id = "job-6d368040",
.state = .succeeded,
.command = &.{ "echo", "Hello World" },
.created_at = 1_769_046_526 * std.time.ns_per_s,
.exit_code = .{ .code = 0 },
.pid = 17486,
};
try expectRender(renderXml, .{Node{ .job = job }},
\\<?xml version="1.0" encoding="UTF-8"?>
\\<job>
\\ <id>job-6d368040</id>
\\ <state>succeeded</state>
\\ <command>
\\ <arg>echo</arg>
\\ <arg>Hello World</arg>
\\ </command>
\\ <created_at>2026-01-22T01:48:46Z</created_at>
\\ <exit_code>0</exit_code>
\\ <pid>17486</pid>
\\ <load_level>medium</load_level>
\\</job>
\\
);
}
test "errors render per format" {
try expectRender(renderError, .{ Format.human, Color{}, "boom", null }, "Error: boom\n");
try expectRender(renderError, .{ Format.json, Color{}, "boom \"x\"", "why" },
\\{
\\ "error" : true,
\\ "message" : "boom \"x\"",
\\ "cause" : "why"
\\}
\\
);
try expectRender(renderError, .{ Format.xml, Color{}, "a&b", null },
\\<?xml version="1.0" encoding="UTF-8"?>
\\<error>
\\ <message>a&amp;b</message>
\\</error>
\\
);
}
test "colour wraps only when enabled" {
var aw: Io.Writer.Allocating = .init(std.testing.allocator);
defer aw.deinit();
try aw.writer.print("{f}|{f}", .{ (Color{ .enabled = true }).wrap("hi", .green), (Color{}).wrap("hi", .green) });
try std.testing.expectEqualStrings("\x1b[32mhi\x1b[0m|hi", aw.written());
}
test "byte, age and uptime formatting" {
var b: [64]u8 = undefined;
try std.testing.expectEqualStrings("512 B", formatBytes(&b, 512));
try std.testing.expectEqualStrings("1.5 KB", formatBytes(&b, 1536));
try std.testing.expectEqualStrings("2.0 MB", formatBytes(&b, 2 * 1024 * 1024));
try std.testing.expectEqualStrings("1.25 GB", formatBytes(&b, 1342177280));
try std.testing.expectEqualStrings("3 KB", formatSize(&b, 3 * 1024 + 100));
try std.testing.expectEqualStrings("1.5 GB", formatSize(&b, 1610612736));
try std.testing.expectEqualStrings("5s ago", relativeTime(&b, 5));
try std.testing.expectEqualStrings("3m ago", relativeTime(&b, 200));
try std.testing.expectEqualStrings("2h ago", relativeTime(&b, 7300));
try std.testing.expectEqualStrings("2d ago", relativeTime(&b, 2 * 86400 + 5));
try std.testing.expectEqualStrings("in the future", relativeTime(&b, -1));
try std.testing.expectEqualStrings("42 seconds", formatUptime(&b, 42));
try std.testing.expectEqualStrings("5 minutes", formatUptime(&b, 300));
try std.testing.expectEqualStrings("2 hours, 3 minutes", formatUptime(&b, 7380));
try std.testing.expectEqualStrings("1 days, 3 hours", formatUptime(&b, 100000));
try std.testing.expectEqualStrings("5 hours old", formatAge(&b, 5 * 3600));
try std.testing.expectEqualStrings("1 day old", formatAge(&b, 30 * 3600));
try std.testing.expectEqualStrings("3 days old", formatAge(&b, 80 * 3600));
}
test "local time has the expected shape" {
var buf: [19]u8 = undefined;
const s = formatLocal(&buf, 1_769_046_526 * std.time.ns_per_s);
try std.testing.expectEqual(@as(usize, 19), s.len);
try std.testing.expect(s[4] == '-' and s[7] == '-' and s[10] == ' ' and s[13] == ':' and s[16] == ':');
try std.testing.expect(std.mem.startsWith(u8, s, "2026-01-2"));
}
+3
View File
@@ -1,4 +1,6 @@
//! zag: cross-platform job daemon (Zig port of barn).
pub const version = @import("build_options").version;
pub const duration = @import("duration.zig");
pub const timestamp = @import("timestamp.zig");
pub const state = @import("state.zig");
@@ -25,6 +27,7 @@ pub const jobjson = @import("jobjson.zig");
pub const ipc = @import("ipc.zig");
pub const service = @import("service.zig");
pub const daemon = @import("daemon.zig");
pub const output = @import("output.zig");
test {
@import("std").testing.refAllDecls(@This());