This repository has been archived by the owner on Oct 21, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsimargs.zig
764 lines (685 loc) · 27.2 KB
/
simargs.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
//! A simple, opinionated, struct-based argument parser in Zig
const std = @import("std");
const testing = std.testing;
const ParseError = error{ NoProgram, NoOption, MissingRequiredOption, MissingOptionValue, InvalidEnumValue };
const OptionError = ParseError || std.mem.Allocator.Error || std.fmt.ParseIntError || std.fmt.ParseFloatError;
/// Parses arguments according to the given structure.
/// - `T` is the configuration of the arguments.
pub fn parse(
allocator: std.mem.Allocator,
comptime T: type,
) OptionError!StructArguments(T) {
const args = try std.process.argsAlloc(allocator);
var parser = OptionParser(T).init(allocator, args);
return parser.parse();
}
const OptionField = struct {
long_name: []const u8,
opt_type: OptionType,
short_name: ?u8 = null,
message: ?[]const u8 = null,
// whether this option is set
is_set: bool = false,
};
fn parseOptionFields(comptime T: type) [std.meta.fields(T).len]OptionField {
const option_type_info = @typeInfo(T);
if (option_type_info != .Struct) {
@compileError("option should be defined using struct, found " ++ @typeName(T));
}
var opt_fields: [std.meta.fields(T).len]OptionField = undefined;
inline for (option_type_info.Struct.fields) |fld, idx| {
const long_name = fld.name;
const opt_type = OptionType.from_zig_type(
fld.field_type,
);
opt_fields[idx] = .{
.long_name = long_name,
.opt_type = opt_type,
// option with default value is set automatically
.is_set = !(fld.default_value == null),
};
}
// parse short names
if (@hasDecl(T, "__shorts__")) {
const shorts_type = @TypeOf(T.__shorts__);
if (@typeInfo(shorts_type) != .Struct) {
@compileError("__shorts__ should be defined using struct, found " ++ @typeName(@typeInfo(shorts_type)));
}
comptime inline for (std.meta.fields(shorts_type)) |fld| {
const long_name = fld.name;
inline for (opt_fields) |*opt_fld| {
if (std.mem.eql(u8, opt_fld.long_name, long_name)) {
const short_name = @field(T.__shorts__, long_name);
if (@typeInfo(@TypeOf(short_name)) != .EnumLiteral) {
@compileError("short option value must be literal enum, found " ++ @typeName(@typeInfo(@TypeOf(short_name))));
}
opt_fld.short_name = @tagName(short_name)[0];
break;
}
} else {
@compileError("no such option exists, long_name: " ++ long_name);
}
};
}
// parse messages
if (@hasDecl(T, "__messages__")) {
const messages_type = @TypeOf(T.__messages__);
if (@typeInfo(messages_type) != .Struct) {
@compileError("__messages__ should be defined using struct, found " ++ @typeName(@typeInfo(messages_type)));
}
inline for (std.meta.fields(messages_type)) |fld| {
const long_name = fld.name;
inline for (opt_fields) |*opt_fld| {
if (std.mem.eql(u8, opt_fld.long_name, long_name)) {
opt_fld.message = @field(T.__messages__, long_name);
break;
}
} else {
@compileError("no such option exists, long_name: " ++ long_name);
}
}
}
return opt_fields;
}
test "parse option fields" {
const fields = comptime parseOptionFields(struct {
verbose: bool,
help: ?bool,
timeout: u16,
@"user-agent": ?[]const u8,
pub const __shorts__ = .{
.verbose = .v,
};
pub const __messages__ = .{
.verbose = "show verbose log",
};
});
try std.testing.expectEqual(4, fields.len);
const first_opt = OptionField{ .long_name = "verbose", .short_name = 'v', .message = "show verbose log", .opt_type = .RequiredBool };
try std.testing.expectEqualStrings(first_opt.long_name, fields[0].long_name);
try std.testing.expectEqual(first_opt.message, fields[0].message);
try std.testing.expectEqual(first_opt.short_name, fields[0].short_name);
try std.testing.expectEqual(first_opt.opt_type, fields[0].opt_type);
try std.testing.expectEqual(first_opt.is_set, fields[0].is_set);
const last_opt = OptionField{ .long_name = "user-agent", .opt_type = .String };
try std.testing.expectEqualStrings(last_opt.long_name, fields[3].long_name);
try std.testing.expectEqual(last_opt.message, fields[3].message);
try std.testing.expectEqual(last_opt.short_name, fields[3].short_name);
try std.testing.expectEqual(last_opt.opt_type, fields[3].opt_type);
try std.testing.expectEqual(last_opt.is_set, fields[3].is_set);
}
fn getRealType(comptime opt_type: type) type {
return switch (@typeInfo(opt_type)) {
.Optional => |o| getRealType(o.child),
else => opt_type,
};
}
fn StructArguments(comptime T: type) type {
return struct {
program: []const u8,
// Parsed arguments
args: T,
// Unparsed arguments
raw_args: [][:0]u8,
positional_args: std.ArrayList([]const u8),
allocator: std.mem.Allocator,
pub fn deinit(self: @This()) void {
self.positional_args.deinit();
if (!@import("builtin").is_test) {
std.process.argsFree(self.allocator, self.raw_args);
}
}
pub fn print_help(
self: @This(),
writer: anytype,
) !void {
const fields = comptime parseOptionFields(T);
const header_tmpl =
\\ USAGE:
\\ {s} [OPTIONS] ...
\\
\\ OPTIONS:
\\
;
const header = try std.fmt.allocPrint(self.allocator, header_tmpl, .{
self.program,
});
defer self.allocator.free(header);
try writer.writeAll(header);
// TODO: Maybe be too small(or big)?
const msg_offset = 35;
inline for (fields) |opt_fld| {
var curr_opt = std.ArrayList([]const u8).init(self.allocator);
defer curr_opt.deinit();
try curr_opt.append("\t");
if (opt_fld.short_name) |sn| {
try curr_opt.append("-");
try curr_opt.append(&[_]u8{sn});
try curr_opt.append(", ");
} else {
try curr_opt.append(" ");
}
try curr_opt.append("--");
try curr_opt.append(opt_fld.long_name);
try curr_opt.append(opt_fld.opt_type.as_string());
var blanks: usize = msg_offset;
for (curr_opt.items) |v| {
blanks -= v.len;
}
while (blanks > 0) {
try curr_opt.append(" ");
blanks -= 1;
}
if (opt_fld.message) |msg| {
try curr_opt.append(msg);
try curr_opt.append(" ");
}
const first_part = try std.mem.join(self.allocator, "", curr_opt.items);
defer self.allocator.free(first_part);
try writer.writeAll(first_part);
inline for (std.meta.fields(T)) |f| {
if (std.mem.eql(u8, f.name, opt_fld.long_name)) {
const real_type = getRealType(f.field_type);
if (@typeInfo(real_type) == .Enum) {
const enum_opts = try std.mem.join(self.allocator, "/", std.meta.fieldNames(real_type));
defer self.allocator.free(enum_opts);
try writer.writeAll("(valid: ");
try writer.writeAll(enum_opts);
try writer.writeAll(")");
}
if (f.default_value) |v| {
const default = @ptrCast(*align(1) const f.field_type, v).*;
const format = "(default: " ++ switch (@TypeOf(default)) {
[]const u8 => "{s}",
?[]const u8 => "{?s}",
else => "{any}",
} ++ ")";
try std.fmt.format(writer, format, .{default});
} else {
if (opt_fld.opt_type.is_required()) {
try writer.writeAll("(required)");
}
}
}
}
try writer.writeAll("\n");
}
}
};
}
const OptionType = enum(u32) {
const REQUIRED_VERSION_SHIFT = 16;
const Self = @This();
RequiredInt,
RequiredBool,
RequiredFloat,
RequiredString,
RequiredEnum,
Int = Self.REQUIRED_VERSION_SHIFT,
Bool,
Float,
String,
Enum,
fn from_zig_type(
comptime T: type,
) OptionType {
return Self.convert(T, false);
}
fn convert(comptime T: type, comptime is_optional: bool) OptionType {
const base_type: Self = switch (@typeInfo(T)) {
.Int => .RequiredInt,
.Bool => .RequiredBool,
.Float => .RequiredFloat,
.Optional => |opt_info| return Self.convert(opt_info.child, true),
.Pointer => |ptr_info|
// only support []const u8
if (ptr_info.size == .Slice and ptr_info.child == u8 and ptr_info.is_const)
.RequiredString
else {
@compileError("not supported option type:" ++ @typeName(T));
},
.Enum => .RequiredEnum,
else => {
@compileError("not supported option type:" ++ @typeName(T));
},
};
return @intToEnum(@This(), @enumToInt(base_type) + if (is_optional) @This().REQUIRED_VERSION_SHIFT else 0);
}
fn is_required(self: Self) bool {
return @enumToInt(self) < REQUIRED_VERSION_SHIFT;
}
fn as_string(self: Self) []const u8 {
return switch (self) {
.Int, .RequiredInt => "=INTEGER",
.Bool, .RequiredBool => "",
.Float, .RequiredFloat => "=FLOAT",
.String, .RequiredString => "=STRING",
.Enum, .RequiredEnum => "=STRING",
};
}
};
test "parse OptionType" {
const testcases = [_]std.meta.Tuple(&.{ type, OptionType }){
.{ i32, OptionType.RequiredInt },
.{ ?u8, OptionType.Int },
.{ f32, OptionType.RequiredFloat },
.{ ?f64, OptionType.Float },
.{ []const u8, OptionType.RequiredString },
.{ ?[]const u8, OptionType.String },
.{ enum {}, OptionType.RequiredEnum },
.{ ?enum {}, OptionType.Enum },
};
inline for (testcases) |tc| {
try std.testing.expectEqual(tc.@"1", comptime OptionType.from_zig_type(tc.@"0"));
}
}
fn OptionParser(
comptime T: type,
) type {
return struct {
allocator: std.mem.Allocator,
args: [][:0]u8,
opt_fields: [std.meta.fields(T).len]OptionField,
const Self = @This();
// `T` is a struct, which define options
fn init(allocator: std.mem.Allocator, args: [][:0]u8) Self {
return .{
.allocator = allocator,
.args = args,
.opt_fields = comptime parseOptionFields(T),
};
}
// State machine used to parse arguments. Available state transitions:
// 1. start -> args
// 2. start -> waitValue -> .. -> waitValue --> args -> ... -> args
// 3. start -> waitBoolValue
// 4. start
const ParseState = enum {
start,
waitValue,
waitBoolValue,
args,
};
fn parse(self: *Self) OptionError!StructArguments(T) {
if (self.args.len == 0) {
return error.NoProgram;
}
var result = StructArguments(T){
.program = self.args[0],
.allocator = self.allocator,
.args = undefined,
.positional_args = std.ArrayList([]const u8).init(self.allocator),
.raw_args = self.args,
};
errdefer result.deinit();
comptime inline for (std.meta.fields(T)) |fld| {
if (fld.default_value) |v| {
// https://github.com/ziglang/zig/blob/d69e97ae1677ca487833caf6937fa428563ed0ae/lib/std/json.zig#L1590
// why align(1) is used here?
@field(result.args, fld.name) = @ptrCast(*align(1) const fld.field_type, v).*;
} else {
if (!OptionType.from_zig_type(fld.field_type).is_required()) {
@field(result.args, fld.name) = null;
}
}
};
var state = ParseState.start;
var current_opt: ?*OptionField = null;
var arg_idx: usize = 1;
while (arg_idx < self.args.len) {
const arg = self.args[arg_idx];
arg_idx += 1;
std.log.debug("state:{s}, arg:{s}", .{ @tagName(
state,
), arg });
switch (state) {
.start => {
if (!std.mem.startsWith(u8, arg, "-")) {
// no option any more, the rest are positional args
state = .args;
arg_idx -= 1;
continue;
}
if (std.mem.startsWith(u8, arg[1..], "-")) {
// long option
const long_name = arg[2..];
for (self.opt_fields) |*opt_fld| {
if (std.mem.eql(u8, opt_fld.long_name, long_name)) {
current_opt = opt_fld;
break;
}
}
} else {
// short option
const short_name = arg[1..];
if (short_name.len != 1) {
std.log.warn("No such short option, name:{s}", .{arg});
return error.NoOption;
}
for (self.opt_fields) |*opt| {
if (opt.short_name) |name| {
if (name == short_name[0]) {
current_opt = opt;
break;
}
}
}
}
var opt = current_opt orelse {
std.log.warn("Current option is null, option_name:{s}", .{arg});
return error.NoOption;
};
if (opt.opt_type == .Bool or opt.opt_type == .RequiredBool) {
state = .waitBoolValue;
} else {
state = .waitValue;
}
},
.args => {
try result.positional_args.append(arg);
},
.waitBoolValue => {
var opt = current_opt.?;
// meet next option name, set current option value to true directly
if (std.mem.startsWith(u8, arg, "-")) {
// push back current arg
arg_idx -= 1;
opt.is_set = try Self.setOptionValue(&result.args, opt.long_name, "true");
} else {
opt.is_set = try Self.setOptionValue(&result.args, opt.long_name, arg);
}
// reset to initial status
state = .start;
current_opt = null;
},
.waitValue => {
var opt = current_opt.?;
opt.is_set = try Self.setOptionValue(&result.args, opt.long_name, arg);
// reset to initial status
state = .start;
current_opt = null;
},
}
}
switch (state) {
// normal exit state
.start, .args => {},
.waitBoolValue => {
var opt = current_opt.?;
opt.is_set = try Self.setOptionValue(&result.args, opt.long_name, "true");
},
.waitValue => return error.MissingOptionValue,
}
inline for (self.opt_fields) |opt| {
if (opt.opt_type.is_required()) {
if (!opt.is_set) {
std.log.warn("Missing required option, name:{s}", .{opt.long_name});
return error.MissingRequiredOption;
}
}
}
return result;
}
fn getSignedness(comptime opt_type: type) std.builtin.Signedness {
return switch (@typeInfo(opt_type)) {
.Int => |i| i.signedness,
.Optional => |o| Self.getSignedness(o.child),
else => @compileError("not int type, have no signedness"),
};
}
// return true when set successfully
fn setOptionValue(opt: *T, long_name: []const u8, raw_value: []const u8) !bool {
inline for (std.meta.fields(T)) |field| {
if (std.mem.eql(u8, field.name, long_name)) {
@field(opt, field.name) =
switch (comptime OptionType.from_zig_type(field.field_type)) {
.Int, .RequiredInt => blk: {
const real_type = comptime getRealType(field.field_type);
break :blk switch (Self.getSignedness(field.field_type)) {
.signed => try std.fmt.parseInt(real_type, raw_value, 0),
.unsigned => try std.fmt.parseUnsigned(real_type, raw_value, 0),
};
},
.Float, .RequiredFloat => try std.fmt.parseFloat(comptime getRealType(field.field_type), raw_value),
.String, .RequiredString => raw_value,
.Bool, .RequiredBool => std.mem.eql(u8, raw_value, "true") or std.mem.eql(u8, raw_value, "1"),
.Enum, .RequiredEnum => blk: {
if (std.meta.stringToEnum(comptime getRealType(field.field_type), raw_value)) |v| {
break :blk v;
} else {
return error.InvalidEnumValue;
}
},
};
return true;
}
}
return false;
}
};
}
const TestArguments = struct {
help: bool,
rate: ?f32 = 2,
timeout: u16,
@"user-agent": ?[]const u8 = "Brave",
pub const __shorts__ = .{
.help = .h,
.rate = .r,
};
pub const __messages__ = .{ .help = "print this help message" };
};
test "parse/valid option values" {
const allocator = std.testing.allocator;
var args = [_][:0]u8{
try allocator.dupeZ(u8, "awesome-cli"),
try allocator.dupeZ(u8, "--help"),
try allocator.dupeZ(u8, "--rate"),
try allocator.dupeZ(u8, "1.2"),
try allocator.dupeZ(u8, "--timeout"),
try allocator.dupeZ(u8, "30"),
try allocator.dupeZ(u8, "--user-agent"),
try allocator.dupeZ(u8, "firefox"),
// positional args
try allocator.dupeZ(u8, "hello"),
try allocator.dupeZ(u8, "world"),
};
defer for (args) |arg| {
allocator.free(arg);
};
var parser = OptionParser(TestArguments).init(allocator, &args);
const opt = try parser.parse();
defer opt.deinit();
// Can't compare struct directly, See following issue
// https://github.com/ziglang/zig/issues/12451
// try std.testing.expectEqual(opt.args, TestArguments{
// .help = true,
// .rate = 1.2,
// .timeout = 30,
// .@"user-agent" = "firefox",
// });
try std.testing.expectEqual(true, opt.args.help);
try std.testing.expectEqual(opt.args.rate.?, 1.2);
try std.testing.expectEqual(opt.args.timeout, 30);
try std.testing.expectEqualStrings("firefox", opt.args.@"user-agent".?);
try std.testing.expectEqualStrings("hello", opt.positional_args.items[0]);
try std.testing.expectEqualStrings("world", opt.positional_args.items[1]);
var help_msg = std.ArrayList(u8).init(allocator);
defer help_msg.deinit();
try opt.print_help(help_msg.writer());
try std.testing.expectEqualStrings(
\\ USAGE:
\\ awesome-cli [OPTIONS] ...
\\
\\ OPTIONS:
\\ -h, --help print this help message (required)
\\ -r, --rate=FLOAT (default: 2.0e+00)
\\ --timeout=INTEGER (required)
\\ --user-agent=STRING (default: Brave)
\\
, help_msg.items);
}
test "parse/bool value" {
const allocator = std.testing.allocator;
{
var args = [_][:0]u8{
try allocator.dupeZ(u8, "awesome-cli"),
try allocator.dupeZ(u8, "--help"),
};
defer for (args) |arg| {
allocator.free(arg);
};
var parser = OptionParser(struct { help: bool }).init(allocator, &args);
const opt = try parser.parse();
defer opt.deinit();
try std.testing.expectEqual(true, opt.args.help);
}
{
var args = [_][:0]u8{
try allocator.dupeZ(u8, "awesome-cli"),
try allocator.dupeZ(u8, "--help"),
try allocator.dupeZ(u8, "true"),
};
defer for (args) |arg| {
allocator.free(arg);
};
var parser = OptionParser(struct { help: bool }).init(allocator, &args);
const opt = try parser.parse();
defer opt.deinit();
try std.testing.expectEqual(true, opt.args.help);
}
}
test "parse/missing required arguments" {
const allocator = std.testing.allocator;
var args = [_][:0]u8{
try allocator.dupeZ(u8, "abc"),
try allocator.dupeZ(u8, "def"),
};
defer for (args) |arg| {
allocator.free(arg);
};
var parser = OptionParser(TestArguments).init(allocator, &args);
try std.testing.expectError(error.MissingRequiredOption, parser.parse());
}
test "parse/invalid u16 values" {
const allocator = std.testing.allocator;
var args = [_][:0]u8{
try allocator.dupeZ(u8, "awesome-cli"),
try allocator.dupeZ(u8, "--timeout"),
try allocator.dupeZ(u8, "not-a-number"),
try allocator.dupeZ(u8, "--help"),
};
defer for (args) |arg| {
allocator.free(arg);
};
var parser = OptionParser(TestArguments).init(allocator, &args);
try std.testing.expectError(error.InvalidCharacter, parser.parse());
}
test "parse/invalid f32 values" {
const allocator = std.testing.allocator;
var args = [_][:0]u8{
try allocator.dupeZ(u8, "awesome-cli"),
try allocator.dupeZ(u8, "--rate"),
try allocator.dupeZ(u8, "not-a-number"),
try allocator.dupeZ(u8, "--help"),
};
defer for (args) |arg| {
allocator.free(arg);
};
var parser = OptionParser(TestArguments).init(allocator, &args);
try std.testing.expectError(error.InvalidCharacter, parser.parse());
}
test "parse/unknown option" {
const allocator = std.testing.allocator;
var args = [_][:0]u8{
try allocator.dupeZ(u8, "awesome-cli"),
try allocator.dupeZ(u8, "-h"),
try allocator.dupeZ(u8, "--timeout"),
try allocator.dupeZ(u8, "1"),
try allocator.dupeZ(u8, "--notexists"),
};
defer for (args) |arg| {
allocator.free(arg);
};
var parser = OptionParser(TestArguments).init(allocator, &args);
try std.testing.expectError(error.NoOption, parser.parse());
}
test "parse/missing option value" {
const allocator = std.testing.allocator;
var args = [_][:0]u8{
try allocator.dupeZ(u8, "awesome-cli"),
try allocator.dupeZ(u8, "-h"),
try allocator.dupeZ(u8, "--timeout"),
};
defer for (args) |arg| {
allocator.free(arg);
};
var parser = OptionParser(TestArguments).init(allocator, &args);
try std.testing.expectError(error.MissingOptionValue, parser.parse());
}
test "parse/default value" {
const allocator = std.testing.allocator;
var args = [_][:0]u8{
try allocator.dupeZ(u8, "awesome-cli"),
};
defer for (args) |arg| {
allocator.free(arg);
};
var parser = OptionParser(struct {
a1: []const u8 = "A1",
a2: ?[]const u8 = "A2",
b1: u8 = 1,
b2: ?u8 = 11,
c1: f16 = 1.5,
c2: ?f16 = 2.5,
d1: bool = true,
d2: ?bool = false,
}).init(allocator, &args);
const opt = try parser.parse();
try std.testing.expectEqualStrings("A1", opt.args.a1);
try std.testing.expectEqual(opt.positional_args.items.len, 0);
var help_msg = std.ArrayList(u8).init(allocator);
defer help_msg.deinit();
try opt.print_help(help_msg.writer());
try std.testing.expectEqualStrings(
\\ USAGE:
\\ awesome-cli [OPTIONS] ...
\\
\\ OPTIONS:
\\ --a1=STRING (default: A1)
\\ --a2=STRING (default: A2)
\\ --b1=INTEGER (default: 1)
\\ --b2=INTEGER (default: 11)
\\ --c1=FLOAT (default: 1.5e+00)
\\ --c2=FLOAT (default: 2.5e+00)
\\ --d1 (default: true)
\\ --d2 (default: false)
\\
, help_msg.items);
}
test "parse/enum option" {
const allocator = std.testing.allocator;
var args = [_][:0]u8{
try allocator.dupeZ(u8, "awesome-cli"),
try allocator.dupeZ(u8, "--a1"),
try allocator.dupeZ(u8, "A"),
};
defer for (args) |arg| {
allocator.free(arg);
};
var parser = OptionParser(struct { a1: enum { A, B }, help: bool = false }).init(allocator, &args);
const opt = try parser.parse();
try std.testing.expectEqual(opt.args.a1, .A);
var help_msg = std.ArrayList(u8).init(allocator);
defer help_msg.deinit();
try opt.print_help(help_msg.writer());
try std.testing.expectEqualStrings(
\\ USAGE:
\\ awesome-cli [OPTIONS] ...
\\
\\ OPTIONS:
\\ --a1=STRING (valid: A/B)(required)
\\ --help (default: false)
\\
, help_msg.items);
}