Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions build.zig.zon
Original file line number Diff line number Diff line change
Expand Up @@ -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 = .{
Expand Down
153 changes: 153 additions & 0 deletions src/cli_parse.zig
Original file line number Diff line number Diff line change
@@ -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),
}
}
109 changes: 41 additions & 68 deletions src/lifecycle.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand All @@ -1211,8 +1184,8 @@ pub fn cmdLifecycle(
env,
envp,
eb_stack_exe,
easyconfigs.items,
easystacks.items,
easyconfigs,
easystacks,
usage_in.packages,
candidates.items,
);
Expand Down
43 changes: 15 additions & 28 deletions src/loads.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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: {
Expand Down
Loading
Loading