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
|
/*
* Copyright (c) 2020, Sergey Bugaev <bugaevc@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <AK/Format.h>
#include <AK/StringBuilder.h>
#include <LibCore/ArgsParser.h>
#include <getopt.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
static constexpr bool isnan(double __x) { return __builtin_isnan(__x); }
static Optional<double> convert_to_double(const char* s)
{
char* p;
double v = strtod(s, &p);
if (isnan(v) || p == s)
return {};
return v;
}
namespace Core {
ArgsParser::ArgsParser()
{
add_option(m_show_help, "Display this message", "help", 0);
}
bool ArgsParser::parse(int argc, char** argv, bool exit_on_failure)
{
auto print_usage_and_exit = [this, argv, exit_on_failure] {
print_usage(stderr, argv[0]);
if (exit_on_failure)
exit(1);
};
Vector<option> long_options;
StringBuilder short_options_builder;
int index_of_found_long_option = -1;
// Tell getopt() to reset its internal state, and start scanning from optind = 1.
// We could also set optreset = 1, but the host platform may not support that.
optind = 0;
for (size_t i = 0; i < m_options.size(); i++) {
auto& opt = m_options[i];
if (opt.long_name) {
option long_opt {
opt.long_name,
opt.requires_argument ? required_argument : no_argument,
&index_of_found_long_option,
static_cast<int>(i)
};
long_options.append(long_opt);
}
if (opt.short_name) {
short_options_builder.append(opt.short_name);
if (opt.requires_argument)
short_options_builder.append(':');
}
}
long_options.append({ 0, 0, 0, 0 });
String short_options = short_options_builder.build();
while (true) {
int c = getopt_long(argc, argv, short_options.characters(), long_options.data(), nullptr);
if (c == -1) {
// We have reached the end.
break;
} else if (c == '?') {
// There was an error, and getopt() has already
// printed its error message.
print_usage_and_exit();
return false;
}
// Let's see what option we just found.
Option* found_option = nullptr;
if (c == 0) {
// It was a long option.
ASSERT(index_of_found_long_option >= 0);
found_option = &m_options[index_of_found_long_option];
index_of_found_long_option = -1;
} else {
// It was a short option, look it up.
auto it = m_options.find_if([c](auto& opt) { return c == opt.short_name; });
ASSERT(!it.is_end());
found_option = &*it;
}
ASSERT(found_option);
const char* arg = found_option->requires_argument ? optarg : nullptr;
if (!found_option->accept_value(arg)) {
warnln("\033[31mInvalid value for option \033[1m{}\033[22m, dude\033[0m", found_option->name_for_display());
print_usage_and_exit();
return false;
}
}
// We're done processing options, now let's parse positional arguments.
int values_left = argc - optind;
int num_values_for_arg[m_positional_args.size()];
int total_values_required = 0;
for (size_t i = 0; i < m_positional_args.size(); i++) {
auto& arg = m_positional_args[i];
num_values_for_arg[i] = arg.min_values;
total_values_required += arg.min_values;
}
if (total_values_required > values_left) {
print_usage_and_exit();
return false;
}
int extra_values_to_distribute = values_left - total_values_required;
for (size_t i = 0; i < m_positional_args.size(); i++) {
auto& arg = m_positional_args[i];
int extra_values_to_this_arg = min(arg.max_values - arg.min_values, extra_values_to_distribute);
num_values_for_arg[i] += extra_values_to_this_arg;
extra_values_to_distribute -= extra_values_to_this_arg;
if (extra_values_to_distribute == 0)
break;
}
if (extra_values_to_distribute > 0) {
// We still have too many values :(
print_usage_and_exit();
return false;
}
for (size_t i = 0; i < m_positional_args.size(); i++) {
auto& arg = m_positional_args[i];
for (int j = 0; j < num_values_for_arg[i]; j++) {
const char* value = argv[optind++];
if (!arg.accept_value(value)) {
warnln("Invalid value for argument {}", arg.name);
print_usage_and_exit();
return false;
}
}
}
// We're done parsing! :)
// Now let's show help if requested.
if (m_show_help) {
print_usage(stdout, argv[0]);
if (exit_on_failure)
exit(0);
return false;
}
return true;
}
void ArgsParser::print_usage(FILE* file, const char* argv0)
{
out(file, "Usage:\n\t\033[1m{}\033[0m", argv0);
for (auto& opt : m_options) {
if (opt.long_name && !strcmp(opt.long_name, "help"))
continue;
if (opt.requires_argument)
out(file, " [{} {}]", opt.name_for_display(), opt.value_name);
else
out(file, " [{}]", opt.name_for_display());
}
for (auto& arg : m_positional_args) {
bool required = arg.min_values > 0;
bool repeated = arg.max_values > 1;
if (required && repeated)
out(file, " <{}...>", arg.name);
else if (required && !repeated)
out(file, " <{}>", arg.name);
else if (!required && repeated)
out(file, " [{}...]", arg.name);
else if (!required && !repeated)
out(file, " [{}]", arg.name);
}
outln(file);
if (m_general_help != nullptr && m_general_help[0] != '\0') {
outln(file, "\nDescription:");
outln(file, m_general_help);
}
if (!m_options.is_empty())
outln(file, "\nOptions:");
for (auto& opt : m_options) {
auto print_argument = [&]() {
if (opt.value_name) {
if (opt.requires_argument)
out(file, " {}", opt.value_name);
else
out(file, " [{}]", opt.value_name);
}
};
out(file, "\t");
if (opt.short_name) {
out(file, "\033[1m-{}\033[0m", opt.short_name);
print_argument();
}
if (opt.short_name && opt.long_name)
out(file, ", ");
if (opt.long_name) {
out(file, "\033[1m--{}\033[0m", opt.long_name);
print_argument();
}
if (opt.help_string)
out(file, "\t{}", opt.help_string);
outln(file);
}
if (!m_positional_args.is_empty())
outln(file, "\nArguments:");
for (auto& arg : m_positional_args) {
out(file, "\t\033[1m{}\033[0m", arg.name);
if (arg.help_string)
out(file, "\t{}", arg.help_string);
outln(file);
}
}
void ArgsParser::add_option(Option&& option)
{
m_options.append(move(option));
}
void ArgsParser::add_option(bool& value, const char* help_string, const char* long_name, char short_name)
{
Option option {
false,
help_string,
long_name,
short_name,
nullptr,
[&value](const char* s) {
ASSERT(s == nullptr);
value = true;
return true;
}
};
add_option(move(option));
}
void ArgsParser::add_option(const char*& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
{
Option option {
true,
help_string,
long_name,
short_name,
value_name,
[&value](const char* s) {
value = s;
return true;
}
};
add_option(move(option));
}
void ArgsParser::add_option(int& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
{
Option option {
true,
help_string,
long_name,
short_name,
value_name,
[&value](const char* s) {
auto opt = StringView(s).to_int();
value = opt.value_or(0);
return opt.has_value();
}
};
add_option(move(option));
}
void ArgsParser::add_option(double& value, const char* help_string, const char* long_name, char short_name, const char* value_name)
{
Option option {
true,
help_string,
long_name,
short_name,
value_name,
[&value](const char* s) {
auto opt = convert_to_double(s);
value = opt.value_or(0.0);
return opt.has_value();
}
};
add_option(move(option));
}
void ArgsParser::add_positional_argument(Arg&& arg)
{
m_positional_args.append(move(arg));
}
void ArgsParser::add_positional_argument(const char*& value, const char* help_string, const char* name, Required required)
{
Arg arg {
help_string,
name,
required == Required::Yes ? 1 : 0,
1,
[&value](const char* s) {
value = s;
return true;
}
};
add_positional_argument(move(arg));
}
void ArgsParser::add_positional_argument(int& value, const char* help_string, const char* name, Required required)
{
Arg arg {
help_string,
name,
required == Required::Yes ? 1 : 0,
1,
[&value](const char* s) {
auto opt = StringView(s).to_int();
value = opt.value_or(0);
return opt.has_value();
}
};
add_positional_argument(move(arg));
}
void ArgsParser::add_positional_argument(double& value, const char* help_string, const char* name, Required required)
{
Arg arg {
help_string,
name,
required == Required::Yes ? 1 : 0,
1,
[&value](const char* s) {
auto opt = convert_to_double(s);
value = opt.value_or(0.0);
return opt.has_value();
}
};
add_positional_argument(move(arg));
}
void ArgsParser::add_positional_argument(Vector<const char*>& values, const char* help_string, const char* name, Required required)
{
Arg arg {
help_string,
name,
required == Required::Yes ? 1 : 0,
INT_MAX,
[&values](const char* s) {
values.append(s);
return true;
}
};
add_positional_argument(move(arg));
}
}
|