summaryrefslogtreecommitdiff
path: root/example/streaming-clap.zig
diff options
context:
space:
mode:
Diffstat (limited to 'example/streaming-clap.zig')
-rw-r--r--example/streaming-clap.zig54
1 files changed, 54 insertions, 0 deletions
diff --git a/example/streaming-clap.zig b/example/streaming-clap.zig
new file mode 100644
index 0000000..0dc2bf7
--- /dev/null
+++ b/example/streaming-clap.zig
@@ -0,0 +1,54 @@
1const std = @import("std");
2const clap = @import("clap");
3
4const debug = std.debug;
5
6pub fn main() !void {
7 var direct_allocator = std.heap.DirectAllocator.init();
8 const allocator = &direct_allocator.allocator;
9 defer direct_allocator.deinit();
10
11 // First we specify what parameters our program can take.
12 const params = []clap.Param(u8){
13 // Param.init takes 3 arguments.
14 // * An "id", which can be any type specified by the argument to Param. Here, we
15 // use a "u8" as the "id" type.
16 // * A bool which determins wether the parameter takes a value.
17 // * A "Names" struct, which determins what names the parameter will have on the
18 // commandline. Names.prefix inits a "Names" struct that has the "short" name
19 // set to the first letter, and the "long" name set to the full name.
20 clap.Param(u8).init('h', false, clap.Names.prefix("help")),
21 clap.Param(u8).init('n', true, clap.Names.prefix("number")),
22
23 // Names.positional returns a "Names" struct where neither the "short" or "long"
24 // name is set.
25 clap.Param(u8).init('f', true, clap.Names.positional()),
26 };
27
28 // We then initialize an argument iterator. We will use the OsIterator as it nicely
29 // wraps iterating over arguments the most efficient way on each os.
30 var os_iter = clap.args.OsIterator.init(allocator);
31 const iter = &os_iter.iter;
32 defer os_iter.deinit();
33
34 // Consume the exe arg.
35 const exe = try iter.next();
36
37 // Finally we initialize our streaming parser.
38 var parser = clap.StreamingClap(u8, clap.args.OsIterator.Error).init(params, iter);
39
40 // Because we use a streaming parser, we have to consume each argument parsed individually.
41 while (try parser.next()) |arg| {
42 // arg.param will point to the parameter which matched the argument.
43 switch (arg.param.id) {
44 'h' => debug.warn("Help!\n"),
45 'n' => debug.warn("--number = {}\n", arg.value.?),
46
47 // arg.value == null, if arg.param.takes_value == false.
48 // Otherwise, arg.value is the value passed with the argument, such as "-a=10"
49 // or "-a 10".
50 'f' => debug.warn("{}\n", arg.value.?),
51 else => unreachable,
52 }
53 }
54}