diff options
| author | 2022-02-25 19:40:00 +0100 | |
|---|---|---|
| committer | 2022-02-25 19:40:00 +0100 | |
| commit | cfaac64c404fb1c2e892880410aa3b7dd881ea58 (patch) | |
| tree | 0dca149e43daaaef41f55fa61375ab361c36a39c /clap | |
| parent | Fix minor typos in README.md (diff) | |
| download | zig-clap-cfaac64c404fb1c2e892880410aa3b7dd881ea58.tar.gz zig-clap-cfaac64c404fb1c2e892880410aa3b7dd881ea58.tar.xz zig-clap-cfaac64c404fb1c2e892880410aa3b7dd881ea58.zip | |
Change clap into generating a struct
This changes
- `.flag`, `.option`, `.options` and `.positionals` are now just fields
you access.
- Move the current `clap.parse` and friends into `clap.untyped.parse`
- This is in preperation for `clap.typed.parse`
Diffstat (limited to 'clap')
| -rw-r--r-- | clap/comptime.zig | 237 | ||||
| -rw-r--r-- | clap/streaming.zig | 12 | ||||
| -rw-r--r-- | clap/untyped.zig | 394 |
3 files changed, 400 insertions, 243 deletions
diff --git a/clap/comptime.zig b/clap/comptime.zig deleted file mode 100644 index b440004..0000000 --- a/clap/comptime.zig +++ /dev/null | |||
| @@ -1,237 +0,0 @@ | |||
| 1 | const clap = @import("../clap.zig"); | ||
| 2 | const std = @import("std"); | ||
| 3 | |||
| 4 | const debug = std.debug; | ||
| 5 | const heap = std.heap; | ||
| 6 | const io = std.io; | ||
| 7 | const mem = std.mem; | ||
| 8 | const testing = std.testing; | ||
| 9 | |||
| 10 | /// Deprecated: Use `parseEx` instead | ||
| 11 | pub fn ComptimeClap( | ||
| 12 | comptime Id: type, | ||
| 13 | comptime params: []const clap.Param(Id), | ||
| 14 | ) type { | ||
| 15 | comptime var flags: usize = 0; | ||
| 16 | comptime var single_options: usize = 0; | ||
| 17 | comptime var multi_options: usize = 0; | ||
| 18 | comptime var converted_params: []const clap.Param(usize) = &.{}; | ||
| 19 | for (params) |param| { | ||
| 20 | var index: usize = 0; | ||
| 21 | if (param.names.long != null or param.names.short != null) { | ||
| 22 | const ptr = switch (param.takes_value) { | ||
| 23 | .none => &flags, | ||
| 24 | .one => &single_options, | ||
| 25 | .many => &multi_options, | ||
| 26 | }; | ||
| 27 | index = ptr.*; | ||
| 28 | ptr.* += 1; | ||
| 29 | } | ||
| 30 | |||
| 31 | converted_params = converted_params ++ [_]clap.Param(usize){.{ | ||
| 32 | .id = index, | ||
| 33 | .names = param.names, | ||
| 34 | .takes_value = param.takes_value, | ||
| 35 | }}; | ||
| 36 | } | ||
| 37 | |||
| 38 | return struct { | ||
| 39 | multi_options: [multi_options][]const []const u8, | ||
| 40 | single_options: [single_options][]const u8, | ||
| 41 | single_options_is_set: std.PackedIntArray(u1, single_options), | ||
| 42 | flags: std.PackedIntArray(u1, flags), | ||
| 43 | pos: []const []const u8, | ||
| 44 | allocator: mem.Allocator, | ||
| 45 | |||
| 46 | pub fn parse(iter: anytype, opt: clap.ParseOptions) !@This() { | ||
| 47 | const allocator = opt.allocator; | ||
| 48 | var multis = [_]std.ArrayList([]const u8){undefined} ** multi_options; | ||
| 49 | for (multis) |*multi| | ||
| 50 | multi.* = std.ArrayList([]const u8).init(allocator); | ||
| 51 | |||
| 52 | var pos = std.ArrayList([]const u8).init(allocator); | ||
| 53 | |||
| 54 | var res = @This(){ | ||
| 55 | .multi_options = .{undefined} ** multi_options, | ||
| 56 | .single_options = .{undefined} ** single_options, | ||
| 57 | .single_options_is_set = std.PackedIntArray(u1, single_options).init( | ||
| 58 | .{0} ** single_options, | ||
| 59 | ), | ||
| 60 | .flags = std.PackedIntArray(u1, flags).init(.{0} ** flags), | ||
| 61 | .pos = undefined, | ||
| 62 | .allocator = allocator, | ||
| 63 | }; | ||
| 64 | |||
| 65 | var stream = clap.StreamingClap(usize, @typeInfo(@TypeOf(iter)).Pointer.child){ | ||
| 66 | .params = converted_params, | ||
| 67 | .iter = iter, | ||
| 68 | .diagnostic = opt.diagnostic, | ||
| 69 | }; | ||
| 70 | while (try stream.next()) |arg| { | ||
| 71 | const param = arg.param; | ||
| 72 | if (param.names.long == null and param.names.short == null) { | ||
| 73 | try pos.append(arg.value.?); | ||
| 74 | } else if (param.takes_value == .one) { | ||
| 75 | debug.assert(res.single_options.len != 0); | ||
| 76 | if (res.single_options.len != 0) { | ||
| 77 | res.single_options[param.id] = arg.value.?; | ||
| 78 | res.single_options_is_set.set(param.id, 1); | ||
| 79 | } | ||
| 80 | } else if (param.takes_value == .many) { | ||
| 81 | debug.assert(multis.len != 0); | ||
| 82 | if (multis.len != 0) | ||
| 83 | try multis[param.id].append(arg.value.?); | ||
| 84 | } else { | ||
| 85 | debug.assert(res.flags.len != 0); | ||
| 86 | if (res.flags.len != 0) | ||
| 87 | res.flags.set(param.id, 1); | ||
| 88 | } | ||
| 89 | } | ||
| 90 | |||
| 91 | for (multis) |*multi, i| | ||
| 92 | res.multi_options[i] = multi.toOwnedSlice(); | ||
| 93 | res.pos = pos.toOwnedSlice(); | ||
| 94 | |||
| 95 | return res; | ||
| 96 | } | ||
| 97 | |||
| 98 | pub fn deinit(parser: @This()) void { | ||
| 99 | for (parser.multi_options) |o| | ||
| 100 | parser.allocator.free(o); | ||
| 101 | parser.allocator.free(parser.pos); | ||
| 102 | } | ||
| 103 | |||
| 104 | pub fn flag(parser: @This(), comptime name: []const u8) bool { | ||
| 105 | const param = comptime findParam(name); | ||
| 106 | if (param.takes_value != .none) | ||
| 107 | @compileError(name ++ " is an option and not a flag."); | ||
| 108 | |||
| 109 | return parser.flags.get(param.id) != 0; | ||
| 110 | } | ||
| 111 | |||
| 112 | pub fn option(parser: @This(), comptime name: []const u8) ?[]const u8 { | ||
| 113 | const param = comptime findParam(name); | ||
| 114 | if (param.takes_value == .none) | ||
| 115 | @compileError(name ++ " is a flag and not an option."); | ||
| 116 | if (param.takes_value == .many) | ||
| 117 | @compileError(name ++ " takes many options, not one."); | ||
| 118 | if (parser.single_options_is_set.get(param.id) == 0) | ||
| 119 | return null; | ||
| 120 | return parser.single_options[param.id]; | ||
| 121 | } | ||
| 122 | |||
| 123 | pub fn options(parser: @This(), comptime name: []const u8) []const []const u8 { | ||
| 124 | const param = comptime findParam(name); | ||
| 125 | if (param.takes_value == .none) | ||
| 126 | @compileError(name ++ " is a flag and not an option."); | ||
| 127 | if (param.takes_value == .one) | ||
| 128 | @compileError(name ++ " takes one option, not multiple."); | ||
| 129 | |||
| 130 | return parser.multi_options[param.id]; | ||
| 131 | } | ||
| 132 | |||
| 133 | pub fn positionals(parser: @This()) []const []const u8 { | ||
| 134 | return parser.pos; | ||
| 135 | } | ||
| 136 | |||
| 137 | fn findParam(comptime name: []const u8) clap.Param(usize) { | ||
| 138 | comptime { | ||
| 139 | for (converted_params) |param| { | ||
| 140 | if (param.names.short) |s| { | ||
| 141 | if (mem.eql(u8, name, "-" ++ [_]u8{s})) | ||
| 142 | return param; | ||
| 143 | } | ||
| 144 | if (param.names.long) |l| { | ||
| 145 | if (mem.eql(u8, name, "--" ++ l)) | ||
| 146 | return param; | ||
| 147 | } | ||
| 148 | } | ||
| 149 | |||
| 150 | @compileError(name ++ " is not a parameter."); | ||
| 151 | } | ||
| 152 | } | ||
| 153 | }; | ||
| 154 | } | ||
| 155 | |||
| 156 | test "" { | ||
| 157 | const params = comptime &.{ | ||
| 158 | clap.parseParam("-a, --aa") catch unreachable, | ||
| 159 | clap.parseParam("-b, --bb") catch unreachable, | ||
| 160 | clap.parseParam("-c, --cc <V>") catch unreachable, | ||
| 161 | clap.parseParam("-d, --dd <V>...") catch unreachable, | ||
| 162 | clap.parseParam("<P>") catch unreachable, | ||
| 163 | }; | ||
| 164 | |||
| 165 | var iter = clap.args.SliceIterator{ | ||
| 166 | .args = &.{ | ||
| 167 | "-a", "-c", "0", "something", "-d", "a", "--dd", "b", | ||
| 168 | }, | ||
| 169 | }; | ||
| 170 | var args = try clap.parseEx(clap.Help, params, &iter, .{ .allocator = testing.allocator }); | ||
| 171 | defer args.deinit(); | ||
| 172 | |||
| 173 | try testing.expect(args.flag("-a")); | ||
| 174 | try testing.expect(args.flag("--aa")); | ||
| 175 | try testing.expect(!args.flag("-b")); | ||
| 176 | try testing.expect(!args.flag("--bb")); | ||
| 177 | try testing.expectEqualStrings("0", args.option("-c").?); | ||
| 178 | try testing.expectEqualStrings("0", args.option("--cc").?); | ||
| 179 | try testing.expectEqual(@as(usize, 1), args.positionals().len); | ||
| 180 | try testing.expectEqualStrings("something", args.positionals()[0]); | ||
| 181 | try testing.expectEqualSlices([]const u8, &.{ "a", "b" }, args.options("-d")); | ||
| 182 | try testing.expectEqualSlices([]const u8, &.{ "a", "b" }, args.options("--dd")); | ||
| 183 | } | ||
| 184 | |||
| 185 | test "empty" { | ||
| 186 | var iter = clap.args.SliceIterator{ .args = &.{} }; | ||
| 187 | var args = try clap.parseEx(u8, &.{}, &iter, .{ .allocator = testing.allocator }); | ||
| 188 | defer args.deinit(); | ||
| 189 | } | ||
| 190 | |||
| 191 | fn testErr( | ||
| 192 | comptime params: []const clap.Param(u8), | ||
| 193 | args_strings: []const []const u8, | ||
| 194 | expected: []const u8, | ||
| 195 | ) !void { | ||
| 196 | var diag = clap.Diagnostic{}; | ||
| 197 | var iter = clap.args.SliceIterator{ .args = args_strings }; | ||
| 198 | _ = clap.parseEx(u8, params, &iter, .{ | ||
| 199 | .allocator = testing.allocator, | ||
| 200 | .diagnostic = &diag, | ||
| 201 | }) catch |err| { | ||
| 202 | var buf: [1024]u8 = undefined; | ||
| 203 | var fbs = io.fixedBufferStream(&buf); | ||
| 204 | diag.report(fbs.writer(), err) catch return error.TestFailed; | ||
| 205 | try testing.expectEqualStrings(expected, fbs.getWritten()); | ||
| 206 | return; | ||
| 207 | }; | ||
| 208 | |||
| 209 | try testing.expect(false); | ||
| 210 | } | ||
| 211 | |||
| 212 | test "errors" { | ||
| 213 | const params = [_]clap.Param(u8){ | ||
| 214 | .{ | ||
| 215 | .id = 0, | ||
| 216 | .names = .{ .short = 'a', .long = "aa" }, | ||
| 217 | }, | ||
| 218 | .{ | ||
| 219 | .id = 1, | ||
| 220 | .names = .{ .short = 'c', .long = "cc" }, | ||
| 221 | .takes_value = .one, | ||
| 222 | }, | ||
| 223 | }; | ||
| 224 | |||
| 225 | try testErr(¶ms, &.{"q"}, "Invalid argument 'q'\n"); | ||
| 226 | try testErr(¶ms, &.{"-q"}, "Invalid argument '-q'\n"); | ||
| 227 | try testErr(¶ms, &.{"--q"}, "Invalid argument '--q'\n"); | ||
| 228 | try testErr(¶ms, &.{"--q=1"}, "Invalid argument '--q'\n"); | ||
| 229 | try testErr(¶ms, &.{"-a=1"}, "The argument '-a' does not take a value\n"); | ||
| 230 | try testErr(¶ms, &.{"--aa=1"}, "The argument '--aa' does not take a value\n"); | ||
| 231 | try testErr(¶ms, &.{"-c"}, "The argument '-c' requires a value but none was supplied\n"); | ||
| 232 | try testErr( | ||
| 233 | ¶ms, | ||
| 234 | &.{"--cc"}, | ||
| 235 | "The argument '--cc' requires a value but none was supplied\n", | ||
| 236 | ); | ||
| 237 | } | ||
diff --git a/clap/streaming.zig b/clap/streaming.zig index 8eca51a..42b1912 100644 --- a/clap/streaming.zig +++ b/clap/streaming.zig | |||
| @@ -10,7 +10,7 @@ const mem = std.mem; | |||
| 10 | const os = std.os; | 10 | const os = std.os; |
| 11 | const testing = std.testing; | 11 | const testing = std.testing; |
| 12 | 12 | ||
| 13 | /// The result returned from StreamingClap.next | 13 | /// The result returned from Clap.next |
| 14 | pub fn Arg(comptime Id: type) type { | 14 | pub fn Arg(comptime Id: type) type { |
| 15 | return struct { | 15 | return struct { |
| 16 | const Self = @This(); | 16 | const Self = @This(); |
| @@ -21,9 +21,9 @@ pub fn Arg(comptime Id: type) type { | |||
| 21 | } | 21 | } |
| 22 | 22 | ||
| 23 | /// A command line argument parser which, given an ArgIterator, will parse arguments according | 23 | /// A command line argument parser which, given an ArgIterator, will parse arguments according |
| 24 | /// to the params. StreamingClap parses in an iterating manner, so you have to use a loop | 24 | /// to the params. Clap parses in an iterating manner, so you have to use a loop |
| 25 | /// together with StreamingClap.next to parse all the arguments of your program. | 25 | /// together with Clap.next to parse all the arguments of your program. |
| 26 | pub fn StreamingClap(comptime Id: type, comptime ArgIterator: type) type { | 26 | pub fn Clap(comptime Id: type, comptime ArgIterator: type) type { |
| 27 | return struct { | 27 | return struct { |
| 28 | const State = union(enum) { | 28 | const State = union(enum) { |
| 29 | normal, | 29 | normal, |
| @@ -209,7 +209,7 @@ fn testNoErr( | |||
| 209 | results: []const Arg(u8), | 209 | results: []const Arg(u8), |
| 210 | ) !void { | 210 | ) !void { |
| 211 | var iter = args.SliceIterator{ .args = args_strings }; | 211 | var iter = args.SliceIterator{ .args = args_strings }; |
| 212 | var c = StreamingClap(u8, args.SliceIterator){ | 212 | var c = Clap(u8, args.SliceIterator){ |
| 213 | .params = params, | 213 | .params = params, |
| 214 | .iter = &iter, | 214 | .iter = &iter, |
| 215 | }; | 215 | }; |
| @@ -236,7 +236,7 @@ fn testErr( | |||
| 236 | ) !void { | 236 | ) !void { |
| 237 | var diag: clap.Diagnostic = undefined; | 237 | var diag: clap.Diagnostic = undefined; |
| 238 | var iter = args.SliceIterator{ .args = args_strings }; | 238 | var iter = args.SliceIterator{ .args = args_strings }; |
| 239 | var c = StreamingClap(u8, args.SliceIterator){ | 239 | var c = Clap(u8, args.SliceIterator){ |
| 240 | .params = params, | 240 | .params = params, |
| 241 | .iter = &iter, | 241 | .iter = &iter, |
| 242 | .diagnostic = &diag, | 242 | .diagnostic = &diag, |
diff --git a/clap/untyped.zig b/clap/untyped.zig new file mode 100644 index 0000000..c9b6621 --- /dev/null +++ b/clap/untyped.zig | |||
| @@ -0,0 +1,394 @@ | |||
| 1 | const clap = @import("../clap.zig"); | ||
| 2 | const std = @import("std"); | ||
| 3 | |||
| 4 | const builtin = std.builtin; | ||
| 5 | const debug = std.debug; | ||
| 6 | const heap = std.heap; | ||
| 7 | const io = std.io; | ||
| 8 | const mem = std.mem; | ||
| 9 | const process = std.process; | ||
| 10 | const testing = std.testing; | ||
| 11 | |||
| 12 | /// Same as `parseEx` but uses the `args.OsIterator` by default. | ||
| 13 | pub fn parse( | ||
| 14 | comptime Id: type, | ||
| 15 | comptime params: []const clap.Param(Id), | ||
| 16 | opt: clap.ParseOptions, | ||
| 17 | ) !Result(Arguments(Id, params, []const []const u8, &[_][]const u8{})) { | ||
| 18 | var arena = heap.ArenaAllocator.init(opt.allocator); | ||
| 19 | errdefer arena.deinit(); | ||
| 20 | |||
| 21 | var iter = try process.ArgIterator.initWithAllocator(arena.allocator()); | ||
| 22 | const exe_arg = iter.next(); | ||
| 23 | |||
| 24 | const result = try parseEx(Id, params, &iter, .{ | ||
| 25 | // Let's reuse the arena from the `OSIterator` since we already have it. | ||
| 26 | .allocator = arena.allocator(), | ||
| 27 | .diagnostic = opt.diagnostic, | ||
| 28 | }); | ||
| 29 | |||
| 30 | return Result(Arguments(Id, params, []const []const u8, &.{})){ | ||
| 31 | .args = result.args, | ||
| 32 | .positionals = result.positionals, | ||
| 33 | .exe_arg = exe_arg, | ||
| 34 | .arena = arena, | ||
| 35 | }; | ||
| 36 | } | ||
| 37 | |||
| 38 | pub fn Result(comptime Args: type) type { | ||
| 39 | return struct { | ||
| 40 | args: Args, | ||
| 41 | positionals: []const []const u8, | ||
| 42 | exe_arg: ?[]const u8, | ||
| 43 | arena: std.heap.ArenaAllocator, | ||
| 44 | |||
| 45 | pub fn deinit(result: @This()) void { | ||
| 46 | result.arena.deinit(); | ||
| 47 | } | ||
| 48 | }; | ||
| 49 | } | ||
| 50 | |||
| 51 | /// Parses the command line arguments passed into the program based on an | ||
| 52 | /// array of `Param`s. | ||
| 53 | pub fn parseEx( | ||
| 54 | comptime Id: type, | ||
| 55 | comptime params: []const clap.Param(Id), | ||
| 56 | iter: anytype, | ||
| 57 | opt: clap.ParseOptions, | ||
| 58 | ) !ResultEx(Arguments(Id, params, []const []const u8, &.{})) { | ||
| 59 | const allocator = opt.allocator; | ||
| 60 | var positionals = std.ArrayList([]const u8).init(allocator); | ||
| 61 | var args = Arguments(Id, params, std.ArrayListUnmanaged([]const u8), .{}){}; | ||
| 62 | errdefer deinitArgs(allocator, &args); | ||
| 63 | |||
| 64 | var stream = clap.streaming.Clap(Id, @typeInfo(@TypeOf(iter)).Pointer.child){ | ||
| 65 | .params = params, | ||
| 66 | .iter = iter, | ||
| 67 | .diagnostic = opt.diagnostic, | ||
| 68 | }; | ||
| 69 | while (try stream.next()) |arg| { | ||
| 70 | inline for (params) |*param| { | ||
| 71 | if (param == arg.param) { | ||
| 72 | const longest = comptime param.names.longest(); | ||
| 73 | switch (longest.kind) { | ||
| 74 | .short, .long => switch (param.takes_value) { | ||
| 75 | .none => @field(args, longest.name) = true, | ||
| 76 | .one => @field(args, longest.name) = arg.value.?, | ||
| 77 | .many => try @field(args, longest.name).append(allocator, arg.value.?), | ||
| 78 | }, | ||
| 79 | .positinal => try positionals.append(arg.value.?), | ||
| 80 | } | ||
| 81 | } | ||
| 82 | } | ||
| 83 | } | ||
| 84 | |||
| 85 | var result_args = Arguments(Id, params, []const []const u8, &.{}){}; | ||
| 86 | inline for (@typeInfo(@TypeOf(args)).Struct.fields) |field| { | ||
| 87 | if (field.field_type == std.ArrayListUnmanaged([]const u8)) { | ||
| 88 | const slice = @field(args, field.name).toOwnedSlice(allocator); | ||
| 89 | @field(result_args, field.name) = slice; | ||
| 90 | } else { | ||
| 91 | @field(result_args, field.name) = @field(args, field.name); | ||
| 92 | } | ||
| 93 | } | ||
| 94 | |||
| 95 | return ResultEx(@TypeOf(result_args)){ | ||
| 96 | .args = result_args, | ||
| 97 | .positionals = positionals.toOwnedSlice(), | ||
| 98 | .allocator = allocator, | ||
| 99 | }; | ||
| 100 | } | ||
| 101 | |||
| 102 | pub fn ResultEx(comptime Args: type) type { | ||
| 103 | return struct { | ||
| 104 | args: Args, | ||
| 105 | positionals: []const []const u8, | ||
| 106 | allocator: mem.Allocator, | ||
| 107 | |||
| 108 | pub fn deinit(result: *@This()) void { | ||
| 109 | deinitArgs(result.allocator, &result.args); | ||
| 110 | result.allocator.free(result.positionals); | ||
| 111 | } | ||
| 112 | }; | ||
| 113 | } | ||
| 114 | |||
| 115 | fn deinitArgs(allocator: mem.Allocator, args: anytype) void { | ||
| 116 | const Args = @TypeOf(args.*); | ||
| 117 | inline for (@typeInfo(Args).Struct.fields) |field| { | ||
| 118 | if (field.field_type == []const []const u8) | ||
| 119 | allocator.free(@field(args, field.name)); | ||
| 120 | if (field.field_type == std.ArrayListUnmanaged([]const u8)) | ||
| 121 | @field(args, field.name).deinit(allocator); | ||
| 122 | } | ||
| 123 | } | ||
| 124 | |||
| 125 | fn Arguments( | ||
| 126 | comptime Id: type, | ||
| 127 | comptime params: []const clap.Param(Id), | ||
| 128 | comptime MultiArgsType: type, | ||
| 129 | comptime multi_args_default: MultiArgsType, | ||
| 130 | ) type { | ||
| 131 | var fields: [params.len]builtin.TypeInfo.StructField = undefined; | ||
| 132 | |||
| 133 | var i: usize = 0; | ||
| 134 | for (params) |param| { | ||
| 135 | const longest = param.names.longest(); | ||
| 136 | if (longest.kind == .positinal) | ||
| 137 | continue; | ||
| 138 | |||
| 139 | const field_type = switch (param.takes_value) { | ||
| 140 | .none => bool, | ||
| 141 | .one => ?[]const u8, | ||
| 142 | .many => MultiArgsType, | ||
| 143 | }; | ||
| 144 | fields[i] = .{ | ||
| 145 | .name = longest.name, | ||
| 146 | .field_type = field_type, | ||
| 147 | .default_value = switch (param.takes_value) { | ||
| 148 | .none => &false, | ||
| 149 | .one => &@as(?[]const u8, null), | ||
| 150 | .many => &multi_args_default, | ||
| 151 | }, | ||
| 152 | .is_comptime = false, | ||
| 153 | .alignment = @alignOf(field_type), | ||
| 154 | }; | ||
| 155 | i += 1; | ||
| 156 | } | ||
| 157 | |||
| 158 | return @Type(.{ .Struct = .{ | ||
| 159 | .layout = .Auto, | ||
| 160 | .fields = fields[0..i], | ||
| 161 | .decls = &.{}, | ||
| 162 | .is_tuple = false, | ||
| 163 | } }); | ||
| 164 | } | ||
| 165 | |||
| 166 | test "" { | ||
| 167 | const params = comptime &.{ | ||
| 168 | parseParam("-a, --aa") catch unreachable, | ||
| 169 | parseParam("-b, --bb") catch unreachable, | ||
| 170 | parseParam("-c, --cc <V>") catch unreachable, | ||
| 171 | parseParam("-d, --dd <V>...") catch unreachable, | ||
| 172 | parseParam("<P>") catch unreachable, | ||
| 173 | }; | ||
| 174 | |||
| 175 | var iter = clap.args.SliceIterator{ | ||
| 176 | .args = &.{ | ||
| 177 | "-a", "-c", "0", "something", "-d", "a", "--dd", "b", | ||
| 178 | }, | ||
| 179 | }; | ||
| 180 | var res = try clap.untyped.parseEx(clap.Help, params, &iter, .{ | ||
| 181 | .allocator = testing.allocator, | ||
| 182 | }); | ||
| 183 | defer res.deinit(); | ||
| 184 | |||
| 185 | try testing.expect(res.args.aa); | ||
| 186 | try testing.expect(!res.args.bb); | ||
| 187 | try testing.expectEqualStrings("0", res.args.cc.?); | ||
| 188 | try testing.expectEqual(@as(usize, 1), res.positionals.len); | ||
| 189 | try testing.expectEqualStrings("something", res.positionals[0]); | ||
| 190 | try testing.expectEqualSlices([]const u8, &.{ "a", "b" }, res.args.dd); | ||
| 191 | } | ||
| 192 | |||
| 193 | test "empty" { | ||
| 194 | var iter = clap.args.SliceIterator{ .args = &.{} }; | ||
| 195 | var res = try clap.untyped.parseEx(u8, &.{}, &iter, .{ .allocator = testing.allocator }); | ||
| 196 | defer res.deinit(); | ||
| 197 | } | ||
| 198 | |||
| 199 | fn testErr( | ||
| 200 | comptime params: []const clap.Param(u8), | ||
| 201 | args_strings: []const []const u8, | ||
| 202 | expected: []const u8, | ||
| 203 | ) !void { | ||
| 204 | var diag = clap.Diagnostic{}; | ||
| 205 | var iter = clap.args.SliceIterator{ .args = args_strings }; | ||
| 206 | _ = clap.untyped.parseEx(u8, params, &iter, .{ | ||
| 207 | .allocator = testing.allocator, | ||
| 208 | .diagnostic = &diag, | ||
| 209 | }) catch |err| { | ||
| 210 | var buf: [1024]u8 = undefined; | ||
| 211 | var fbs = io.fixedBufferStream(&buf); | ||
| 212 | diag.report(fbs.writer(), err) catch return error.TestFailed; | ||
| 213 | try testing.expectEqualStrings(expected, fbs.getWritten()); | ||
| 214 | return; | ||
| 215 | }; | ||
| 216 | |||
| 217 | try testing.expect(false); | ||
| 218 | } | ||
| 219 | |||
| 220 | test "errors" { | ||
| 221 | const params = [_]clap.Param(u8){ | ||
| 222 | .{ | ||
| 223 | .id = 0, | ||
| 224 | .names = .{ .short = 'a', .long = "aa" }, | ||
| 225 | }, | ||
| 226 | .{ | ||
| 227 | .id = 1, | ||
| 228 | .names = .{ .short = 'c', .long = "cc" }, | ||
| 229 | .takes_value = .one, | ||
| 230 | }, | ||
| 231 | }; | ||
| 232 | |||
| 233 | try testErr(¶ms, &.{"q"}, "Invalid argument 'q'\n"); | ||
| 234 | try testErr(¶ms, &.{"-q"}, "Invalid argument '-q'\n"); | ||
| 235 | try testErr(¶ms, &.{"--q"}, "Invalid argument '--q'\n"); | ||
| 236 | try testErr(¶ms, &.{"--q=1"}, "Invalid argument '--q'\n"); | ||
| 237 | try testErr(¶ms, &.{"-a=1"}, "The argument '-a' does not take a value\n"); | ||
| 238 | try testErr(¶ms, &.{"--aa=1"}, "The argument '--aa' does not take a value\n"); | ||
| 239 | try testErr(¶ms, &.{"-c"}, "The argument '-c' requires a value but none was supplied\n"); | ||
| 240 | try testErr( | ||
| 241 | ¶ms, | ||
| 242 | &.{"--cc"}, | ||
| 243 | "The argument '--cc' requires a value but none was supplied\n", | ||
| 244 | ); | ||
| 245 | } | ||
| 246 | |||
| 247 | /// Takes a string and parses it to a Param(clap.Help). | ||
| 248 | /// This is the reverse of 'help' but for at single parameter only. | ||
| 249 | pub fn parseParam(line: []const u8) !clap.Param(clap.Help) { | ||
| 250 | // This function become a lot less ergonomic to use once you hit the eval branch quota. To | ||
| 251 | // avoid this we pick a sane default. Sadly, the only sane default is the biggest possible | ||
| 252 | // value. If we pick something a lot smaller and a user hits the quota after that, they have | ||
| 253 | // no way of overriding it, since we set it here. | ||
| 254 | // We can recosider this again if: | ||
| 255 | // * We get parseParams: https://github.com/Hejsil/zig-clap/issues/39 | ||
| 256 | // * We get a larger default branch quota in the zig compiler (stage 2). | ||
| 257 | // * Someone points out how this is a really bad idea. | ||
| 258 | @setEvalBranchQuota(std.math.maxInt(u32)); | ||
| 259 | |||
| 260 | var found_comma = false; | ||
| 261 | var it = mem.tokenize(u8, line, " \t"); | ||
| 262 | var param_str = it.next() orelse return error.NoParamFound; | ||
| 263 | |||
| 264 | const short_name = if (!mem.startsWith(u8, param_str, "--") and | ||
| 265 | mem.startsWith(u8, param_str, "-")) | ||
| 266 | blk: { | ||
| 267 | found_comma = param_str[param_str.len - 1] == ','; | ||
| 268 | if (found_comma) | ||
| 269 | param_str = param_str[0 .. param_str.len - 1]; | ||
| 270 | |||
| 271 | if (param_str.len != 2) | ||
| 272 | return error.InvalidShortParam; | ||
| 273 | |||
| 274 | const short_name = param_str[1]; | ||
| 275 | if (!found_comma) { | ||
| 276 | var res = parseParamRest(it.rest()); | ||
| 277 | res.names.short = short_name; | ||
| 278 | return res; | ||
| 279 | } | ||
| 280 | |||
| 281 | param_str = it.next() orelse return error.NoParamFound; | ||
| 282 | break :blk short_name; | ||
| 283 | } else null; | ||
| 284 | |||
| 285 | const long_name = if (mem.startsWith(u8, param_str, "--")) blk: { | ||
| 286 | if (param_str[param_str.len - 1] == ',') | ||
| 287 | return error.TrailingComma; | ||
| 288 | |||
| 289 | break :blk param_str[2..]; | ||
| 290 | } else if (found_comma) { | ||
| 291 | return error.TrailingComma; | ||
| 292 | } else if (short_name == null) { | ||
| 293 | return parseParamRest(mem.trimLeft(u8, line, " \t")); | ||
| 294 | } else null; | ||
| 295 | |||
| 296 | var res = parseParamRest(it.rest()); | ||
| 297 | res.names.long = long_name; | ||
| 298 | res.names.short = short_name; | ||
| 299 | return res; | ||
| 300 | } | ||
| 301 | |||
| 302 | fn parseParamRest(line: []const u8) clap.Param(clap.Help) { | ||
| 303 | if (mem.startsWith(u8, line, "<")) blk: { | ||
| 304 | const len = mem.indexOfScalar(u8, line, '>') orelse break :blk; | ||
| 305 | const takes_many = mem.startsWith(u8, line[len + 1 ..], "..."); | ||
| 306 | const help_start = len + 1 + @as(usize, 3) * @boolToInt(takes_many); | ||
| 307 | return .{ | ||
| 308 | .takes_value = if (takes_many) .many else .one, | ||
| 309 | .id = .{ | ||
| 310 | .msg = mem.trim(u8, line[help_start..], " \t"), | ||
| 311 | .value = line[1..len], | ||
| 312 | }, | ||
| 313 | }; | ||
| 314 | } | ||
| 315 | |||
| 316 | return .{ .id = .{ .msg = mem.trim(u8, line, " \t") } }; | ||
| 317 | } | ||
| 318 | |||
| 319 | fn expectParam(expect: clap.Param(clap.Help), actual: clap.Param(clap.Help)) !void { | ||
| 320 | try testing.expectEqualStrings(expect.id.msg, actual.id.msg); | ||
| 321 | try testing.expectEqualStrings(expect.id.value, actual.id.value); | ||
| 322 | try testing.expectEqual(expect.names.short, actual.names.short); | ||
| 323 | try testing.expectEqual(expect.takes_value, actual.takes_value); | ||
| 324 | if (expect.names.long) |long| { | ||
| 325 | try testing.expectEqualStrings(long, actual.names.long.?); | ||
| 326 | } else { | ||
| 327 | try testing.expectEqual(@as(?[]const u8, null), actual.names.long); | ||
| 328 | } | ||
| 329 | } | ||
| 330 | |||
| 331 | test "parseParam" { | ||
| 332 | try expectParam(clap.Param(clap.Help){ | ||
| 333 | .id = .{ .msg = "Help text", .value = "value" }, | ||
| 334 | .names = .{ .short = 's', .long = "long" }, | ||
| 335 | .takes_value = .one, | ||
| 336 | }, try parseParam("-s, --long <value> Help text")); | ||
| 337 | |||
| 338 | try expectParam(clap.Param(clap.Help){ | ||
| 339 | .id = .{ .msg = "Help text", .value = "value" }, | ||
| 340 | .names = .{ .short = 's', .long = "long" }, | ||
| 341 | .takes_value = .many, | ||
| 342 | }, try parseParam("-s, --long <value>... Help text")); | ||
| 343 | |||
| 344 | try expectParam(clap.Param(clap.Help){ | ||
| 345 | .id = .{ .msg = "Help text", .value = "value" }, | ||
| 346 | .names = .{ .long = "long" }, | ||
| 347 | .takes_value = .one, | ||
| 348 | }, try parseParam("--long <value> Help text")); | ||
| 349 | |||
| 350 | try expectParam(clap.Param(clap.Help){ | ||
| 351 | .id = .{ .msg = "Help text", .value = "value" }, | ||
| 352 | .names = .{ .short = 's' }, | ||
| 353 | .takes_value = .one, | ||
| 354 | }, try parseParam("-s <value> Help text")); | ||
| 355 | |||
| 356 | try expectParam(clap.Param(clap.Help){ | ||
| 357 | .id = .{ .msg = "Help text" }, | ||
| 358 | .names = .{ .short = 's', .long = "long" }, | ||
| 359 | }, try parseParam("-s, --long Help text")); | ||
| 360 | |||
| 361 | try expectParam(clap.Param(clap.Help){ | ||
| 362 | .id = .{ .msg = "Help text" }, | ||
| 363 | .names = .{ .short = 's' }, | ||
| 364 | }, try parseParam("-s Help text")); | ||
| 365 | |||
| 366 | try expectParam(clap.Param(clap.Help){ | ||
| 367 | .id = .{ .msg = "Help text" }, | ||
| 368 | .names = .{ .long = "long" }, | ||
| 369 | }, try parseParam("--long Help text")); | ||
| 370 | |||
| 371 | try expectParam(clap.Param(clap.Help){ | ||
| 372 | .id = .{ .msg = "Help text", .value = "A | B" }, | ||
| 373 | .names = .{ .long = "long" }, | ||
| 374 | .takes_value = .one, | ||
| 375 | }, try parseParam("--long <A | B> Help text")); | ||
| 376 | |||
| 377 | try expectParam(clap.Param(clap.Help){ | ||
| 378 | .id = .{ .msg = "Help text", .value = "A" }, | ||
| 379 | .names = .{}, | ||
| 380 | .takes_value = .one, | ||
| 381 | }, try parseParam("<A> Help text")); | ||
| 382 | |||
| 383 | try expectParam(clap.Param(clap.Help){ | ||
| 384 | .id = .{ .msg = "Help text", .value = "A" }, | ||
| 385 | .names = .{}, | ||
| 386 | .takes_value = .many, | ||
| 387 | }, try parseParam("<A>... Help text")); | ||
| 388 | |||
| 389 | try testing.expectError(error.TrailingComma, parseParam("--long, Help")); | ||
| 390 | try testing.expectError(error.TrailingComma, parseParam("-s, Help")); | ||
| 391 | try testing.expectError(error.InvalidShortParam, parseParam("-ss Help")); | ||
| 392 | try testing.expectError(error.InvalidShortParam, parseParam("-ss <value> Help")); | ||
| 393 | try testing.expectError(error.InvalidShortParam, parseParam("- Help")); | ||
| 394 | } | ||