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
|
const std = @import("std");
const debug = std.debug;
const io = std.io;
const mem = std.mem;
const testing = std.testing;
pub const args = @import("src/args.zig");
test "clap" {
_ = args;
_ = ComptimeClap;
_ = StreamingClap;
}
pub const ComptimeClap = @import("src/comptime.zig").ComptimeClap;
pub const StreamingClap = @import("src/streaming.zig").StreamingClap;
/// The names a ::Param can have.
pub const Names = struct {
/// '-' prefix
short: ?u8 = null,
/// '--' prefix
long: ?[]const u8 = null,
};
/// Represents a parameter for the command line.
/// Parameters come in three kinds:
/// * Short ("-a"): Should be used for the most commonly used parameters in your program.
/// * They can take a value three different ways.
/// * "-a value"
/// * "-a=value"
/// * "-avalue"
/// * They chain if they don't take values: "-abc".
/// * The last given parameter can take a value in the same way that a single parameter can:
/// * "-abc value"
/// * "-abc=value"
/// * "-abcvalue"
/// * Long ("--long-param"): Should be used for less common parameters, or when no single character
/// can describe the paramter.
/// * They can take a value two different ways.
/// * "--long-param value"
/// * "--long-param=value"
/// * Positional: Should be used as the primary parameter of the program, like a filename or
/// an expression to parse.
/// * Positional parameters have both names.long and names.short == null.
/// * Positional parameters must take a value.
pub fn Param(comptime Id: type) type {
return struct {
id: Id = Id{},
names: Names = Names{},
takes_value: bool = false,
};
}
/// Takes a string and parses it to a Param(Help).
/// This is the reverse of 'help' but for at single parameter only.
pub fn parseParam(line: []const u8) !Param(Help) {
var res = Param(Help){
.id = Help{
.msg = line[0..0],
.value = line[0..0],
},
};
var it = mem.tokenize(line, " \t");
var param_str = it.next() orelse return error.NoParamFound;
if (!mem.startsWith(u8, param_str, "--") and mem.startsWith(u8, param_str, "-")) {
const found_comma = param_str[param_str.len - 1] == ',';
if (found_comma)
param_str = param_str[0..param_str.len - 1];
if (param_str.len != 2)
return error.InvalidShortParam;
res.names.short = param_str[1];
if (!found_comma) {
var help_msg = it.rest();
if (it.next()) |next| blk: {
if (mem.startsWith(u8, next, "<")) {
const start = mem.indexOfScalar(u8, help_msg, '<').? + 1;
const len = mem.indexOfScalar(u8, help_msg[start..], '>') orelse break :blk;
res.id.value = help_msg[start..][0..len];
res.takes_value = true;
help_msg = help_msg[start + len + 1..];
}
}
res.id.msg = mem.trim(u8, help_msg, " \t");
return res;
}
param_str = it.next() orelse return error.NoParamFound;
}
if (mem.startsWith(u8, param_str, "--")) {
res.names.long = param_str[2..];
if (param_str[param_str.len - 1] == ',')
return error.TrailingComma;
var help_msg = it.rest();
if (it.next()) |next| blk: {
if (mem.startsWith(u8, next, "<")) {
const start = mem.indexOfScalar(u8, help_msg, '<').? + 1;
const len = mem.indexOfScalar(u8, help_msg[start..], '>') orelse break :blk;
res.id.value = help_msg[start..][0..len];
res.takes_value = true;
help_msg = help_msg[start + len + 1..];
}
}
res.id.msg = mem.trim(u8, help_msg, " \t");
return res;
}
return error.NoParamFound;
}
test "parseParam" {
var text: []const u8 = "-s, --long <value> Help text";
testing.expectEqual(Param(Help){
.id = Help{
.msg = find(text, "Help text"),
.value = find(text, "value"),
},
.names = Names{
.short = 's',
.long = find(text, "long"),
},
.takes_value = true,
}, try parseParam(text));
text = "--long <value> Help text";
testing.expectEqual(Param(Help){
.id = Help{
.msg = find(text, "Help text"),
.value = find(text, "value"),
},
.names = Names{
.short = null,
.long = find(text, "long"),
},
.takes_value = true,
}, try parseParam(text));
text = "-s <value> Help text";
testing.expectEqual(Param(Help){
.id = Help{
.msg = find(text, "Help text"),
.value = find(text, "value"),
},
.names = Names{
.short = 's',
.long = null,
},
.takes_value = true,
}, try parseParam(text));
text = "-s, --long Help text";
testing.expectEqual(Param(Help){
.id = Help{
.msg = find(text, "Help text"),
.value = text[0..0],
},
.names = Names{
.short = 's',
.long = find(text, "long"),
},
.takes_value = false,
}, try parseParam(text));
text = "-s Help text";
testing.expectEqual(Param(Help){
.id = Help{
.msg = find(text, "Help text"),
.value = text[0..0],
},
.names = Names{
.short = 's',
.long = null,
},
.takes_value = false,
}, try parseParam(text));
text = "--long Help text";
testing.expectEqual(Param(Help){
.id = Help{
.msg = find(text, "Help text"),
.value = text[0..0],
},
.names = Names{
.short = null,
.long = find(text, "long"),
},
.takes_value = false,
}, try parseParam(text));
text = "--long <A | B> Help text";
testing.expectEqual(Param(Help){
.id = Help{
.msg = find(text, "Help text"),
.value = find(text, "A | B"),
},
.names = Names{
.short = null,
.long = find(text, "long"),
},
.takes_value = true,
}, try parseParam(text));
testing.expectError(error.NoParamFound, parseParam("Help"));
testing.expectError(error.TrailingComma, parseParam("--long, Help"));
testing.expectError(error.NoParamFound, parseParam("-s, Help"));
testing.expectError(error.InvalidShortParam, parseParam("-ss Help"));
testing.expectError(error.InvalidShortParam, parseParam("-ss <value> Help"));
testing.expectError(error.InvalidShortParam, parseParam("- Help"));
}
fn find(str: []const u8, f: []const u8) []const u8 {
const i = mem.indexOf(u8, str, f).?;
return str[i..][0..f.len];
}
/// Will print a help message in the following format:
/// -s, --long <value_text> help_text
/// -s, help_text
/// -s <value_text> help_text
/// --long help_text
/// --long <value_text> help_text
pub fn helpFull(
stream: var,
comptime Id: type,
params: []const Param(Id),
comptime Error: type,
context: var,
help_text: fn (@typeOf(context), Param(Id)) Error![]const u8,
value_text: fn (@typeOf(context), Param(Id)) Error![]const u8,
) !void {
const max_spacing = blk: {
var res: usize = 0;
for (params) |param| {
var counting_stream = io.CountingOutStream(io.NullOutStream.Error).init(io.null_out_stream);
try printParam(&counting_stream.stream, Id, param, Error, context, value_text);
if (res < counting_stream.bytes_written)
res = counting_stream.bytes_written;
}
break :blk res;
};
for (params) |param| {
if (param.names.short == null and param.names.long == null)
continue;
var counting_stream = io.CountingOutStream(@typeOf(stream.*).Error).init(stream);
try stream.print("\t");
try printParam(&counting_stream.stream, Id, param, Error, context, value_text);
try stream.writeByteNTimes(' ', max_spacing - counting_stream.bytes_written);
try stream.print("\t{}\n", try help_text(context, param));
}
}
fn printParam(
stream: var,
comptime Id: type,
param: Param(Id),
comptime Error: type,
context: var,
value_text: fn (@typeOf(context), Param(Id)) Error![]const u8,
) @typeOf(stream.*).Error!void {
if (param.names.short) |s| {
try stream.print("-{c}", s);
} else {
try stream.print(" ");
}
if (param.names.long) |l| {
if (param.names.short) |_| {
try stream.print(", ");
} else {
try stream.print(" ");
}
try stream.print("--{}", l);
}
if (param.takes_value)
try stream.print(" <{}>", value_text(context, param));
}
/// A wrapper around helpFull for simple help_text and value_text functions that
/// cant return an error or take a context.
pub fn helpEx(
stream: var,
comptime Id: type,
params: []const Param(Id),
help_text: fn (Param(Id)) []const u8,
value_text: fn (Param(Id)) []const u8,
) !void {
const Context = struct {
help_text: fn (Param(Id)) []const u8,
value_text: fn (Param(Id)) []const u8,
pub fn help(c: @This(), p: Param(Id)) error{}![]const u8 {
return c.help_text(p);
}
pub fn value(c: @This(), p: Param(Id)) error{}![]const u8 {
return c.value_text(p);
}
};
return helpFull(
stream,
Id,
params,
error{},
Context{
.help_text = help_text,
.value_text = value_text,
},
Context.help,
Context.value,
);
}
pub const Help = struct {
msg: []const u8 = "",
value: []const u8 = "",
};
/// A wrapper around helpEx that takes a Param(Help).
pub fn help(stream: var, params: []const Param(Help)) !void {
try helpEx(stream, Help, params, getHelpSimple, getValueSimple);
}
fn getHelpSimple(param: Param(Help)) []const u8 {
return param.id.msg;
}
fn getValueSimple(param: Param(Help)) []const u8 {
return param.id.value;
}
test "clap.help" {
var buf: [1024]u8 = undefined;
var slice_stream = io.SliceOutStream.init(buf[0..]);
try help(
&slice_stream.stream,
comptime [_]Param(Help){
parseParam("-a Short flag. ") catch unreachable,
parseParam("-b <V1> Short option.") catch unreachable,
parseParam("--aa Long flag. ") catch unreachable,
parseParam("--bb <V2> Long option. ") catch unreachable,
parseParam("-c, --cc Both flag. ") catch unreachable,
parseParam("-d, --dd <V3> Both option. ") catch unreachable,
Param(Help){
.id = Help{
.msg = "Positional. This should not appear in the help message.",
},
.takes_value = true,
},
},
);
const expected = "" ++
"\t-a \tShort flag.\n" ++
"\t-b <V1> \tShort option.\n" ++
"\t --aa \tLong flag.\n" ++
"\t --bb <V2>\tLong option.\n" ++
"\t-c, --cc \tBoth flag.\n" ++
"\t-d, --dd <V3>\tBoth option.\n";
const actual = slice_stream.getWritten();
if (!mem.eql(u8, actual, expected)) {
debug.warn("\n============ Expected ============\n");
debug.warn("{}", expected);
debug.warn("============= Actual =============\n");
debug.warn("{}", actual);
var buffer: [1024 * 2]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&buffer);
debug.warn("============ Expected (escaped) ============\n");
debug.warn("{x}\n", expected);
debug.warn("============ Actual (escaped) ============\n");
debug.warn("{x}\n", actual);
testing.expect(false);
}
}
|