const std = @import("std"); const u = @import("utils.zig"); const Arg = @This(); key: []const u8, value: Value, description: []const u8 = "", /// Index of the last character of `key` required to uniquely identify it /// among its siblings. Computed at comptime when the sibling list is /// assembled (`group`, `run`); null when not computed. When `key` is a /// prefix of a sibling this is `key.len - 1`, covered only by an exact /// match (matchers resolve exact matches first). unique_index: ?usize = null, const Value = union(enum) { func: Function, group: []const Arg, }; /// list of exclusive sub commands pub inline fn group( /// Arg name used for the group in the CLI. comptime key: []const u8, /// Help text for the group (groups have no function, so no doc source). comptime description: []const u8, /// Args under this group. comptime args: []const Arg, ) Arg { const children = comptime u.withUniqueIndices(Arg, args, "key"); return .{ .key = key, .description = description, .value = .{ .group = &children }, }; } pub inline fn func(comptime f: anytype, comptime description: []const u8) Arg { const params = @as(std.lang.Type, @typeInfo(@TypeOf(f))).@"fn".param_types; comptime var arg_list: [params.len]u.Info = undefined; comptime var arg_count: usize = 0; comptime var seen_optional: ?[]const u8 = null; inline for (params) |param| { const T = param orelse @compileError("command function parameters must have explicit types"); if (T == std.process.Init or T == std.mem.Allocator or T == std.Io) continue; const info = getInfo(T) orelse @compileError("Invalid Type"); // mandatory params must come first, throw error if mandatory after optional switch (info.optional) { .not => if (seen_optional) |name| @compileError( "required parameter '" ++ info.name ++ "' cannot come after optional parameter '" ++ name ++ "' in " ++ u.funcName(f), ), .default_value => if (seen_optional == null) { seen_optional = info.name; }, } arg_list[arg_count] = .{ .name = info.name, .description = info.description, .type_text = info.type_text, .enum_values = info.enum_values, .optional = info.optional, }; arg_count += 1; } const end = if (arg_count > 0) arg_count else 0; const frozen = comptime u.withUniqueIndices(u.Info, arg_list[0..end], "name"); const Func = Wrapped(f); return .{ .key = u.funcName(f), .description = description, .value = .{ .func = .{ .params = &frozen, .Handler = Func.wrapper, .validate = Func.validate, .help_on_error = helpOnError(f), }, }, }; } fn helpOnError(comptime f: anytype) bool { const ret = @typeInfo(@TypeOf(f)).@"fn".return_type orelse return false; const info = @typeInfo(ret); if (info != .error_union) return false; const err_ty = info.error_union.error_set; if (@typeInfo(err_ty).error_set.error_names == null) return false; return !std.mem.startsWith(u8, @typeName(err_ty), "@typeInfo"); } const Function = struct { params: []const u.Info = &.{}, Handler: Handler = undefined, validate: ?*const fn (std.process.Init, []const []const u8, ?*u.Diag) anyerror!void = null, help_on_error: bool = false, }; const Handler = *const fn (std.process.Init, []const []const u8) anyerror!void; fn Wrapped(comptime f: anytype) type { const Fn = @TypeOf(f); const Params = @as(std.lang.Type, @typeInfo(Fn)).@"fn".param_types; return struct { fn parseAll(init: std.process.Init, alloc: std.mem.Allocator, raw_args: []const []const u8, diag: ?*u.Diag) anyerror!ArgsTuple(Fn) { var args: ArgsTuple(Fn) = undefined; var cli_index: usize = 0; inline for (Params, 0..) |fp, i| { const Param = fp.?; args[i] = if (Param == std.process.Init) init else if (Param == std.mem.Allocator) alloc else if (Param == std.Io) init.io else blk: { const info: u.Info = @field(Param, "info"); const has_value = @hasField(Param, "value"); const field = if (has_value) "value" else "is_present"; const Type = @FieldType(Param, field); const has_raw = cli_index < raw_args.len; const raw = if (has_raw) raw_args[cli_index] else ""; cli_index += 1; if (raw.len != 0) { const value = parseArg(Type, alloc, raw) catch |err| { if (diag) |d| { d.param = info.name; d.value = raw; } return err; }; break :blk .{ .value = value, .raw = "" }; } switch (info.optional) { .not => return error.MissingParameter, .default_value => |value| break :blk .{ // null defaults only exist on optional types // (enforced by Param), and parseArg maps empty // raw to null for those. .value = try parseArg(Type, alloc, value orelse ""), .raw = "", }, } }; } return args; } pub fn validate(init: std.process.Init, raw_args: []const []const u8, diag: ?*u.Diag) anyerror!void { if (Params.len == 0) return; var arena: std.heap.ArenaAllocator = .init(init.gpa); defer arena.deinit(); _ = try parseAll(init, arena.allocator(), raw_args, diag); } pub fn wrapper(init: std.process.Init, raw_args: []const []const u8) anyerror!void { if (Params.len == 0) return @call(.auto, f, .{}); var arena: std.heap.ArenaAllocator = .init(init.gpa); // parsed slices point into the arena; it must outlive the call defer arena.deinit(); const args = try parseAll(init, arena.allocator(), raw_args, null); return @call(.auto, f, args); } }; } fn ArgsTuple(comptime f: type) type { const info: std.lang.Type = @typeInfo(f); if (info != .@"fn") @compileError("ArgsTuple expects a function type"); const function_info = info.@"fn"; if (function_info.attrs.varargs) @compileError("Cannot create ArgsTuple for variadic function"); var argument_field_list: [function_info.param_types.len]type = undefined; inline for (function_info.param_types, 0..) |arg_type, i| { const T = arg_type orelse @compileError("cannot create ArgsTuple for function with an 'anytype' parameter"); argument_field_list[i] = T; } return @Tuple(&argument_field_list); } fn parseArg(comptime T: type, arena: std.mem.Allocator, raw: []const u8) !T { const type_info: std.lang.Type = @typeInfo(T); switch (type_info) { .optional => |o| { if (raw.len == 0) return null; return try parseArg(o.child, arena, raw); }, .pointer => |p| { if (p.size != .slice) @compileError("only slice pointers supported: " ++ @typeName(T)); if (p.child == u8 and p.attrs.@"const") return raw; return try parseList(T, arena, raw); }, .int => return std.fmt.parseInt(T, raw, 10), .float => return std.fmt.parseFloat(T, raw), .bool => { var buf: [5]u8 = undefined; const lower = std.ascii.lowerString(&buf, raw); for ([_][]const u8{ "true", "yes" }) |s| if (std.mem.startsWith(u8, s, lower)) return true; for ([_][]const u8{ "false", "no" }) |s| if (std.mem.startsWith(u8, s, lower)) return false; return error.InvalidBoolean; }, .@"enum" => |e| { var partial: ?T = null; inline for (e.field_names, e.field_values) |name, value| { if (std.mem.eql(u8, name, raw)) return @enumFromInt(value); if (std.mem.startsWith(u8, name, raw)) { if (partial != null) return error.AmbiguousEnumValue; partial = @enumFromInt(value); } } return partial orelse error.InvalidEnumTag; }, else => { if (comptime @hasDecl(T, "parse")) { const parse_fn = @typeInfo(@TypeOf(T.parse)).@"fn"; if (parse_fn.params.len == 1) { return try T.parse(raw); } else if (parse_fn.params.len == 2) { return try T.parse(arena, raw); } else { @compileError("parse function must take ([]const u8) or (Allocator, []const u8)"); } } @compileError("unsupported argument type: " ++ @typeName(T)); }, } } inline fn getInfo(comptime T: type) ?u.Info { if (!@hasDecl(T, "info")) return null; const info = @field(T, "info"); if (@TypeOf(info) != u.Info) return null; return @field(T, "info"); } fn parseList(comptime T: type, arena: std.mem.Allocator, raw: []const u8) !T { const Child = @typeInfo(T).pointer.child; if (raw.len == 0) return &.{}; var count: usize = 1; for (raw) |c| { if (c == ',') count += 1; } const out = try arena.alloc(Child, count); var it = std.mem.splitScalar(u8, raw, ','); var i: usize = 0; while (it.next()) |part| : (i += 1) { out[i] = try parseArg(Child, arena, part); } return out; }