-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathargparse.zig
More file actions
240 lines (222 loc) · 8.25 KB
/
argparse.zig
File metadata and controls
240 lines (222 loc) · 8.25 KB
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
const std = @import("std");
// Since parse is the only public function, these variables can be set there and
// used globally.
var stdout: *std.Io.Writer = undefined;
var stderr: *std.Io.Writer = undefined;
pub fn parse(
init: std.process.Init,
T: type,
errorCheck: ?fn (args: T, stderr: *std.Io.Writer) anyerror!bool,
) !T {
const allocator = init.gpa;
const io = init.io;
var stdout_writer = std.Io.File.stdout().writer(io, &.{});
stdout = &stdout_writer.interface;
var stderr_writer = std.Io.File.stderr().writer(io, &.{});
stderr = &stderr_writer.interface;
var arena: std.heap.ArenaAllocator = .init(allocator);
defer arena.deinit();
const a = arena.allocator();
const args = try init.minimal.args.toSlice(a);
const fields = @typeInfo(T).@"struct".fields;
var seen = [_]bool{false} ** fields.len;
var result: T = undefined;
errdefer {
inline for (fields, seen) |field, seen_field| {
if (seen_field) {
freeField(allocator, @field(result, field.name));
}
}
}
try setFromCli(T, allocator, &arena, args, &seen, &result);
try setFromEnv(T, allocator, &arena, &seen, &result, init.environ_map);
try setFromDefaults(T, allocator, &seen, &result);
inline for (fields, seen) |field, seen_field| {
if (!seen_field) {
if (@typeInfo(stripOptional(field.type)) == .bool) {
@field(result, field.name) = false;
} else {
try stderr.print(
"Missing required argument {s}\n",
.{field.name},
);
try printUsage(T, arena.allocator(), args[0]);
std.process.exit(1);
}
}
}
if (errorCheck) |check| {
if (!(try check(result, stderr))) {
try printUsage(T, arena.allocator(), args[0]);
std.process.exit(1);
}
}
return result;
}
fn setFromCli(
T: type,
allocator: std.mem.Allocator,
arena: *std.heap.ArenaAllocator,
args: []const []const u8,
seen: []bool,
result: *T,
) !void {
const a = arena.allocator();
var i: usize = 1;
args: while (i < args.len) : (i += 1) {
const raw_arg = args[i];
if (std.mem.eql(u8, raw_arg, "-h") or
std.mem.eql(u8, raw_arg, "--help"))
{
try printUsage(T, arena.allocator(), args[0]);
std.process.exit(0);
}
// TODO: Handle one-letter arguments
if (!std.mem.startsWith(u8, raw_arg, "--")) {
try stderr.print("Unknown argument: '{s}'\n", .{raw_arg});
try printUsage(T, arena.allocator(), args[0]);
std.process.exit(1);
}
const arg = try a.dupe(u8, raw_arg[2..]);
defer a.free(arg);
std.mem.replaceScalar(u8, arg, '-', '_');
inline for (@typeInfo(T).@"struct".fields, seen) |field, *seen_field| {
if (!seen_field.* and std.ascii.eqlIgnoreCase(arg, field.name)) {
const t = @typeInfo(stripOptional(field.type));
if (t == .bool) {
@field(result, field.name) = true;
} else {
i += 1;
if (i >= args.len) {
try stderr.print(
"Missing required value for argument {s} {s}\n",
.{ raw_arg, field.name },
);
try printUsage(T, arena.allocator(), args[0]);
std.process.exit(1);
}
switch (t) {
.int => @field(result, field.name) =
try std.fmt.parseInt(
stripOptional(field.type),
args[i],
0,
),
.pointer => @field(
result,
field.name,
) = try allocator.dupe(u8, args[i]),
.bool => comptime unreachable,
else => @compileError(
"Disallowed or unimplemented struct field type.",
),
}
}
seen_field.* = true;
continue :args;
}
}
try stderr.print("Unknown argument: '{s}'\n", .{raw_arg});
try printUsage(T, arena.allocator(), args[0]);
std.process.exit(1);
}
}
fn setFromEnv(
T: type,
allocator: std.mem.Allocator,
arena: *std.heap.ArenaAllocator,
seen: []bool,
result: *T,
env: *std.process.Environ.Map,
) !void {
const a = arena.allocator();
var iterator = env.iterator();
while (iterator.next()) |entry| {
const key = try a.dupe(u8, entry.key_ptr.*);
defer a.free(key);
std.mem.replaceScalar(u8, key, '-', '_');
inline for (@typeInfo(T).@"struct".fields, seen) |field, *seen_field| {
if (!seen_field.* and std.ascii.eqlIgnoreCase(key, field.name)) {
switch (@typeInfo(stripOptional(field.type))) {
.bool => {
const value = try a.dupe(u8, entry.value_ptr.*);
defer a.free(value);
@field(result, field.name) = value.len > 0 and
!std.ascii.eqlIgnoreCase(value, "false");
},
.int => @field(result, field.name) = try std.fmt.parseInt(
stripOptional(field.type),
entry.value_ptr.*,
0,
),
.pointer => @field(
result,
field.name,
) = try allocator.dupe(u8, entry.value_ptr.*),
else => @compileError(
"Disallowed or unimplemented struct field type.",
),
}
seen_field.* = true;
}
}
}
}
fn setFromDefaults(
T: type,
allocator: std.mem.Allocator,
seen: []bool,
result: *T,
) !void {
inline for (@typeInfo(T).@"struct".fields, seen) |field, *seen_field| {
if (!seen_field.*) {
if (field.defaultValue()) |default| {
switch (@typeInfo(stripOptional(field.type))) {
.bool, .int, .float, .@"enum" => {
@field(result, field.name) = default;
},
.pointer => @field(
result,
field.name,
) = if (default) |p| try allocator.dupe(u8, p) else null,
else => @compileError("Disallowed struct field type."),
}
seen_field.* = true;
}
}
}
}
fn printUsage(T: type, allocator: std.mem.Allocator, argv0: []const u8) !void {
try stdout.print("Usage: {s} [options]\n\n", .{argv0});
try stdout.print("Options:\n", .{});
const fields = @typeInfo(T).@"struct".fields;
inline for (fields) |field| {
switch (@typeInfo(stripOptional(field.type))) {
.bool => {
const flag_version = try allocator.dupe(u8, field.name);
defer allocator.free(flag_version);
std.mem.replaceScalar(u8, flag_version, '_', '-');
try stdout.print("--{s}\n", .{flag_version});
},
else => {
const flag_version = try allocator.dupe(u8, field.name);
defer allocator.free(flag_version);
std.mem.replaceScalar(u8, flag_version, '_', '-');
try stdout.print("--{s} {s}\n", .{ flag_version, field.name });
},
}
}
}
fn stripOptional(T: type) type {
const info = @typeInfo(T);
if (info != .optional) return T;
return stripOptional(info.optional.child);
}
fn freeField(allocator: std.mem.Allocator, field: anytype) void {
switch (@typeInfo(@TypeOf(field))) {
.pointer => allocator.free(field),
.optional => if (field) |v| freeField(allocator, v),
.bool, .int, .float, .@"enum" => {},
else => @compileError("Disallowed struct field type."),
}
}