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:
1 parent
0d91b0490a
commit
bd4e585ed8
4 files changed
+620
-135
No files matched your search
@@ -47,3 +47,11 @@ Guidance for AI coding agents working in `zag`, the Zig port of the
|
||||
| `src/ipc.zig` | NDJSON-over-Unix-socket server and client |
|
||||
| `src/service.zig` | Daemon core: recovery, scheduler, IPC handlers, cleanup timer, reload |
|
||||
| `src/daemon.zig` | pid file, foreground run loop + signals, detached start, stop (TERM/KILL) |
|
||||
| `src/output.zig` | JSON/XML rendering of a value tree, human helpers (bytes, ages, local time, colour) |
|
||||
|
||||
## Build notes
|
||||
|
||||
- `build.zig` links libc (for `localtime_r`) and defaults Linux builds to `x86_64-linux-musl` so the
|
||||
binary is static and does not depend on the host's crt files (the host linker fails on newer gcc
|
||||
`.sframe` sections).
|
||||
- Width/fill on a signed integer prints a leading `+` (`{d:0>2}` of an `i64`); cast to unsigned first.
|
||||
@@ -1,156 +1,45 @@
|
||||
const std = @import("std");
|
||||
const builtin = @import("builtin");
|
||||
const zon = @import("build.zig.zon");
|
||||
|
||||
// Although this function looks imperative, it does not perform the build
|
||||
// directly and instead it mutates the build graph (`b`) that will be then
|
||||
// executed by an external runner. The functions in `std.Build` implement a DSL
|
||||
// for defining build steps and express dependencies between them, allowing the
|
||||
// build runner to parallelize the build automatically (and the cache system to
|
||||
// know when a step doesn't need to be re-run).
|
||||
pub fn build(b: *std.Build) void {
|
||||
// Standard target options allow the person running `zig build` to choose
|
||||
// what target to build for. Here we do not override the defaults, which
|
||||
// means any target is allowed, and the default is native. Other options
|
||||
// for restricting supported target set are available.
|
||||
const target = b.standardTargetOptions(.{});
|
||||
// Standard optimization options allow the person running `zig build` to select
|
||||
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not
|
||||
// set a preferred release mode, allowing the user to decide how to optimize.
|
||||
const optimize = b.standardOptimizeOption(.{});
|
||||
// It's also possible to define more custom flags to toggle optional features
|
||||
// of this build script using `b.option()`. All defined flags (including
|
||||
// target and optimize options) will be listed when running `zig build --help`
|
||||
// in this directory.
|
||||
|
||||
// This creates a module, which represents a collection of source files alongside
|
||||
// some compilation options, such as optimization mode and linked system libraries.
|
||||
// Zig modules are the preferred way of making Zig code available to consumers.
|
||||
// addModule defines a module that we intend to make available for importing
|
||||
// to our consumers. We must give it a name because a Zig package can expose
|
||||
// multiple modules and consumers will need to be able to specify which
|
||||
// module they want to access.
|
||||
const mod = b.addModule("zag", .{
|
||||
// The root source file is the "entry point" of this module. Users of
|
||||
// this module will only be able to access public declarations contained
|
||||
// in this file, which means that if you have declarations that you
|
||||
// intend to expose to consumers that were defined in other files part
|
||||
// of this module, you will have to make sure to re-export them from
|
||||
// the root file.
|
||||
.root_source_file = b.path("src/root.zig"),
|
||||
// Later on we'll use this module as the root module of a test executable
|
||||
// which requires us to specify a target.
|
||||
.target = target,
|
||||
// Linux builds default to musl: static binaries with no dependency on the host's libc.
|
||||
const target = b.standardTargetOptions(.{
|
||||
.default_target = if (builtin.os.tag == .linux) .{ .abi = .musl } else .{},
|
||||
});
|
||||
const optimize = b.standardOptimizeOption(.{});
|
||||
|
||||
const options = b.addOptions();
|
||||
options.addOption([]const u8, "version", zon.version);
|
||||
|
||||
// libc is linked for `localtime_r` (human-readable local timestamps).
|
||||
const mod = b.addModule("zag", .{
|
||||
.root_source_file = b.path("src/root.zig"),
|
||||
.target = target,
|
||||
.optimize = optimize,
|
||||
.link_libc = true,
|
||||
});
|
||||
mod.addOptions("build_options", options);
|
||||
|
||||
// Here we define an executable. An executable needs to have a root module
|
||||
// which needs to expose a `main` function. While we could add a main function
|
||||
// to the module defined above, it's sometimes preferable to split business
|
||||
// logic and the CLI into two separate modules.
|
||||
//
|
||||
// If your goal is to create a Zig library for others to use, consider if
|
||||
// it might benefit from also exposing a CLI tool. A parser library for a
|
||||
// data serialization format could also bundle a CLI syntax checker, for example.
|
||||
//
|
||||
// If instead your goal is to create an executable, consider if users might
|
||||
// be interested in also being able to embed the core functionality of your
|
||||
// program in their own executable in order to avoid the overhead involved in
|
||||
// subprocessing your CLI tool.
|
||||
//
|
||||
// If neither case applies to you, feel free to delete the declaration you
|
||||
// don't need and to put everything under a single module.
|
||||
const exe = b.addExecutable(.{
|
||||
.name = "zag",
|
||||
.root_module = b.createModule(.{
|
||||
// b.createModule defines a new module just like b.addModule but,
|
||||
// unlike b.addModule, it does not expose the module to consumers of
|
||||
// this package, which is why in this case we don't have to give it a name.
|
||||
.root_source_file = b.path("src/main.zig"),
|
||||
// Target and optimization levels must be explicitly wired in when
|
||||
// defining an executable or library (in the root module), and you
|
||||
// can also hardcode a specific target for an executable or library
|
||||
// definition if desireable (e.g. firmware for embedded devices).
|
||||
.target = target,
|
||||
.optimize = optimize,
|
||||
// List of modules available for import in source files part of the
|
||||
// root module.
|
||||
.imports = &.{
|
||||
// Here "zag" is the name you will use in your source code to
|
||||
// import this module (e.g. `@import("zag")`). The name is
|
||||
// repeated because you are allowed to rename your imports, which
|
||||
// can be extremely useful in case of collisions (which can happen
|
||||
// importing modules from different packages).
|
||||
.{ .name = "zag", .module = mod },
|
||||
},
|
||||
.link_libc = true,
|
||||
.imports = &.{.{ .name = "zag", .module = mod }},
|
||||
}),
|
||||
});
|
||||
|
||||
// This declares intent for the executable to be installed into the
|
||||
// install prefix when running `zig build` (i.e. when executing the default
|
||||
// step). By default the install prefix is `zig-out/` but can be overridden
|
||||
// by passing `--prefix` or `-p`.
|
||||
b.installArtifact(exe);
|
||||
|
||||
// This creates a top level step. Top level steps have a name and can be
|
||||
// invoked by name when running `zig build` (e.g. `zig build run`).
|
||||
// This will evaluate the `run` step rather than the default step.
|
||||
// For a top level step to actually do something, it must depend on other
|
||||
// steps (e.g. a Run step, as we will see in a moment).
|
||||
const run_step = b.step("run", "Run the app");
|
||||
|
||||
// This creates a RunArtifact step in the build graph. A RunArtifact step
|
||||
// invokes an executable compiled by Zig. Steps will only be executed by the
|
||||
// runner if invoked directly by the user (in the case of top level steps)
|
||||
// or if another step depends on it, so it's up to you to define when and
|
||||
// how this Run step will be executed. In our case we want to run it when
|
||||
// the user runs `zig build run`, so we create a dependency link.
|
||||
const run_step = b.step("run", "Run zag");
|
||||
const run_cmd = b.addRunArtifact(exe);
|
||||
run_step.dependOn(&run_cmd.step);
|
||||
|
||||
// By making the run step depend on the default step, it will be run from the
|
||||
// installation directory rather than directly from within the cache directory.
|
||||
run_cmd.step.dependOn(b.getInstallStep());
|
||||
if (b.args) |args| run_cmd.addArgs(args);
|
||||
|
||||
// This allows the user to pass arguments to the application in the build
|
||||
// command itself, like this: `zig build run -- arg1 arg2 etc`
|
||||
if (b.args) |args| {
|
||||
run_cmd.addArgs(args);
|
||||
}
|
||||
|
||||
// Creates an executable that will run `test` blocks from the provided module.
|
||||
// Here `mod` needs to define a target, which is why earlier we made sure to
|
||||
// set the releative field.
|
||||
const mod_tests = b.addTest(.{
|
||||
.root_module = mod,
|
||||
});
|
||||
|
||||
// A run step that will run the test executable.
|
||||
const run_mod_tests = b.addRunArtifact(mod_tests);
|
||||
|
||||
// Creates an executable that will run `test` blocks from the executable's
|
||||
// root module. Note that test executables only test one module at a time,
|
||||
// hence why we have to create two separate ones.
|
||||
const exe_tests = b.addTest(.{
|
||||
.root_module = exe.root_module,
|
||||
});
|
||||
|
||||
// A run step that will run the second test executable.
|
||||
const run_exe_tests = b.addRunArtifact(exe_tests);
|
||||
|
||||
// A top level step for running all tests. dependOn can be called multiple
|
||||
// times and since the two run steps do not depend on one another, this will
|
||||
// make the two of them run in parallel.
|
||||
const test_step = b.step("test", "Run tests");
|
||||
test_step.dependOn(&run_mod_tests.step);
|
||||
test_step.dependOn(&run_exe_tests.step);
|
||||
|
||||
// Just like flags, top level steps are also listed in the `--help` menu.
|
||||
//
|
||||
// The Zig build system is entirely implemented in userland, which means
|
||||
// that it cannot hook into private compiler APIs. All compilation work
|
||||
// orchestrated by the build system will result in other Zig compiler
|
||||
// subcommands being invoked with the right flags defined. You can observe
|
||||
// these invocations when one fails (or you pass a flag to increase
|
||||
// verbosity) to validate assumptions and diagnose problems.
|
||||
//
|
||||
// Lastly, the Zig build system is relatively simple and self-contained,
|
||||
// and reading its source code will allow you to master it.
|
||||
test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mod })).step);
|
||||
test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = exe.root_module })).step);
|
||||
}
|
||||
+585
@@ -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("&"),
|
||||
'<' => try out.writeAll("<"),
|
||||
'>' => try out.writeAll(">"),
|
||||
'"' => try out.writeAll("""),
|
||||
'\'' => try out.writeAll("'"),
|
||||
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<b&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&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"));
|
||||
}
|
||||
@@ -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());
|
||||
|
||||
Reference in new issue
Block a user