Files
zag/src/cli.zig
T

430 lines
19 KiB
Zig

//! The `zag` command line: argument dispatch, shared context and help text.
//! Command implementations live in `cli_jobs.zig` and `cli_admin.zig`.
const std = @import("std");
const Io = std.Io;
const Allocator = std.mem.Allocator;
const Environ = std.process.Environ;
const args_mod = @import("args.zig");
const config = @import("config.zig");
const dirs_mod = @import("dirs.zig");
const ipc = @import("ipc.zig");
const output = @import("output.zig");
const jsonpretty = @import("jsonpretty.zig");
const jobs_cmds = @import("cli_jobs.zig");
const admin_cmds = @import("cli_admin.zig");
pub const exit_ok: u8 = 0;
pub const exit_error: u8 = 1;
pub const exit_usage: u8 = 2;
pub const Context = struct {
gpa: Allocator,
arena: Allocator,
io: Io,
env: *const Environ.Map,
stdout: *Io.Writer,
stderr: *Io.Writer,
/// Path of the running binary (used to re-exec the daemon).
exe_path: []const u8,
format: output.Format = .human,
color: output.Color = .{},
parsed: args_mod.Parsed = .{},
/// Name of the subcommand being run, e.g. `status` or `service start`.
command: []const u8 = "",
config_loaded: bool = false,
config_value: config.Config = .{},
config_error: ?config.Error = null,
config_diag: config.Diagnostic = .{},
pub fn flag(self: *const Context, name: []const u8) bool {
return self.parsed.flag(name);
}
pub fn value(self: *const Context, name: []const u8) ?[]const u8 {
return self.parsed.value(name);
}
pub fn positional(self: *const Context, i: usize) ?[]const u8 {
return if (i < self.parsed.positionals.len) self.parsed.positionals[i] else null;
}
/// Prints an error in the selected output format; returns `exit_error`.
pub fn fail(self: *Context, comptime fmt: []const u8, fargs: anytype) u8 {
return self.failWithCause(null, fmt, fargs);
}
pub fn failWithCause(self: *Context, cause: ?[]const u8, comptime fmt: []const u8, fargs: anytype) u8 {
const msg = std.fmt.allocPrint(self.arena, fmt, fargs) catch "out of memory";
output.renderError(self.stderr, self.format, self.color, msg, cause) catch {};
return exit_error;
}
/// Prints an error and returns the usage exit code.
pub fn usageError(self: *Context, comptime fmt: []const u8, fargs: anytype) u8 {
_ = self.fail(fmt, fargs);
return exit_usage;
}
// -- configuration -------------------------------------------------------------
fn loadConfigOnce(self: *Context) void {
if (self.config_loaded) return;
self.config_loaded = true;
if (config.load(self.arena, self.io, self.env, .{ .explicit_path = self.value("config") }, &self.config_diag)) |c| {
self.config_value = c;
} else |err| {
self.config_error = err;
}
}
/// The effective configuration, or the error that stopped it loading.
pub fn loadConfig(self: *Context) config.Error!config.Config {
self.loadConfigOnce();
if (self.config_error) |e| return e;
return self.config_value;
}
/// Like `config`, but a broken file falls back to the defaults (client commands should keep
/// working when the config is wrong; `zag config validate` reports the problem).
pub fn configOrDefault(self: *Context) config.Config {
return self.loadConfig() catch .{};
}
pub fn describeConfigError(self: *Context) u8 {
const err = self.config_error orelse return exit_ok;
const d = self.config_diag;
if (err == error.ParseFailed) return self.fail("Failed to parse configuration file {s} at line {d}", .{ d.path, d.line });
if (d.key.len > 0) return self.fail("Invalid configuration: '{s}' in [{s}] ({s})", .{ d.key, d.section, @errorName(err) });
return self.fail("Failed to load configuration: {s}", .{@errorName(err)});
}
/// `--barn-dir`, else `storage.base_dir`.
pub fn baseDir(self: *Context) []const u8 {
if (self.value("barn-dir")) |d| return d;
return self.configOrDefault().storage.base_dir;
}
pub fn socketPath(self: *Context) []const u8 {
if (self.value("barn-dir")) |d| return std.fmt.allocPrint(self.arena, "{s}/{s}", .{ d, dirs_mod.socket_file }) catch d;
const cfg = self.configOrDefault();
return cfg.ipcSocketPath(self.arena) catch "/tmp/zag/zag.sock";
}
pub fn openDirs(self: *Context) !dirs_mod.Dirs {
return dirs_mod.Dirs.open(self.io, self.baseDir());
}
// -- service access ------------------------------------------------------------
pub const CallResult = union(enum) {
ok: std.json.Value,
/// An error was already printed; the value is the exit code.
exit: u8,
};
/// Sends a request to the daemon. Failures are printed in the selected format.
pub fn call(self: *Context, request_type: []const u8, payload_json: ?[]const u8) CallResult {
const reply = ipc.call(self.io, self.arena, self.socketPath(), request_type, payload_json) catch |err| switch (err) {
error.ServiceNotRunning => return .{ .exit = self.fail("Service not running. Start with: zag service start\nOr use --offline to run without the service.", .{}) },
error.ConnectionFailed => return .{ .exit = self.fail("Could not talk to the zag service (connection failed)", .{}) },
error.BadResponse => return .{ .exit = self.fail("The zag service sent an invalid response", .{}) },
error.OutOfMemory => return .{ .exit = self.fail("Out of memory", .{}) },
};
return switch (reply) {
.ok => |v| .{ .ok = v },
.err => |e| .{ .exit = self.remoteFail(e) },
};
}
/// Maps a daemon error to a message.
pub fn remoteFail(self: *Context, e: ipc.RemoteError) u8 {
if (std.mem.eql(u8, e.code, "NOT_FOUND") or std.mem.eql(u8, e.code, "INVALID_STATE") or std.mem.eql(u8, e.code, "INVALID_REQUEST"))
return self.fail("{s}", .{e.message});
return self.fail("IPC error: {s}", .{e.message});
}
pub fn emit(self: *Context, node: output.Node) !void {
try output.render(self.stdout, self.format, node);
}
};
// -- option tables ---------------------------------------------------------------------
const global_opts = [_]args_mod.Opt{
.{ .long = "output", .short = 'o', .takes_value = true },
.{ .long = "config", .takes_value = true },
.{ .long = "offline" },
.{ .long = "barn-dir", .takes_value = true },
.{ .long = "help", .short = 'h' },
.{ .long = "version", .short = 'V' },
};
pub const Command = struct {
name: []const u8,
/// Set for commands with subcommands (`service`, `config`).
sub: ?[]const u8 = null,
summary: []const u8,
usage: []const u8,
opts: []const args_mod.Opt = &.{},
stop_at_positional: bool = false,
run: *const fn (*Context) anyerror!u8,
};
const commands = [_]Command{
.{ .name = "run", .summary = "Start a new job", .usage = jobs_cmds.run_usage, .opts = &jobs_cmds.run_opts, .stop_at_positional = true, .run = jobs_cmds.cmdRun },
.{ .name = "status", .summary = "Show status of all jobs", .usage = jobs_cmds.status_usage, .opts = &jobs_cmds.status_opts, .run = jobs_cmds.cmdStatus },
.{ .name = "describe", .summary = "Show detailed job information", .usage = jobs_cmds.describe_usage, .opts = &jobs_cmds.describe_opts, .run = jobs_cmds.cmdDescribe },
.{ .name = "usage", .summary = "Show resource usage for a job", .usage = jobs_cmds.usage_usage, .opts = &jobs_cmds.usage_opts, .run = jobs_cmds.cmdUsage },
.{ .name = "kill", .summary = "Stop a running job", .usage = jobs_cmds.kill_usage, .opts = &jobs_cmds.kill_opts, .run = jobs_cmds.cmdKill },
.{ .name = "clean", .summary = "Remove completed jobs", .usage = jobs_cmds.clean_usage, .opts = &jobs_cmds.clean_opts, .run = jobs_cmds.cmdClean },
.{ .name = "service", .sub = "start", .summary = "Start the zag service", .usage = admin_cmds.service_start_usage, .opts = &admin_cmds.service_start_opts, .run = admin_cmds.cmdServiceStart },
.{ .name = "service", .sub = "stop", .summary = "Stop the zag service", .usage = admin_cmds.service_stop_usage, .opts = &admin_cmds.service_stop_opts, .run = admin_cmds.cmdServiceStop },
.{ .name = "service", .sub = "restart", .summary = "Restart the zag service", .usage = admin_cmds.service_restart_usage, .opts = &admin_cmds.service_restart_opts, .run = admin_cmds.cmdServiceRestart },
.{ .name = "service", .sub = "reload", .summary = "Reload configuration without stopping jobs", .usage = admin_cmds.service_reload_usage, .run = admin_cmds.cmdServiceReload },
.{ .name = "service", .sub = "status", .summary = "Show service status", .usage = admin_cmds.service_status_usage, .run = admin_cmds.cmdServiceStatus },
.{ .name = "service", .sub = "logs", .summary = "Show service logs", .usage = admin_cmds.service_logs_usage, .opts = &admin_cmds.service_logs_opts, .run = admin_cmds.cmdServiceLogs },
.{ .name = "service", .sub = "install", .summary = "Install zag as a system service", .usage = admin_cmds.service_install_usage, .opts = &admin_cmds.service_install_opts, .run = admin_cmds.cmdServiceInstall },
.{ .name = "service", .sub = "uninstall", .summary = "Remove the system service", .usage = admin_cmds.service_uninstall_usage, .run = admin_cmds.cmdServiceUninstall },
.{ .name = "config", .sub = "show", .summary = "Show effective configuration", .usage = admin_cmds.config_show_usage, .opts = &admin_cmds.config_show_opts, .run = admin_cmds.cmdConfigShow },
.{ .name = "config", .sub = "validate", .summary = "Validate a configuration file", .usage = admin_cmds.config_validate_usage, .opts = &admin_cmds.config_validate_opts, .run = admin_cmds.cmdConfigValidate },
.{ .name = "config", .sub = "init", .summary = "Create a default configuration file", .usage = admin_cmds.config_init_usage, .opts = &admin_cmds.config_init_opts, .run = admin_cmds.cmdConfigInit },
.{ .name = "config", .sub = "install", .summary = "Install default configuration files", .usage = admin_cmds.config_install_usage, .opts = &admin_cmds.config_install_opts, .run = admin_cmds.cmdConfigInstall },
.{ .name = "autocompletion", .summary = "Generate shell autocompletion scripts", .usage = admin_cmds.autocompletion_usage, .opts = &admin_cmds.autocompletion_opts, .run = admin_cmds.cmdAutocompletion },
};
const root_help =
\\zag - cross-platform job daemon for media processing
\\
\\Usage: zag [options] <command> [command options]
\\
\\Commands:
\\ run Start a new job
\\ status Show status of all jobs
\\ describe Show detailed job information
\\ usage Show resource usage for a job
\\ kill Stop a running job
\\ clean Remove completed jobs
\\ service Manage the zag service (start|stop|restart|reload|status|logs|install|uninstall)
\\ config Configuration management (show|validate|init|install)
\\ autocompletion Generate shell autocompletion scripts
\\
\\Global options:
\\ -o, --output <format> Output format: human, json, xml (default: human)
\\ --config <file> Path to a configuration file
\\ --offline Run without the service (same code, in this process)
\\ --barn-dir <dir> Data directory (overrides storage.base_dir)
\\ -h, --help Show help (also per command)
\\ -V, --version Show the version
\\
;
const service_help =
\\Usage: zag service <start|stop|restart|reload|status|logs|install|uninstall>
\\
\\ start Start the zag service
\\ stop Stop the zag service
\\ restart Restart the zag service
\\ reload Reload configuration without stopping jobs
\\ status Show service status
\\ logs Show service logs
\\ install Install zag as a system service (systemd / launchd)
\\ uninstall Remove the system service
\\
;
const config_help =
\\Usage: zag config <show|validate|init|install>
\\
\\ show Show effective configuration
\\ validate Validate a configuration file
\\ init Create a default configuration file
\\ install Install default configuration files
\\
;
/// Number of leading tokens that are global options (and their values).
fn leadingOptionCount(argv: []const []const u8) usize {
var i: usize = 0;
while (i < argv.len and argv[i].len > 1 and argv[i][0] == '-') : (i += 1) {
const a = argv[i];
if (std.mem.eql(u8, a, "--")) break;
var takes_value = false;
if (std.mem.startsWith(u8, a, "--")) {
if (std.mem.indexOfScalar(u8, a, '=') == null) {
for (global_opts) |o| if (std.mem.eql(u8, o.long, a[2..])) {
takes_value = o.takes_value;
};
}
} else if (a.len == 2) {
for (global_opts) |o| if (o.short != null and o.short.? == a[1]) {
takes_value = o.takes_value;
};
}
if (takes_value) i += 1;
}
return @min(i, argv.len);
}
fn find(name: []const u8, sub: ?[]const u8) ?*const Command {
for (&commands) |*c| {
if (!std.mem.eql(u8, c.name, name)) continue;
if (c.sub == null and sub == null) return c;
if (c.sub != null and sub != null and std.mem.eql(u8, c.sub.?, sub.?)) return c;
}
return null;
}
fn hasSubcommands(name: []const u8) bool {
return std.mem.eql(u8, name, "service") or std.mem.eql(u8, name, "config");
}
/// Runs the CLI and returns the process exit code.
pub fn run(
gpa: Allocator,
io: Io,
env: *const Environ.Map,
stdout: *Io.Writer,
stderr: *Io.Writer,
exe_path: []const u8,
argv: []const []const u8,
stdout_is_tty: bool,
) u8 {
var arena_state = std.heap.ArenaAllocator.init(gpa);
defer arena_state.deinit();
const arena = arena_state.allocator();
var ctx: Context = .{
.gpa = gpa,
.arena = arena,
.io = io,
.env = env,
.stdout = stdout,
.stderr = stderr,
.exe_path = exe_path,
};
return dispatch(&ctx, argv, stdout_is_tty) catch |err| {
_ = ctx.fail("Unexpected error: {s}", .{@errorName(err)});
return exit_error;
};
}
fn dispatch(ctx: *Context, argv: []const []const u8, stdout_is_tty: bool) !u8 {
// Global options may precede the command: `zag -o json status`.
const cmd_index = leadingOptionCount(argv);
const prefix = argv[0..@min(cmd_index, argv.len)];
const rest = argv[@min(cmd_index, argv.len)..];
var diag: args_mod.Diagnostic = .{};
const pre = args_mod.parse(ctx.arena, prefix, &global_opts, .{}, &diag) catch |err| return ctx.usageError("{s}: {s}", .{ @errorName(err), diag.token });
ctx.parsed = pre;
if (rest.len == 0) {
if (pre.flag("version")) return printVersion(ctx);
try ctx.stdout.writeAll(root_help);
return exit_ok;
}
if (pre.flag("version")) return printVersion(ctx);
const name = rest[0];
var sub: ?[]const u8 = null;
var cmd_args = rest[1..];
if (std.mem.eql(u8, name, "help")) {
try ctx.stdout.writeAll(root_help);
return exit_ok;
}
if (hasSubcommands(name)) {
const help_text = if (std.mem.eql(u8, name, "service")) service_help else config_help;
if (cmd_args.len == 0 or std.mem.eql(u8, cmd_args[0], "--help") or std.mem.eql(u8, cmd_args[0], "-h")) {
try ctx.stdout.writeAll(help_text);
return exit_ok;
}
sub = cmd_args[0];
cmd_args = cmd_args[1..];
}
const cmd = find(name, sub) orelse {
if (sub) |s| return ctx.usageError("Unknown subcommand '{s}' for '{s}'\n{s}", .{ s, name, if (std.mem.eql(u8, name, "service")) service_help else config_help });
return ctx.usageError("Unknown command '{s}'. Run 'zag --help' for usage.", .{name});
};
ctx.command = if (cmd.sub) |s| try std.fmt.allocPrint(ctx.arena, "{s} {s}", .{ cmd.name, s }) else cmd.name;
const specs = try std.mem.concat(ctx.arena, args_mod.Opt, &.{ &global_opts, cmd.opts });
const own = args_mod.parse(ctx.arena, cmd_args, specs, .{ .stop_at_positional = cmd.stop_at_positional }, &diag) catch |err| {
const what = switch (err) {
error.UnknownOption => "Unknown option",
error.MissingValue => "Missing value for option",
error.UnexpectedValue => "Option does not take a value",
error.OutOfMemory => return error.OutOfMemory,
};
return ctx.usageError("{s}: {s}\nRun 'zag {s} --help' for usage.", .{ what, diag.token, ctx.command });
};
ctx.parsed = try pre.merge(ctx.arena, own);
if (ctx.flag("version")) return printVersion(ctx);
if (ctx.flag("help")) {
try ctx.stdout.writeAll(cmd.usage);
return exit_ok;
}
if (ctx.value("output")) |o| {
ctx.format = output.Format.parse(o) orelse return ctx.usageError("Invalid output format '{s}' (expected human, json or xml)", .{o});
}
ctx.color = .{ .enabled = stdout_is_tty and ctx.format == .human and ctx.env.get("NO_COLOR") == null };
const code = try cmd.run(ctx);
return code;
}
fn printVersion(ctx: *Context) !u8 {
try ctx.stdout.print("zag {s}\n", .{@import("root.zig").version});
return exit_ok;
}
// -- tests -----------------------------------------------------------------------------
pub const TestRun = struct { code: u8, out: []const u8, err: []const u8 };
/// Runs the CLI in-process with captured output (for tests). `env` may be null.
pub fn runCaptured(arena: Allocator, argv: []const []const u8, env_in: ?*const Environ.Map) !TestRun {
var out: Io.Writer.Allocating = .init(arena);
var err: Io.Writer.Allocating = .init(arena);
var empty = Environ.Map.init(std.testing.allocator);
defer empty.deinit();
const code = run(std.testing.allocator, std.testing.io, env_in orelse &empty, &out.writer, &err.writer, "zag-test", argv, false);
return .{ .code = code, .out = out.written(), .err = err.written() };
}
test "no arguments prints help; --version prints the version" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const help = try runCaptured(arena.allocator(), &.{}, null);
try std.testing.expectEqual(exit_ok, help.code);
try std.testing.expect(std.mem.indexOf(u8, help.out, "Usage: zag") != null);
const v = try runCaptured(arena.allocator(), &.{"--version"}, null);
try std.testing.expectEqual(exit_ok, v.code);
try std.testing.expect(std.mem.startsWith(u8, v.out, "zag "));
}
test "usage errors exit with 2" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
try std.testing.expectEqual(exit_usage, (try runCaptured(a, &.{"frobnicate"}, null)).code);
try std.testing.expectEqual(exit_usage, (try runCaptured(a, &.{ "status", "--bogus" }, null)).code);
try std.testing.expectEqual(exit_usage, (try runCaptured(a, &.{ "status", "-o", "yaml" }, null)).code);
try std.testing.expectEqual(exit_usage, (try runCaptured(a, &.{ "service", "explode" }, null)).code);
}
test "per-command help" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const r = try runCaptured(arena.allocator(), &.{ "run", "--help" }, null);
try std.testing.expectEqual(exit_ok, r.code);
try std.testing.expect(std.mem.indexOf(u8, r.out, "--load-level") != null);
const s = try runCaptured(arena.allocator(), &.{ "service", "--help" }, null);
try std.testing.expect(std.mem.indexOf(u8, s.out, "restart") != null);
}