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
|
const clap = @import("clap");
const std = @import("std");
const debug = std.debug;
pub fn main() !void {
const allocator = std.heap.page_allocator;
// First we specify what parameters our program can take.
const params = [_]clap.Param(u8){
clap.Param(u8){
.id = 'h',
.names = clap.Names{ .short = 'h', .long = "help" },
},
clap.Param(u8){
.id = 'n',
.names = clap.Names{ .short = 'n', .long = "number" },
.takes_value = .One,
},
clap.Param(u8){
.id = 'f',
.takes_value = .One,
},
};
// We then initialize an argument iterator. We will use the OsIterator as it nicely
// wraps iterating over arguments the most efficient way on each os.
var iter = try clap.args.OsIterator.init(allocator);
defer iter.deinit();
// Initalize our diagnostics, which can be used for reporting useful errors.
// This is optional. You can also leave the `diagnostic` field unset if you
// don't care about the extra information `Diagnostic` provides.
var diag = clap.Diagnostic{};
var parser = clap.StreamingClap(u8, clap.args.OsIterator){
.params = ¶ms,
.iter = &iter,
.diagnostic = &diag,
};
// Because we use a streaming parser, we have to consume each argument parsed individually.
while (parser.next() catch |err| {
// Report useful error and exit
diag.report(std.io.getStdErr().outStream(), err) catch {};
return err;
}) |arg| {
// arg.param will point to the parameter which matched the argument.
switch (arg.param.id) {
'h' => debug.warn("Help!\n", .{}),
'n' => debug.warn("--number = {}\n", .{arg.value.?}),
// arg.value == null, if arg.param.takes_value == false.
// Otherwise, arg.value is the value passed with the argument, such as "-a=10"
// or "-a 10".
'f' => debug.warn("{}\n", .{arg.value.?}),
else => unreachable,
}
}
}
|