diff --git a/build.zig.zon b/build.zig.zon index 08e732e..78ebf3f 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -5,8 +5,8 @@ .minimum_zig_version = "0.17.1", .dependencies = .{ .zig_common = .{ - .url = "git+https://github.com/stackhands/zig-common?ref=v0.12.0#556a92c8f469449e944175b7dd2993c6037573ed", - .hash = "zig_common-0.12.0-kBaPeZBnBQDdEF6SU_k7R0FFAtuWaDkgydjuzD9sl8_u", + .url = "git+https://github.com/stackhands/zig-common?ref=v0.13.0#2eea6b7fe8f328e56c63647b9523c4a7fe80b56a", + .hash = "zig_common-0.13.0-kBaPeWL0CABmnAAv_SexG9PtG5cP3PjKE6cX7KqHJELu", }, }, .paths = .{ diff --git a/src/cli_parse.zig b/src/cli_parse.zig new file mode 100644 index 0000000..9029750 --- /dev/null +++ b/src/cli_parse.zig @@ -0,0 +1,153 @@ +//! CommandSpec scanning for the subcommands. Diagnostics stay the lines each command already prints. +const std = @import("std"); +const common = @import("zig_common"); + +const argparse = common.argparse; +const cli = common.cli; +const Allocator = std.mem.Allocator; +const tool = "eb-keep-logs"; + +pub const ValidationResult = argparse.ValidationResult; +pub const ValidatorFn = argparse.ValidatorFn; + +/// Exact names, no short clusters, any next token is a value, first scan error wins. +fn policy(unknown: argparse.UnknownMode, special: argparse.SpecialActionMode) argparse.Policy { + return .{ + .allow_abbrev = false, + .unknown = unknown, + .double_dash = .ignore, + .negative_numbers = .any, + .short_clusters = false, + .special_action = special, + .flag_explicit_as_unknown = true, + .unknown_before_required = true, + .fail_fast = true, + }; +} +pub const exact = policy(.collect, .immediate_exit); +pub const prescan = policy(.collect, .prescan); +pub const as_positional = policy(.positional, .immediate_exit); + +pub const Extra = enum { same, static, failures }; +pub const Missing = struct { name: []const u8, msg: []const u8 }; +pub const Build = struct { + prog: []const u8, + help: []const u8 = "", + policy: argparse.Policy = exact, + bare_unknown: bool = false, + extra: Extra = .same, + extra_msg: []const u8 = "", + mutex: ?[]const u8 = null, + missing: []const Missing = &.{}, + options: []const argparse.OptionSpec = &.{}, + positionals: []const argparse.PositionalSpec = &.{}, + mutually_exclusive: []const argparse.MutexGroup = &.{}, +}; +pub const Result = union(enum) { ok: argparse.Parsed, help }; +pub const Cmd = struct { + // spec outlives every Parsed this command returns. Parsed keeps the pointer. + spec: argparse.CommandSpec, + b: Build, + + pub fn take(self: *const Cmd, gpa: Allocator, args: anytype) argparse.Parsed { + return switch (drive(gpa, &self.spec, args, &self.b)) { + .ok => |parsed| parsed, + .help => cli.die(tool, "internal parse error", .{}), + }; + } + pub fn takeOrHelp(self: *const Cmd, gpa: Allocator, args: anytype) Result { + return drive(gpa, &self.spec, args, &self.b); + } +}; + +pub fn make(b: Build) Cmd { + return .{ + .b = b, + .spec = .{ + .prog = b.prog, + .usage = "", + .help = b.help, + .add_help = b.help.len != 0, + .policy = b.policy, + .options = b.options, + .positionals = b.positionals, + .mutually_exclusive = b.mutually_exclusive, + }, + }; +} + +pub fn flag(comptime name: []const u8) argparse.OptionSpec { + return .{ .name = name }; +} +pub fn value(comptime name: []const u8) argparse.OptionSpec { + return .{ .name = name, .kind = .value }; +} +pub fn req(comptime n: []const u8) argparse.OptionSpec { + return .{ .name = n, .kind = .value, .required = true, .allow_empty = false, .allow_dash_value = false }; +} +pub fn strict(comptime n: []const u8) argparse.OptionSpec { + return .{ .name = n, .kind = .value, .allow_empty = false, .allow_dash_value = false }; +} +pub fn filled(comptime n: []const u8) argparse.OptionSpec { + return .{ .name = n, .kind = .value, .allow_empty = false }; +} +pub fn append(comptime n: []const u8) argparse.OptionSpec { + return .{ .name = n, .kind = .append, .allow_empty = false, .allow_dash_value = false }; +} +pub fn checked(spec: argparse.OptionSpec, validate: ValidatorFn) argparse.OptionSpec { + var out = spec; + out.validate = validate; + return out; +} +pub fn one(comptime n: []const u8, skip_empty: bool) argparse.PositionalSpec { + return .{ .name = n, .arity = .required_one, .ignore_empty = skip_empty }; +} +pub fn optional(comptime n: []const u8) argparse.PositionalSpec { + return .{ .name = n, .arity = .optional_one }; +} +pub fn zeroOrMore(comptime n: []const u8) argparse.PositionalSpec { + return .{ .name = n, .arity = .zero_or_more }; +} +pub fn oneOrMore(comptime n: []const u8) argparse.PositionalSpec { + return .{ .name = n, .arity = .one_or_more }; +} + +fn say(msg: []const u8) noreturn { + cli.die(tool, "{s}", .{msg}); +} +fn sayUnknown(spec: *const Build, tok: []const u8) noreturn { + if (spec.bare_unknown) cli.die(tool, "unknown option {s}", .{tok}); + cli.die(tool, "{s} does not know '{s}'", .{ spec.prog, tok }); +} +fn missingMsg(spec: *const Build, name: []const u8) noreturn { + for (spec.missing) |row| if (std.mem.eql(u8, row.name, name)) say(row.msg); + cli.die(tool, "{s} needs --{s}", .{ spec.prog, name }); +} +fn refuse(err: argparse.UsageError, spec: *const Build) noreturn { + switch (err.kind) { + .unknown_option => |tok| sayUnknown(spec, tok), + .extra_positional => |tok| switch (spec.extra) { + .same => sayUnknown(spec, tok), + .static => say(spec.extra_msg), + .failures => cli.die(tool, "failures takes no positional argument, got '{s}'", .{tok}), + }, + .missing_value, .missing_required => |name| missingMsg(spec, name), + .invalid_value => |bad| missingMsg(spec, bad.name), + .mutually_exclusive => say(spec.mutex orelse "internal parse error"), + else => cli.die(tool, "internal parse error", .{}), + } +} +fn drive(gpa: Allocator, spec: *const argparse.CommandSpec, args: anytype, build: *const Build) Result { + const argv = gpa.alloc([]const u8, args.len) catch cli.die(tool, "out of memory", .{}); + defer gpa.free(argv); + for (args, 0..) |arg, i| argv[i] = arg; + const outcome = argparse.parse(gpa, spec, argv) catch cli.die(tool, "out of memory", .{}); + switch (outcome) { + .ok => |parsed| return .{ .ok = parsed }, + .action_done => |done| { + cli.put(1, done.stdout_text); + return .help; + }, + .usage_error => |err| refuse(err, build), + } +} diff --git a/src/lifecycle.zig b/src/lifecycle.zig index 87b948e..c77b27e 100644 --- a/src/lifecycle.zig +++ b/src/lifecycle.zig @@ -12,6 +12,7 @@ const fsx = common.fsx; const atomic = common.atomic; const proc = common.proc; const cli = common.cli; +const cli_parse = @import("cli_parse.zig"); const localtime = @import("localtime.zig"); const Allocator = std.mem.Allocator; @@ -591,23 +592,29 @@ fn formatUtcDate(arena: Allocator, epoch_sec: i64) Allocator.Error![]const u8 { return try arena.print("{d}-{d:0>2}-{d:0>2}", .{ d.year, d.month, d.day }); } -fn optionValue( - args: []const []const u8, - i: *usize, - arg: []const u8, - comptime option: []const u8, - comptime message: []const u8, -) []const u8 { - const value = if (std.mem.startsWith(u8, arg, option ++ "=")) - arg[option.len + 1 ..] - else blk: { - i.* += 1; - if (i.* >= args.len) die(message, .{}); - break :blk args[i.*]; - }; - if (value.len == 0 or value[0] == '-') die(message, .{}); - return value; -} +const lifecycle_cli = cli_parse.make(.{ + .prog = "lifecycle", + .options = &.{ + cli_parse.req("policy"), + cli_parse.strict("modulerc-out"), + cli_parse.append("easyconfigs"), + cli_parse.append("easystack"), + cli_parse.strict("eb-stack"), + cli_parse.strict("rebuild-set"), + cli_parse.strict("now"), + cli_parse.flag("json"), + }, + .positionals = &.{cli_parse.one("FILE", true)}, + .missing = &.{ + .{ .name = "modulerc-out", .msg = "--modulerc-out needs a path" }, + .{ .name = "easyconfigs", .msg = "--easyconfigs needs a directory" }, + .{ .name = "easystack", .msg = "--easystack needs a file" }, + .{ .name = "eb-stack", .msg = "--eb-stack needs a path" }, + .{ .name = "rebuild-set", .msg = "--rebuild-set needs a file" }, + .{ .name = "now", .msg = "--now needs an epoch" }, + .{ .name = "FILE", .msg = "lifecycle needs a usage JSON file" }, + }, +}); const RebuildInfo = struct { changed: std.StringHashMapUnmanaged(void) = .empty, @@ -1037,60 +1044,26 @@ pub fn cmdLifecycle( envp: proc.Envp, args: []const []const u8, ) u8 { - var policy_path: []const u8 = ""; - var modulerc_out: ?[]const u8 = null; - var eb_stack_opt: ?[]const u8 = null; - var rebuild_set_opt: ?[]const u8 = null; - var now_opt: ?[]const u8 = null; - var json_out = false; - var usage_path: []const u8 = ""; - - var easyconfigs: std.ArrayList([]const u8) = .empty; - defer easyconfigs.deinit(gpa); - var easystacks: std.ArrayList([]const u8) = .empty; - defer easystacks.deinit(gpa); - - var i: usize = 0; - while (i < args.len) : (i += 1) { - const arg = args[i]; - if (std.mem.eql(u8, arg, "--policy") or std.mem.startsWith(u8, arg, "--policy=")) { - policy_path = optionValue(args, &i, arg, "--policy", "lifecycle needs --policy"); - } else if (std.mem.eql(u8, arg, "--modulerc-out") or std.mem.startsWith(u8, arg, "--modulerc-out=")) { - modulerc_out = optionValue(args, &i, arg, "--modulerc-out", "--modulerc-out needs a path"); - } else if (std.mem.eql(u8, arg, "--easyconfigs") or std.mem.startsWith(u8, arg, "--easyconfigs=")) { - const v = optionValue(args, &i, arg, "--easyconfigs", "--easyconfigs needs a directory"); - easyconfigs.append(gpa, v) catch die("out of memory", .{}); - } else if (std.mem.eql(u8, arg, "--easystack") or std.mem.startsWith(u8, arg, "--easystack=")) { - const v = optionValue(args, &i, arg, "--easystack", "--easystack needs a file"); - easystacks.append(gpa, v) catch die("out of memory", .{}); - } else if (std.mem.eql(u8, arg, "--eb-stack") or std.mem.startsWith(u8, arg, "--eb-stack=")) { - eb_stack_opt = optionValue(args, &i, arg, "--eb-stack", "--eb-stack needs a path"); - } else if (std.mem.eql(u8, arg, "--rebuild-set") or std.mem.startsWith(u8, arg, "--rebuild-set=")) { - rebuild_set_opt = optionValue(args, &i, arg, "--rebuild-set", "--rebuild-set needs a file"); - } else if (std.mem.eql(u8, arg, "--now") or std.mem.startsWith(u8, arg, "--now=")) { - now_opt = optionValue(args, &i, arg, "--now", "--now needs an epoch"); - } else if (std.mem.eql(u8, arg, "--json")) { - json_out = true; - } else if (arg.len > 0 and arg[0] == '-') { - die("lifecycle does not know '{s}'", .{arg}); - } else if (usage_path.len == 0) { - usage_path = arg; - } else { - die("lifecycle does not know '{s}'", .{arg}); - } - } - - if (policy_path.len == 0) die("lifecycle needs --policy", .{}); - if (usage_path.len == 0) die("lifecycle needs a usage JSON file", .{}); - if (rebuild_set_opt != null and easyconfigs.items.len > 0) + var parsed = lifecycle_cli.take(gpa, args); + defer parsed.deinit(gpa); + const policy_path = parsed.value("policy").?; + const modulerc_out = parsed.value("modulerc-out"); + const eb_stack_opt = parsed.value("eb-stack"); + const rebuild_set_opt = parsed.value("rebuild-set"); + const now_opt = parsed.value("now"); + const json_out = parsed.seen("json"); + const usage_path = parsed.positional(0).?; + const easyconfigs = parsed.values("easyconfigs"); + const easystacks = parsed.values("easystack"); + if (rebuild_set_opt != null and easyconfigs.len > 0) die("lifecycle takes --easyconfigs or --rebuild-set, not both", .{}); - if (easystacks.items.len > 0 and easyconfigs.items.len == 0) + if (easystacks.len > 0 and easyconfigs.len == 0) die("--easystack requires --easyconfigs", .{}); if (modulerc_out) |out_p| { if (std.mem.indexOfScalar(u8, out_p, '\n') != null or std.mem.indexOfScalar(u8, out_p, 0) != null) die("--modulerc-out must not contain a newline", .{}); } - for (easyconfigs.items) |ec_dir| { + for (easyconfigs) |ec_dir| { const d = fsx.openDir(fsx.cwd, ec_dir, true) catch die("easyconfigs directory {s} is not a directory", .{ec_dir}); sys.close(d); @@ -1201,7 +1174,7 @@ pub fn cmdLifecycle( defer gpa.free(rs_text); rebuild_info = parseRebuildSetJson(arena, rs_path, rs_text); dependents_checked = true; - } else if (candidates.items.len > 0 and easyconfigs.items.len > 0) { + } else if (candidates.items.len > 0 and easyconfigs.len > 0) { const path_env = env.get("PATH") orelse ""; const eb_stack_exe = resolveExecutable(gpa, eb_stack_opt, path_env); defer gpa.free(eb_stack_exe); @@ -1211,8 +1184,8 @@ pub fn cmdLifecycle( env, envp, eb_stack_exe, - easyconfigs.items, - easystacks.items, + easyconfigs, + easystacks, usage_in.packages, candidates.items, ); diff --git a/src/loads.zig b/src/loads.zig index 7003f34..7c59ec1 100644 --- a/src/loads.zig +++ b/src/loads.zig @@ -9,6 +9,7 @@ const common = @import("zig_common"); const sys = common.sys; const fsx = common.fsx; const cli = common.cli; +const cli_parse = @import("cli_parse.zig"); const Allocator = std.mem.Allocator; const tool = "eb-keep-logs"; @@ -127,36 +128,22 @@ fn readLog(gpa: Allocator, path: []const u8) ?[]u8 { }; } +const loads_cli = cli_parse.make(.{ + .prog = "loads", + .options = &.{ cli_parse.req("module"), cli_parse.flag("json") }, + .positionals = &.{cli_parse.one("FILE", true)}, + .missing = &.{ + .{ .name = "FILE", .msg = "loads needs a log file" }, + }, +}); + /// `loads --module NAME [--json] FILE`. pub fn cmdLoads(gpa: Allocator, args: []const []const u8) u8 { - var module: []const u8 = ""; - var json_out = false; - var path: []const u8 = ""; - var i: usize = 0; - while (i < args.len) : (i += 1) { - const a = args[i]; - if (std.mem.eql(u8, a, "--json")) { - json_out = true; - } else if (std.mem.eql(u8, a, "--module") or std.mem.startsWith(u8, a, "--module=")) { - const v = if (std.mem.startsWith(u8, a, "--module=")) - a["--module=".len..] - else blk: { - i += 1; - if (i >= args.len) die("loads needs --module", .{}); - break :blk args[i]; - }; - if (v.len == 0 or v[0] == '-') die("loads needs --module", .{}); - module = v; - } else if (a.len > 0 and a[0] == '-') { - die("loads does not know '{s}'", .{a}); - } else if (path.len == 0) { - path = a; - } else { - die("loads does not know '{s}'", .{a}); - } - } - if (module.len == 0) die("loads needs --module", .{}); - if (path.len == 0) die("loads needs a log file", .{}); + var parsed = loads_cli.take(gpa, args); + defer parsed.deinit(gpa); + const module = parsed.value("module").?; + const json_out = parsed.seen("json"); + const path = parsed.positional(0).?; const text = readLog(gpa, path) orelse return 2; defer gpa.free(text); const body = if (json_out) blk: { diff --git a/src/main.zig b/src/main.zig index 8bdbc66..7108189 100644 --- a/src/main.zig +++ b/src/main.zig @@ -25,6 +25,7 @@ const syslog = common.syslog; /// journald, and the name in the structured-data identifier. const syslog_identity: syslog.Identity = .{ .app = "eb-keep-logs", .sd_name = "ebKeepLogs" }; const metrics = @import("metrics.zig"); +const cli_parse = @import("cli_parse.zig"); const Allocator = std.mem.Allocator; const tool = "eb-keep-logs"; @@ -747,42 +748,35 @@ const KeepStats = struct { } }; +const failed_cli = cli_parse.make(.{ + .prog = "failed", + .policy = cli_parse.as_positional, + .options = &.{ cli_parse.value("syslog"), cli_parse.value("metrics-file") }, + .positionals = &.{cli_parse.zeroOrMore("ARG")}, + .missing = &.{ + .{ .name = "syslog", .msg = "--syslog needs a target" }, + .{ .name = "metrics-file", .msg = "--metrics-file needs a path" }, + }, +}); + fn cmdFailed(c: Ctx, args: []const [:0]const u8) u8 { - var pos: std.ArrayList([]const u8) = .empty; - defer pos.deinit(c.gpa); - var syslog_v: ?[]const u8 = null; - var metrics_file: ?[]const u8 = null; - var i: usize = 0; - while (i < args.len) : (i += 1) { - const a = args[i]; - if (std.mem.eql(u8, a, "--syslog")) { - if (i + 1 >= args.len) die("--syslog needs a target", .{}); - i += 1; - syslog_v = args[i]; - } else if (std.mem.startsWith(u8, a, "--syslog=")) { - syslog_v = a["--syslog=".len..]; - } else if (std.mem.eql(u8, a, "--metrics-file")) { - if (i + 1 >= args.len) die("--metrics-file needs a path", .{}); - i += 1; - metrics_file = args[i]; - } else if (std.mem.startsWith(u8, a, "--metrics-file=")) { - metrics_file = a["--metrics-file=".len..]; - } else { - pos.append(c.gpa, a) catch return 2; - } - } - if (pos.items.len < 3) die("failed needs STATUS NAME LOGDIR [TMP_LOGDIR]", .{}); - const status = pos.items[0]; - const name = pos.items[1]; - const explicit: ?[]const u8 = if (pos.items.len >= 4 and pos.items[3].len > 0) pos.items[3] else null; + var parsed = failed_cli.take(c.gpa, args); + defer parsed.deinit(c.gpa); + const pos = parsed.positionals; + const syslog_v = parsed.value("syslog"); + const metrics_file = parsed.value("metrics-file"); + if (pos.len < 3) die("failed needs STATUS NAME LOGDIR [TMP_LOGDIR]", .{}); + const status = pos[0]; + const name = pos[1]; + const explicit: ?[]const u8 = if (pos.len >= 4 and pos[3].len > 0) pos[3] else null; if (!allDigits(status)) die("STATUS must be a number, not '{s}'", .{status}); - const logdir = fsx.openDir(fsx.cwd, pos.items[2], true) catch die("LOGDIR {s} is not a directory", .{pos.items[2]}); + const logdir = fsx.openDir(fsx.cwd, pos[2], true) catch die("LOGDIR {s} is not a directory", .{pos[2]}); defer sys.close(logdir); if (metrics_file) |p| if (p.len == 0) die("--metrics-file needs a path", .{}); var kept: KeepStats = .{}; defer updateMetrics(c, metrics_file, kept.logs, kept.bytes, false); const syslog_target = resolveSyslog(c, syslog_v); - const logdir_s = joinable(pos.items[2]); + const logdir_s = joinable(pos[2]); if (std.mem.indexOfNone(u8, status, "0") == null) return 0; closeBuildLogs(c, logdir, logdir_s, name, explicit); @@ -1260,73 +1254,51 @@ fn readLinkAt(dir: fsx.fd_t, name: []const u8, out: *[sys.path_max]u8) sys.Error return out[0..n]; } +const rotate_cli = cli_parse.make(.{ + .prog = "rotate", + .bare_unknown = true, + .extra = .static, + .extra_msg = "rotate takes one ROOT", + .options = &.{ + cli_parse.value("lock-timeout"), + cli_parse.value("syslog"), + cli_parse.value("metrics-file"), + cli_parse.flag("dry-run"), + cli_parse.value("compress-after"), + cli_parse.value("delete-after"), + }, + .positionals = &.{cli_parse.optional("ROOT")}, + .missing = &.{ + .{ .name = "lock-timeout", .msg = "--lock-timeout needs a number of seconds" }, + .{ .name = "syslog", .msg = "--syslog needs a target" }, + .{ .name = "metrics-file", .msg = "--metrics-file needs a path" }, + .{ .name = "compress-after", .msg = "--compress-after needs a number of days" }, + .{ .name = "delete-after", .msg = "--delete-after needs a number of days" }, + }, +}); + fn cmdRotate(c: Ctx, args: []const [:0]const u8) u8 { - var root_s: ?[]const u8 = null; - var compress_v: ?[]const u8 = null; - var delete_v: ?[]const u8 = null; - var lock_v: []const u8 = ""; - var syslog_v: ?[]const u8 = null; - var metrics_file: ?[]const u8 = null; - var dry_run = false; - var have_compress = false; - var have_delete = false; - var i: usize = 0; - while (i < args.len) : (i += 1) { - const a = args[i]; - if (std.mem.eql(u8, a, "--lock-timeout")) { - if (i + 1 >= args.len) die("--lock-timeout needs a number of seconds", .{}); - i += 1; - lock_v = args[i]; - } else if (std.mem.startsWith(u8, a, "--lock-timeout=")) { - lock_v = a["--lock-timeout=".len..]; - } else if (std.mem.eql(u8, a, "--syslog")) { - if (i + 1 >= args.len) die("--syslog needs a target", .{}); - i += 1; - syslog_v = args[i]; - } else if (std.mem.startsWith(u8, a, "--syslog=")) { - syslog_v = a["--syslog=".len..]; - } else if (std.mem.eql(u8, a, "--metrics-file")) { - if (i + 1 >= args.len) die("--metrics-file needs a path", .{}); - i += 1; - metrics_file = args[i]; - } else if (std.mem.startsWith(u8, a, "--metrics-file=")) { - metrics_file = a["--metrics-file=".len..]; - } else if (std.mem.eql(u8, a, "--dry-run")) { - dry_run = true; - } else if (std.mem.eql(u8, a, "--compress-after") or std.mem.eql(u8, a, "--delete-after")) { - const v: ?[]const u8 = if (i + 1 < args.len) args[i + 1] else null; - if (v == null) die("{s} needs a number of days", .{a}); - i += 1; - if (a[2] == 'c') { - compress_v = v; - have_compress = true; - } else { - delete_v = v; - have_delete = true; - } - } else if (std.mem.startsWith(u8, a, "--compress-after=")) { - compress_v = a["--compress-after=".len..]; - have_compress = true; - } else if (std.mem.startsWith(u8, a, "--delete-after=")) { - delete_v = a["--delete-after=".len..]; - have_delete = true; - } else if (a.len > 0 and a[0] == '-') { - die("unknown option {s}", .{a}); - } else { - if (root_s != null) die("rotate takes one ROOT", .{}); - root_s = a; - } - } + var parsed = rotate_cli.take(c.gpa, args); + defer parsed.deinit(c.gpa); + const root_s = parsed.positional(0); + const compress_v = parsed.value("compress-after"); + const delete_v = parsed.value("delete-after"); + const lock_v = parsed.value("lock-timeout") orelse ""; + const syslog_v = parsed.value("syslog"); + const metrics_file = parsed.value("metrics-file"); + const dry_run = parsed.seen("dry-run"); const root_p = root_s orelse die("rotate needs ROOT", .{}); if (root_p.len == 0) die("rotate needs ROOT", .{}); if (metrics_file) |p| if (p.len == 0) die("--metrics-file needs a path", .{}); const root = fsx.openDir(fsx.cwd, root_p, true) catch die("ROOT {s} is not a directory", .{root_p}); defer sys.close(root); - const compress_after = parseDays("--compress-after", if (have_compress) compress_v else null); + const compress_after = parseDays("--compress-after", compress_v); var delete_after: ?u64 = null; - if (have_delete and delete_v.?.len > 0) { - delete_after = parseDays("--delete-after", delete_v); - if (delete_after.? <= compress_after) die("--delete-after must be later than --compress-after", .{}); + if (delete_v) |v| { + if (v.len > 0) { + delete_after = parseDays("--delete-after", v); + if (delete_after.? <= compress_after) die("--delete-after must be later than --compress-after", .{}); + } } const lock_timeout = if (lock_v.len > 0) parseSeconds(lock_v) else default_lock_timeout; const syslog_target = resolveSyslog(c, syslog_v); diff --git a/src/pending.zig b/src/pending.zig index eb4a9d1..059c3a5 100644 --- a/src/pending.zig +++ b/src/pending.zig @@ -12,6 +12,7 @@ const common = @import("zig_common"); const sys = common.sys; const fsx = common.fsx; const cli = common.cli; +const cli_parse = @import("cli_parse.zig"); const Allocator = std.mem.Allocator; const tool = "eb-keep-logs"; @@ -184,20 +185,21 @@ pub fn formatPending(gpa: Allocator, text: []const u8) (Allocator.Error || error return try out.toOwnedSlice(gpa); } +const pending_cli = cli_parse.make(.{ + .prog = "pending", + .options = &.{cli_parse.flag("json")}, + .positionals = &.{cli_parse.one("FILE", true)}, + .missing = &.{ + .{ .name = "FILE", .msg = "pending needs a report" }, + }, +}); + /// `pending [--json] FILE`. pub fn cmdPending(gpa: Allocator, args: []const []const u8) u8 { - var json_out = false; - var path: []const u8 = ""; - for (args) |a| { - if (std.mem.eql(u8, a, "--json")) { - json_out = true; - continue; - } - if (a.len > 0 and a[0] == '-') die("pending does not know '{s}'", .{a}); - if (path.len != 0) die("pending does not know '{s}'", .{a}); - path = a; - } - if (path.len == 0) die("pending needs a report", .{}); + var parsed = pending_cli.take(gpa, args); + defer parsed.deinit(gpa); + const json_out = parsed.seen("json"); + const path = parsed.positional(0).?; const text = readLog(gpa, path) orelse return 2; defer gpa.free(text); const body = if (json_out) blk: { diff --git a/src/runs.zig b/src/runs.zig index bbad2cb..44d57ad 100644 --- a/src/runs.zig +++ b/src/runs.zig @@ -10,6 +10,7 @@ const common = @import("zig_common"); const sys = common.sys; const fsx = common.fsx; const cli = common.cli; +const cli_parse = @import("cli_parse.zig"); const Allocator = std.mem.Allocator; const tool = "eb-keep-logs"; @@ -198,36 +199,22 @@ pub fn formatRuns(gpa: Allocator, text: []const u8, exec: []const u8) (Allocator return try out.toOwnedSlice(gpa); } +const runs_cli = cli_parse.make(.{ + .prog = "runs", + .options = &.{ cli_parse.req("exec"), cli_parse.flag("json") }, + .positionals = &.{cli_parse.one("FILE", true)}, + .missing = &.{ + .{ .name = "FILE", .msg = "runs needs a record file" }, + }, +}); + /// `runs --exec PATH [--json] FILE`. pub fn cmdRuns(gpa: Allocator, args: []const []const u8) u8 { - var exec: []const u8 = ""; - var json_out = false; - var path: []const u8 = ""; - var i: usize = 0; - while (i < args.len) : (i += 1) { - const a = args[i]; - if (std.mem.eql(u8, a, "--json")) { - json_out = true; - } else if (std.mem.eql(u8, a, "--exec") or std.mem.startsWith(u8, a, "--exec=")) { - const v = if (std.mem.startsWith(u8, a, "--exec=")) - a["--exec=".len..] - else blk: { - i += 1; - if (i >= args.len) die("runs needs --exec", .{}); - break :blk args[i]; - }; - if (v.len == 0 or v[0] == '-') die("runs needs --exec", .{}); - exec = v; - } else if (a.len > 0 and a[0] == '-') { - die("runs does not know '{s}'", .{a}); - } else if (path.len == 0) { - path = a; - } else { - die("runs does not know '{s}'", .{a}); - } - } - if (exec.len == 0) die("runs needs --exec", .{}); - if (path.len == 0) die("runs needs a record file", .{}); + var parsed = runs_cli.take(gpa, args); + defer parsed.deinit(gpa); + const exec = parsed.value("exec").?; + const json_out = parsed.seen("json"); + const path = parsed.positional(0).?; const text = readLog(gpa, path) orelse return 2; defer gpa.free(text); var arena = std.heap.ArenaAllocator.init(gpa); diff --git a/src/test_bundle.zig b/src/test_bundle.zig index 68ad4c7..feb0c5f 100644 --- a/src/test_bundle.zig +++ b/src/test_bundle.zig @@ -3,6 +3,7 @@ const std = @import("std"); const common = @import("zig_common"); const cli = common.cli; +const cli_parse = @import("cli_parse.zig"); const fsx = common.fsx; const sys = common.sys; @@ -122,35 +123,57 @@ fn lessInput(_: void, a: InputRecord, b: InputRecord) bool { } fn parseModule(gpa: Allocator, raw: []const u8) !ModuleRecord { - const sep = std.mem.indexOfScalar(u8, raw, '=') orelse - die("test-bundle needs --module NAME=PATH", .{}); + if (!modulePairOk(raw)) die("test-bundle needs --module NAME=PATH", .{}); + const sep = std.mem.indexOfScalar(u8, raw, '=').?; const name = std.mem.trim(u8, raw[0..sep], " \t"); const path = std.mem.trim(u8, raw[sep + 1 ..], " \t"); - if (name.len == 0 or path.len == 0) die("test-bundle needs --module NAME=PATH", .{}); return .{ .name = try gpa.dupe(u8, name), .path = try gpa.dupe(u8, path), }; } -fn optionValue( - args: []const []const u8, - i: *usize, - arg: []const u8, - comptime option: []const u8, - comptime message: []const u8, -) []const u8 { - const value = if (std.mem.startsWith(u8, arg, option ++ "=")) - arg[option.len + 1 ..] - else blk: { - i.* += 1; - if (i.* >= args.len) die(message, .{}); - break :blk args[i.*]; - }; - if (value.len == 0 or value[0] == '-') die(message, .{}); - return value; +fn modulePairOk(raw: []const u8) bool { + const sep = std.mem.indexOfScalar(u8, raw, '=') orelse return false; + const name = std.mem.trim(u8, raw[0..sep], " \t"); + const path = std.mem.trim(u8, raw[sep + 1 ..], " \t"); + return name.len != 0 and path.len != 0; } +fn validModule(gpa: Allocator, raw: []const u8) Allocator.Error!cli_parse.ValidationResult { + if (!modulePairOk(raw)) return .{ .err = try gpa.dupe(u8, "module") }; + return .ok; +} + +const bundle_cli = cli_parse.make(.{ + .prog = "test-bundle", + .options = &.{ + cli_parse.req("test-id"), + cli_parse.req("suite-revision"), + cli_parse.req("eessi-target"), + cli_parse.req("stdout"), + cli_parse.req("stderr"), + cli_parse.req("allocation"), + cli_parse.req("binding"), + cli_parse.req("cpu"), + cli_parse.req("gpu"), + cli_parse.strict("seed"), + cli_parse.strict("out"), + cli_parse.append("input"), + cli_parse.checked(cli_parse.append("module"), validModule), + }, + .missing = &.{ + .{ .name = "input", .msg = "test-bundle needs --input PATH" }, + .{ .name = "module", .msg = "test-bundle needs --module NAME=PATH" }, + }, +}); + +const compare_cli = cli_parse.make(.{ + .prog = "test-compare", + .options = &.{cli_parse.flag("json")}, + .positionals = &.{cli_parse.zeroOrMore("FILE")}, +}); + fn combinedInputHash(gpa: Allocator, inputs: []const InputRecord) ![]u8 { var hash = std.crypto.hash.sha2.Sha256.init(.{}); for (inputs) |input| { @@ -182,70 +205,28 @@ pub fn cmdTestBundle(gpa: Allocator, args: []const []const u8) u8 { defer arena_state.deinit(); const arena = arena_state.allocator(); - var test_id: []const u8 = ""; - var suite_revision: []const u8 = ""; - var eessi_target: []const u8 = ""; - var seed: []const u8 = ""; - var allocation: []const u8 = ""; - var binding: []const u8 = ""; - var cpu: []const u8 = ""; - var gpu: []const u8 = ""; - var stdout_path: []const u8 = ""; - var stderr_path: []const u8 = ""; - var out_path: ?[]const u8 = null; + var parsed = bundle_cli.take(gpa, args); + defer parsed.deinit(gpa); + const test_id = parsed.value("test-id").?; + const suite_revision = parsed.value("suite-revision").?; + const eessi_target = parsed.value("eessi-target").?; + const seed = parsed.value("seed") orelse ""; + const allocation = parsed.value("allocation").?; + const binding = parsed.value("binding").?; + const cpu = parsed.value("cpu").?; + const gpu = parsed.value("gpu").?; + const stdout_path = parsed.value("stdout").?; + const stderr_path = parsed.value("stderr").?; + const out_path = parsed.value("out"); var inputs: std.ArrayList([]const u8) = .empty; defer inputs.deinit(arena); + for (parsed.values("input")) |value| inputs.append(arena, value) catch die("out of memory", .{}); var modules: std.ArrayList(ModuleRecord) = .empty; defer modules.deinit(arena); - - var i: usize = 0; - while (i < args.len) : (i += 1) { - const arg = args[i]; - if (std.mem.eql(u8, arg, "--test-id") or std.mem.startsWith(u8, arg, "--test-id=")) { - test_id = optionValue(args, &i, arg, "--test-id", "test-bundle needs --test-id"); - } else if (std.mem.eql(u8, arg, "--suite-revision") or std.mem.startsWith(u8, arg, "--suite-revision=")) { - suite_revision = optionValue(args, &i, arg, "--suite-revision", "test-bundle needs --suite-revision"); - } else if (std.mem.eql(u8, arg, "--eessi-target") or std.mem.startsWith(u8, arg, "--eessi-target=")) { - eessi_target = optionValue(args, &i, arg, "--eessi-target", "test-bundle needs --eessi-target"); - } else if (std.mem.eql(u8, arg, "--seed") or std.mem.startsWith(u8, arg, "--seed=")) { - seed = optionValue(args, &i, arg, "--seed", "test-bundle needs --seed"); - } else if (std.mem.eql(u8, arg, "--allocation") or std.mem.startsWith(u8, arg, "--allocation=")) { - allocation = optionValue(args, &i, arg, "--allocation", "test-bundle needs --allocation"); - } else if (std.mem.eql(u8, arg, "--binding") or std.mem.startsWith(u8, arg, "--binding=")) { - binding = optionValue(args, &i, arg, "--binding", "test-bundle needs --binding"); - } else if (std.mem.eql(u8, arg, "--cpu") or std.mem.startsWith(u8, arg, "--cpu=")) { - cpu = optionValue(args, &i, arg, "--cpu", "test-bundle needs --cpu"); - } else if (std.mem.eql(u8, arg, "--gpu") or std.mem.startsWith(u8, arg, "--gpu=")) { - gpu = optionValue(args, &i, arg, "--gpu", "test-bundle needs --gpu"); - } else if (std.mem.eql(u8, arg, "--stdout") or std.mem.startsWith(u8, arg, "--stdout=")) { - stdout_path = optionValue(args, &i, arg, "--stdout", "test-bundle needs --stdout"); - } else if (std.mem.eql(u8, arg, "--stderr") or std.mem.startsWith(u8, arg, "--stderr=")) { - stderr_path = optionValue(args, &i, arg, "--stderr", "test-bundle needs --stderr"); - } else if (std.mem.eql(u8, arg, "--out") or std.mem.startsWith(u8, arg, "--out=")) { - out_path = optionValue(args, &i, arg, "--out", "test-bundle needs --out"); - } else if (std.mem.eql(u8, arg, "--input") or std.mem.startsWith(u8, arg, "--input=")) { - const value = optionValue(args, &i, arg, "--input", "test-bundle needs --input PATH"); - inputs.append(arena, value) catch die("out of memory", .{}); - } else if (std.mem.eql(u8, arg, "--module") or std.mem.startsWith(u8, arg, "--module=")) { - const value = optionValue(args, &i, arg, "--module", "test-bundle needs --module NAME=PATH"); - modules.append(arena, parseModule(arena, value) catch die("out of memory", .{})) catch die("out of memory", .{}); - } else if (arg.len > 0 and arg[0] == '-') { - die("test-bundle does not know '{s}'", .{arg}); - } else { - die("test-bundle does not know '{s}'", .{arg}); - } + for (parsed.values("module")) |value| { + modules.append(arena, parseModule(arena, value) catch die("out of memory", .{})) catch die("out of memory", .{}); } - if (test_id.len == 0) die("test-bundle needs --test-id", .{}); - if (suite_revision.len == 0) die("test-bundle needs --suite-revision", .{}); - if (eessi_target.len == 0) die("test-bundle needs --eessi-target", .{}); - if (stdout_path.len == 0) die("test-bundle needs --stdout", .{}); - if (stderr_path.len == 0) die("test-bundle needs --stderr", .{}); - if (allocation.len == 0) die("test-bundle needs --allocation", .{}); - if (binding.len == 0) die("test-bundle needs --binding", .{}); - if (cpu.len == 0) die("test-bundle needs --cpu", .{}); - if (gpu.len == 0) die("test-bundle needs --gpu", .{}); - const stdout_raw = readFile(gpa, stdout_path) orelse return 2; defer gpa.free(stdout_raw); const stderr_raw = readFile(gpa, stderr_path) orelse return 2; @@ -509,19 +490,11 @@ fn valueGpu(b: BundleCore) []const u8 { } pub fn cmdTestCompare(gpa: Allocator, args: []const []const u8) u8 { - var json_out = false; - var files: std.ArrayList([]const u8) = .empty; - defer files.deinit(gpa); - for (args) |arg| { - if (std.mem.eql(u8, arg, "--json")) { - json_out = true; - } else if (arg.len > 0 and arg[0] == '-') { - die("test-compare does not know '{s}'", .{arg}); - } else { - files.append(gpa, arg) catch die("out of memory", .{}); - } - } - if (files.items.len < 2) die("test-compare needs at least two bundle files", .{}); + var parsed = compare_cli.take(gpa, args); + defer parsed.deinit(gpa); + const json_out = parsed.seen("json"); + const files = parsed.positionals; + if (files.len < 2) die("test-compare needs at least two bundle files", .{}); var arena_state = std.heap.ArenaAllocator.init(gpa); defer arena_state.deinit(); @@ -529,14 +502,14 @@ pub fn cmdTestCompare(gpa: Allocator, args: []const []const u8) u8 { var bundles: std.ArrayList(BundleCore) = .empty; defer bundles.deinit(arena); - for (files.items) |path| { + for (files) |path| { const text = readFile(gpa, path) orelse return 2; defer gpa.free(text); - const parsed = parseBundle(arena, path, text) catch { + const bundle = parseBundle(arena, path, text) catch { warn("test-compare: {s} is not a test-bundle schema_version {d} document", .{ path, bundle_schema_version }); return 2; }; - bundles.append(arena, parsed) catch die("out of memory", .{}); + bundles.append(arena, bundle) catch die("out of memory", .{}); } var diffs: std.ArrayList(FieldDiff) = .empty; diff --git a/src/usage.zig b/src/usage.zig index 81bc882..76b8aa3 100644 --- a/src/usage.zig +++ b/src/usage.zig @@ -4,6 +4,7 @@ const common = @import("zig_common"); const sys = common.sys; const fsx = common.fsx; const cli = common.cli; +const cli_parse = @import("cli_parse.zig"); const used = @import("used.zig"); const Allocator = std.mem.Allocator; @@ -253,48 +254,48 @@ fn formatJson( return try out.toOwnedSlice(); } +fn finiteEpoch(gpa: Allocator, raw: []const u8) Allocator.Error!cli_parse.ValidationResult { + const number = std.fmt.parseFloat(f64, raw) catch return .{ .err = try gpa.dupe(u8, "epoch") }; + if (!std.math.isFinite(number) or number < 0) return .{ .err = try gpa.dupe(u8, "epoch") }; + return .ok; +} + +const usage_cli = cli_parse.make(.{ + .prog = "usage", + .mutex = "usage takes --unused or --active, not both", + .options = &.{ + cli_parse.req("software"), + cli_parse.req("modules"), + cli_parse.checked(cli_parse.strict("since"), finiteEpoch), + cli_parse.flag("unused"), + cli_parse.flag("active"), + cli_parse.flag("json"), + }, + .mutually_exclusive = &.{ + .{ .options = &.{ "unused", "active" } }, + }, + .positionals = &.{cli_parse.oneOrMore("FILE")}, + .missing = &.{ + .{ .name = "since", .msg = "--since needs an epoch" }, + .{ .name = "FILE", .msg = "usage needs a record file" }, + }, +}); + /// `usage --software DIR --modules DIR [--since EPOCH] /// [--unused | --active] [--json] FILE...`. pub fn cmdUsage(gpa: Allocator, args: []const []const u8) u8 { - var software: []const u8 = ""; - var modules: []const u8 = ""; - var since_text: ?[]const u8 = null; - var since: ?f64 = null; - var selection: Selection = .all; - var json_out = false; - var files: std.ArrayList([]const u8) = .empty; - defer files.deinit(gpa); - - var i: usize = 0; - while (i < args.len) : (i += 1) { - const arg = args[i]; - if (std.mem.eql(u8, arg, "--software") or std.mem.startsWith(u8, arg, "--software=")) { - software = optionValue(args, &i, arg, "--software", "usage needs --software"); - } else if (std.mem.eql(u8, arg, "--modules") or std.mem.startsWith(u8, arg, "--modules=")) { - modules = optionValue(args, &i, arg, "--modules", "usage needs --modules"); - } else if (std.mem.eql(u8, arg, "--since") or std.mem.startsWith(u8, arg, "--since=")) { - const value = optionValue(args, &i, arg, "--since", "--since needs an epoch"); - const parsed = std.fmt.parseFloat(f64, value) catch die("--since needs an epoch", .{}); - if (!std.math.isFinite(parsed) or parsed < 0) die("--since needs an epoch", .{}); - since_text = value; - since = parsed; - } else if (std.mem.eql(u8, arg, "--unused")) { - if (selection == .active) die("usage takes --unused or --active, not both", .{}); - selection = .unused; - } else if (std.mem.eql(u8, arg, "--active")) { - if (selection == .unused) die("usage takes --unused or --active, not both", .{}); - selection = .active; - } else if (std.mem.eql(u8, arg, "--json")) { - json_out = true; - } else if (arg.len > 0 and arg[0] == '-') { - die("usage does not know '{s}'", .{arg}); - } else { - files.append(gpa, arg) catch die("out of memory", .{}); - } - } - if (software.len == 0) die("usage needs --software", .{}); - if (modules.len == 0) die("usage needs --modules", .{}); - if (files.items.len == 0) die("usage needs a record file", .{}); + var parsed = usage_cli.take(gpa, args); + defer parsed.deinit(gpa); + const software = parsed.value("software").?; + const modules = parsed.value("modules").?; + const since_text = parsed.value("since"); + const since: ?f64 = if (since_text) |value| + std.fmt.parseFloat(f64, value) catch die("--since needs an epoch", .{}) + else + null; + const selection: Selection = if (parsed.seen("unused")) .unused else if (parsed.seen("active")) .active else .all; + const json_out = parsed.seen("json"); + const files = parsed.positionals; if (std.mem.indexOfScalar(u8, software, '\n') != null or std.mem.indexOfScalar(u8, modules, '\n') != null) die("usage directory must not contain a newline", .{}); @@ -315,7 +316,7 @@ pub fn cmdUsage(gpa: Allocator, args: []const []const u8) u8 { var table = inventory(gpa, arena, software) catch die("out of memory", .{}); defer table.deinit(arena); - for (files.items) |path| { + for (files) |path| { const text = readLog(gpa, path) orelse return 2; defer gpa.free(text); const hits = used.parseHits(arena, text) catch |err| switch (err) { @@ -346,24 +347,6 @@ pub fn cmdUsage(gpa: Allocator, args: []const []const u8) u8 { return 0; } -fn optionValue( - args: []const []const u8, - i: *usize, - arg: []const u8, - comptime option: []const u8, - comptime message: []const u8, -) []const u8 { - const value = if (std.mem.startsWith(u8, arg, option ++ "=")) - arg[option.len + 1 ..] - else blk: { - i.* += 1; - if (i.* >= args.len) die(message, .{}); - break :blk args[i.*]; - }; - if (value.len == 0 or value[0] == '-') die(message, .{}); - return value; -} - test "software paths name their installed module" { var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_state.deinit(); diff --git a/src/used.zig b/src/used.zig index 875f38d..7f8ae3e 100644 --- a/src/used.zig +++ b/src/used.zig @@ -9,6 +9,7 @@ const common = @import("zig_common"); const sys = common.sys; const fsx = common.fsx; const cli = common.cli; +const cli_parse = @import("cli_parse.zig"); const loads = @import("loads.zig"); const runs = @import("runs.zig"); @@ -386,40 +387,22 @@ fn readLog(gpa: Allocator, path: []const u8) ?[]u8 { }; } +const used_cli = cli_parse.make(.{ + .prog = "used", + .options = &.{ cli_parse.req("prefix"), cli_parse.flag("json"), cli_parse.flag("require-none") }, + .positionals = &.{cli_parse.zeroOrMore("FILE")}, +}); + /// `used --prefix PREFIX [--json] [--require-none] FILE...`. pub fn cmdUsed(gpa: Allocator, args: []const []const u8) u8 { - var prefix: []const u8 = ""; - var json_out = false; - var require_none = false; - var files: std.ArrayList([]const u8) = .empty; - defer files.deinit(gpa); - - var i: usize = 0; - while (i < args.len) : (i += 1) { - const a = args[i]; - if (std.mem.eql(u8, a, "--prefix") or std.mem.startsWith(u8, a, "--prefix=")) { - const v = if (std.mem.startsWith(u8, a, "--prefix=")) - a["--prefix=".len..] - else blk: { - i += 1; - if (i >= args.len) die("used needs --prefix", .{}); - break :blk args[i]; - }; - if (v.len == 0 or v[0] == '-') die("used needs --prefix", .{}); - prefix = v; - } else if (std.mem.eql(u8, a, "--json")) { - json_out = true; - } else if (std.mem.eql(u8, a, "--require-none")) { - require_none = true; - } else if (a.len > 0 and a[0] == '-') { - die("used does not know '{s}'", .{a}); - } else { - files.append(gpa, a) catch die("out of memory", .{}); - } - } - if (prefix.len == 0) die("used needs --prefix", .{}); + var parsed = used_cli.take(gpa, args); + defer parsed.deinit(gpa); + const prefix = parsed.value("prefix").?; + const json_out = parsed.seen("json"); + const require_none = parsed.seen("require-none"); + const files = parsed.positionals; if (std.mem.indexOfScalar(u8, prefix, '\n') != null) die("used needs --prefix", .{}); - if (files.items.len == 0) die("used needs a record file", .{}); + if (files.len == 0) die("used needs a record file", .{}); var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); @@ -428,7 +411,7 @@ pub fn cmdUsed(gpa: Allocator, args: []const []const u8) u8 { var table = Table.init(a); defer table.deinit(); - for (files.items) |path| { + for (files) |path| { const text = readLog(gpa, path) orelse return 2; defer gpa.free(text); scanText(a, &table, prefix, text) catch |err| switch (err) { diff --git a/src/why.zig b/src/why.zig index 205f480..468516c 100644 --- a/src/why.zig +++ b/src/why.zig @@ -9,6 +9,7 @@ const common = @import("zig_common"); const sys = common.sys; const fsx = common.fsx; const cli = common.cli; +const cli_parse = @import("cli_parse.zig"); const Allocator = std.mem.Allocator; const tool = "eb-keep-logs"; @@ -687,20 +688,6 @@ fn isDirAt(dir: fsx.fd_t, name: []const u8) bool { return st.isDir(); } -/// The value of option `name` at `args[i.*]`, given as `NAME VALUE`, which -/// moves `i` past the value, or as `NAME=VALUE`; null when `args[i.*]` is -/// not the option. A missing or empty value is refused. -fn optionValue(args: []const [:0]const u8, i: *usize, comptime name: []const u8, comptime what: []const u8) ?[]const u8 { - const a = args[i.*]; - const v: []const u8 = if (std.mem.eql(u8, a, name)) blk: { - if (i.* + 1 >= args.len) die(name ++ " needs " ++ what, .{}); - i.* += 1; - break :blk args[i.*]; - } else if (std.mem.startsWith(u8, a, name ++ "=")) a[name.len + 1 ..] else return null; - if (v.len == 0) die(name ++ " needs " ++ what, .{}); - return v; -} - fn plural(n: usize) []const u8 { return if (n == 1) "" else "s"; } @@ -906,54 +893,92 @@ fn normalizePackage(arena: Allocator, raw: []const u8) Allocator.Error![]const u return package; } -fn wantsHelp(args: []const [:0]const u8) bool { - for (args) |a| { - if (std.mem.eql(u8, a, "-h") or std.mem.eql(u8, a, "--help")) return true; - } - return false; -} +const date_missing: []const cli_parse.Missing = &.{ + .{ .name = "target", .msg = "--target needs a target" }, + .{ .name = "package", .msg = "--package needs a package" }, + .{ .name = "since", .msg = "--since needs a date" }, + .{ .name = "until", .msg = "--until needs a date" }, + .{ .name = "root", .msg = "--root needs a directory" }, +}; + +const history_missing: []const cli_parse.Missing = date_missing ++ [_]cli_parse.Missing{ + .{ .name = "PACKAGE", .msg = "history needs PACKAGE: the easyconfig name without .eb, or NAME/VERSION" }, +}; + +const why_cli = cli_parse.make(.{ + .prog = "why", + .help = why_help, + .policy = cli_parse.prescan, + .bare_unknown = true, + .extra = .static, + .extra_msg = "why takes one RUN", + .missing = date_missing, + .options = &.{ + cli_parse.filled("target"), + cli_parse.filled("package"), + cli_parse.filled("since"), + cli_parse.filled("until"), + cli_parse.filled("root"), + cli_parse.flag("latest"), + cli_parse.flag("json"), + }, + .positionals = &.{cli_parse.optional("RUN")}, +}); + +const history_cli = cli_parse.make(.{ + .prog = "history", + .help = history_help, + .policy = cli_parse.prescan, + .bare_unknown = true, + .extra = .static, + .extra_msg = "history takes one PACKAGE", + .missing = history_missing, + .options = &.{ + cli_parse.filled("target"), + cli_parse.filled("since"), + cli_parse.filled("until"), + cli_parse.filled("root"), + cli_parse.flag("failed"), + cli_parse.flag("json"), + }, + .positionals = &.{cli_parse.one("PACKAGE", false)}, +}); + +const failures_cli = cli_parse.make(.{ + .prog = "failures", + .help = failures_help, + .policy = cli_parse.prescan, + .bare_unknown = true, + .extra = .failures, + .missing = date_missing, + .options = &.{ + cli_parse.filled("package"), + cli_parse.filled("target"), + cli_parse.filled("since"), + cli_parse.filled("until"), + cli_parse.filled("root"), + cli_parse.flag("json"), + }, +}); /// `why [RUN | --latest] [--target TARGET] [--package PACKAGE] [--since DATE] [--until DATE] [--root ROOT] [--json]`: /// print why the builds of a run failed, from the logs it kept. Returns 0 once /// its arguments are accepted, whatever it could read; a refused /// invocation exits 2. `-h` and `--help` print what to pass and return 0. pub fn cmdWhy(gpa: Allocator, args: []const [:0]const u8) u8 { - if (wantsHelp(args)) { - cli.put(1, why_help); - return 0; - } - var run_arg: ?[]const u8 = null; - var latest = false; - var target: ?[]const u8 = null; - var package_arg: ?[]const u8 = null; - var since_raw: ?[]const u8 = null; - var until_raw: ?[]const u8 = null; - var root_arg: ?[]const u8 = null; - var as_json = false; - var i: usize = 0; - while (i < args.len) : (i += 1) { - const a = args[i]; - if (std.mem.eql(u8, a, "--latest")) { - latest = true; - } else if (std.mem.eql(u8, a, "--json")) { - as_json = true; - } else if (optionValue(args, &i, "--target", "a target")) |v| { - target = v; - } else if (optionValue(args, &i, "--package", "a package")) |v| { - package_arg = v; - } else if (optionValue(args, &i, "--since", "a date")) |v| { - since_raw = v; - } else if (optionValue(args, &i, "--until", "a date")) |v| { - until_raw = v; - } else if (optionValue(args, &i, "--root", "a directory")) |v| { - root_arg = v; - } else if (a.len > 0 and a[0] == '-') { - die("unknown option {s}", .{a}); - } else { - if (run_arg != null) die("why takes one RUN", .{}); - run_arg = a; - } - } + var parsed = switch (why_cli.takeOrHelp(gpa, args)) { + .help => return 0, + .ok => |p| p, + }; + defer parsed.deinit(gpa); + const run_arg = parsed.positional(0); + const latest = parsed.seen("latest"); + const target = parsed.value("target"); + const package_arg = parsed.value("package"); + const since_raw = parsed.value("since"); + const until_raw = parsed.value("until"); + const root_arg = parsed.value("root"); + const as_json = parsed.seen("json"); if (run_arg != null and latest) die("why takes RUN or --latest, not both", .{}); if (run_arg != null and (since_raw != null or until_raw != null)) die("why takes RUN or --since/--until, not both", .{}); if (run_arg) |r| if (r.len == 0) die("RUN must not be empty", .{}); @@ -1087,40 +1112,18 @@ fn writeHistory(w: *std.Io.Writer, r: HistoryReport) std.Io.Writer.Error!void { /// once its arguments are accepted, whatever it could read; a refused /// invocation exits 2. pub fn cmdHistory(gpa: Allocator, args: []const [:0]const u8) u8 { - if (wantsHelp(args)) { - cli.put(1, history_help); - return 0; - } - var package_arg: ?[]const u8 = null; - var target: ?[]const u8 = null; - var since_raw: ?[]const u8 = null; - var until_raw: ?[]const u8 = null; - var failed_only = false; - var root_arg: ?[]const u8 = null; - var as_json = false; - var i: usize = 0; - while (i < args.len) : (i += 1) { - const a = args[i]; - if (std.mem.eql(u8, a, "--json")) { - as_json = true; - } else if (std.mem.eql(u8, a, "--failed")) { - failed_only = true; - } else if (optionValue(args, &i, "--target", "a target")) |v| { - target = v; - } else if (optionValue(args, &i, "--since", "a date")) |v| { - since_raw = v; - } else if (optionValue(args, &i, "--until", "a date")) |v| { - until_raw = v; - } else if (optionValue(args, &i, "--root", "a directory")) |v| { - root_arg = v; - } else if (a.len > 0 and a[0] == '-') { - die("unknown option {s}", .{a}); - } else { - if (package_arg != null) die("history takes one PACKAGE", .{}); - package_arg = a; - } - } - const package_s = package_arg orelse die("history needs PACKAGE: the easyconfig name without .eb, or NAME/VERSION", .{}); + var parsed = switch (history_cli.takeOrHelp(gpa, args)) { + .help => return 0, + .ok => |p| p, + }; + defer parsed.deinit(gpa); + const package_s = parsed.positional(0).?; + const target = parsed.value("target"); + const since_raw = parsed.value("since"); + const until_raw = parsed.value("until"); + const failed_only = parsed.seen("failed"); + const root_arg = parsed.value("root"); + const as_json = parsed.seen("json"); if (package_s.len == 0) die("PACKAGE must not be empty", .{}); const date_filter = DateFilter.init(since_raw, until_raw); @@ -1238,37 +1241,17 @@ fn writeFailures(w: *std.Io.Writer, r: FailuresReport) std.Io.Writer.Error!void /// its arguments are accepted, whatever it could read; a refused invocation /// exits 2. `-h` and `--help` print what to pass and return 0. pub fn cmdFailures(gpa: Allocator, args: []const [:0]const u8) u8 { - if (wantsHelp(args)) { - cli.put(1, failures_help); - return 0; - } - var package_arg: ?[]const u8 = null; - var target: ?[]const u8 = null; - var since_raw: ?[]const u8 = null; - var until_raw: ?[]const u8 = null; - var root_arg: ?[]const u8 = null; - var as_json = false; - var i: usize = 0; - while (i < args.len) : (i += 1) { - const a = args[i]; - if (std.mem.eql(u8, a, "--json")) { - as_json = true; - } else if (optionValue(args, &i, "--package", "a package")) |v| { - package_arg = v; - } else if (optionValue(args, &i, "--target", "a target")) |v| { - target = v; - } else if (optionValue(args, &i, "--since", "a date")) |v| { - since_raw = v; - } else if (optionValue(args, &i, "--until", "a date")) |v| { - until_raw = v; - } else if (optionValue(args, &i, "--root", "a directory")) |v| { - root_arg = v; - } else if (a.len > 0 and a[0] == '-') { - die("unknown option {s}", .{a}); - } else { - die("failures takes no positional argument, got '{s}'", .{a}); - } - } + var parsed = switch (failures_cli.takeOrHelp(gpa, args)) { + .help => return 0, + .ok => |p| p, + }; + defer parsed.deinit(gpa); + const package_arg = parsed.value("package"); + const target = parsed.value("target"); + const since_raw = parsed.value("since"); + const until_raw = parsed.value("until"); + const root_arg = parsed.value("root"); + const as_json = parsed.seen("json"); const date_filter = DateFilter.init(since_raw, until_raw); var arena_state = std.heap.ArenaAllocator.init(gpa);