-
Notifications
You must be signed in to change notification settings - Fork 44
/
cmdparser.hpp
628 lines (504 loc) · 15.8 KB
/
cmdparser.hpp
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
/*
This file is part of the C++ CmdParser utility.
Copyright (c) 2015 - 2019 Florian Rappl
*/
#pragma once
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
#include <sstream>
#include <functional>
namespace cli {
/// Class used to wrap integer types to specify desired numerical base for specific argument parsing
template <typename T, int numericalBase = 0> class NumericalBase {
public:
/// This constructor required for correct AgrumentCountChecker initialization
NumericalBase() : value(0), base(numericalBase) {}
/// This constructor required for default value initialization
/// \param val comes from default value
NumericalBase(T val) : value(val), base(numericalBase) {}
operator T () const {
return this->value;
}
operator T * () {
return this->value;
}
T value;
unsigned int base;
};
struct CallbackArgs {
const std::vector<std::string>& arguments;
std::ostream& output;
std::ostream& error;
};
class Parser {
private:
class CmdBase {
public:
explicit CmdBase(const std::string& name, const std::string& alternative, const std::string& description, bool required, bool dominant, bool variadic) :
name(name),
command(name.size() > 0 ? "-" + name : ""),
alternative(alternative.size() > 0 ? "--" + alternative : ""),
description(description),
required(required),
handled(false),
arguments({}),
dominant(dominant),
variadic(variadic) {
}
virtual ~CmdBase() {
}
std::string name;
std::string command;
std::string alternative;
std::string description;
bool required;
bool handled;
std::vector<std::string> arguments;
bool const dominant;
bool const variadic;
virtual std::string print_value() const = 0;
virtual bool parse(std::ostream& output, std::ostream& error) = 0;
bool is(const std::string& given) const {
return given == command || given == alternative;
}
};
template<typename T>
struct ArgumentCountChecker
{
static constexpr bool Variadic = false;
};
template<typename T>
struct ArgumentCountChecker<cli::NumericalBase<T>>
{
static constexpr bool Variadic = false;
};
template<typename T>
struct ArgumentCountChecker<std::vector<T>>
{
static constexpr bool Variadic = true;
};
template<typename T>
class CmdFunction final : public CmdBase {
public:
explicit CmdFunction(const std::string& name, const std::string& alternative, const std::string& description, bool required, bool dominant) :
CmdBase(name, alternative, description, required, dominant, ArgumentCountChecker<T>::Variadic) {
}
virtual bool parse(std::ostream& output, std::ostream& error) {
try {
CallbackArgs args { arguments, output, error };
value = callback(args);
return true;
} catch (...) {
return false;
}
}
virtual std::string print_value() const {
return "";
}
std::function<T(CallbackArgs&)> callback;
T value;
};
template<typename T>
class CmdArgument final : public CmdBase {
public:
explicit CmdArgument(const std::string& name, const std::string& alternative, const std::string& description, bool required, bool dominant) :
CmdBase(name, alternative, description, required, dominant, ArgumentCountChecker<T>::Variadic) {
}
virtual bool parse(std::ostream&, std::ostream&) {
try {
value = Parser::parse(arguments, value);
return true;
} catch (...) {
return false;
}
}
virtual std::string print_value() const {
return stringify(value);
}
T value;
};
static int parse(const std::vector<std::string>& elements, const int&, int numberBase = 0) {
if (elements.size() != 1)
throw std::bad_cast();
return std::stoi(elements[0], 0, numberBase);
}
static bool parse(const std::vector<std::string>& elements, const bool& defval) {
if (elements.size() != 0)
throw std::runtime_error("A boolean command line parameter cannot have any arguments.");
return !defval;
}
static double parse(const std::vector<std::string>& elements, const double&) {
if (elements.size() != 1)
throw std::bad_cast();
return std::stod(elements[0]);
}
static float parse(const std::vector<std::string>& elements, const float&) {
if (elements.size() != 1)
throw std::bad_cast();
return std::stof(elements[0]);
}
static long double parse(const std::vector<std::string>& elements, const long double&) {
if (elements.size() != 1)
throw std::bad_cast();
return std::stold(elements[0]);
}
static unsigned int parse(const std::vector<std::string>& elements, const unsigned int&, int numberBase = 0) {
if (elements.size() != 1)
throw std::bad_cast();
return static_cast<unsigned int>(std::stoul(elements[0], 0, numberBase));
}
static unsigned long parse(const std::vector<std::string>& elements, const unsigned long&, int numberBase = 0) {
if (elements.size() != 1)
throw std::bad_cast();
return std::stoul(elements[0], 0, numberBase);
}
static unsigned long long parse(const std::vector<std::string>& elements, const unsigned long long&, int numberBase = 0) {
if (elements.size() != 1)
throw std::bad_cast();
return std::stoull(elements[0], 0, numberBase);
}
static long long parse(const std::vector<std::string>& elements, const long long&, int numberBase = 0) {
if (elements.size() != 1)
throw std::bad_cast();
return std::stoll(elements[0], 0, numberBase);
}
static long parse(const std::vector<std::string>& elements, const long&, int numberBase = 0) {
if (elements.size() != 1)
throw std::bad_cast();
return std::stol(elements[0], 0, numberBase);
}
static std::string parse(const std::vector<std::string>& elements, const std::string&) {
if (elements.size() != 1)
throw std::bad_cast();
return elements[0];
}
template<class T>
static std::vector<T> parse(const std::vector<std::string>& elements, const std::vector<T>&) {
const T defval = T();
std::vector<T> values { };
std::vector<std::string> buffer(1);
for (const auto& element : elements) {
buffer[0] = element;
values.push_back(parse(buffer, defval));
}
return values;
}
template <typename T> static T parse(const std::vector<std::string>& elements, const NumericalBase<T>& wrapper) {
return parse(elements, wrapper.value, 0);
}
/// Specialization for number wrapped into numerical base
/// \tparam T base type of the argument
/// \tparam base numerical base
/// \param elements
/// \param wrapper
/// \return parsed number
template <typename T, int base> static T parse(const std::vector<std::string>& elements, const NumericalBase<T, base>& wrapper) {
return parse(elements, wrapper.value, wrapper.base);
}
template<class T>
static std::string stringify(const T& value) {
return std::to_string(value);
}
template<class T, int base>
static std::string stringify(const NumericalBase<T, base>& wrapper) {
return std::to_string(wrapper.value);
}
template<class T>
static std::string stringify(const std::vector<T>& values) {
std::stringstream ss { };
ss << "[ ";
for (const auto& value : values) {
ss << stringify(value) << " ";
}
ss << "]";
return ss.str();
}
static std::string stringify(const std::string& str) {
return str;
}
public:
template<typename T>
class ArgumentPromise
{
public:
explicit ArgumentPromise(CmdArgument<T> *cmd)
: cmd_(cmd){ }
T get() const { return cmd_->value;}
private:
CmdArgument<T> * cmd_;
};
explicit Parser(int argc, const char** argv) {
init(argc, argv);
}
explicit Parser(int argc, char** argv) {
init(argc, argv);
}
Parser(int argc, const char** argv, std::string generalProgramDescriptionForHelpText) :
_general_help_text(std::move(generalProgramDescriptionForHelpText)) {
init(argc, argv);
}
Parser(int argc, char** argv, std::string generalProgramDescriptionForHelpText) :
_general_help_text(std::move(generalProgramDescriptionForHelpText)) {
init(argc, argv);
}
Parser() {}
Parser(std::string generalProgramDescriptionForHelpText) :
_general_help_text(std::move(generalProgramDescriptionForHelpText)) {}
~Parser() {
for (size_t i = 0, n = _commands.size(); i < n; ++i) {
delete _commands[i];
}
}
void init(int argc, char** argv) {
_appname = argv[0];
for (int i = 1; i < argc; ++i) {
_arguments.push_back(argv[i]);
}
enable_help();
}
void init(int argc, const char** argv) {
_appname = argv[0];
for (int i = 1; i < argc; ++i) {
_arguments.push_back(argv[i]);
}
enable_help();
}
bool has_help() const {
for (const auto& command : _commands) {
if (command->name == "h" && command->alternative == "--help") {
return true;
}
}
return false;
}
void enable_help() {
set_callback("h", "help", std::function<bool(CallbackArgs&)>([this](CallbackArgs& args){
args.output << this->usage();
#pragma warning(push)
#pragma warning(disable: 4702)
exit(0);
return false;
#pragma warning(pop)
}), "", true);
}
void disable_help() {
for (auto command = _commands.begin(); command != _commands.end(); ++command) {
if ((*command)->name == "h" && (*command)->alternative == "--help") {
_commands.erase(command);
delete *command;
break;
}
}
}
template<typename T>
ArgumentPromise<T> set_default(bool is_required, const std::string& description = "", T defaultValue = T()) {
auto command = new CmdArgument<T> { "", "", description, is_required, false };
command->value = defaultValue;
_commands.push_back(command);
return ArgumentPromise<T>(command);
}
template<typename T>
ArgumentPromise<T> set_required(const std::string& name, const std::string& alternative, const std::string& description = "", bool dominant = false) {
auto command = new CmdArgument<T> { name, alternative, description, true, dominant };
_commands.push_back(command);
return ArgumentPromise<T>(command);
}
template<typename T>
ArgumentPromise<T> set_optional(const std::string& name, const std::string& alternative, T defaultValue, const std::string& description = "", bool dominant = false) {
auto command = new CmdArgument<T> { name, alternative, description, false, dominant };
command->value = defaultValue;
_commands.push_back(command);
return ArgumentPromise<T>(command);
}
template<typename T>
void set_callback(const std::string& name, const std::string& alternative, std::function<T(CallbackArgs&)> callback, const std::string& description = "", bool dominant = false) {
auto command = new CmdFunction<T> { name, alternative, description, false, dominant };
command->callback = callback;
_commands.push_back(command);
}
inline void run_and_exit_if_error() {
if (run() == false) {
exit(1);
}
}
inline bool run() {
return run(std::cout, std::cerr);
}
inline bool run(std::ostream& output) {
return run(output, std::cerr);
}
bool doesArgumentExist(std::string name, std::string altName)
{
for (const auto& argument : _arguments) {
if(argument == '-'+ name || argument == altName)
{
return true;
}
}
return false;
}
inline bool doesHelpExist()
{
return doesArgumentExist("h", "--help");
}
bool run(std::ostream& output, std::ostream& error) {
if (_arguments.size() > 0) {
auto current = find_default();
for (size_t i = 0, n = _arguments.size(); i < n; ++i) {
auto isarg = _arguments[i].size() > 0 && _arguments[i][0] == '-';
auto associated = isarg ? find(_arguments[i]) : nullptr;
if (associated != nullptr) {
current = associated;
associated->handled = true;
} else if (current == nullptr) {
error << no_default();
return false;
} else {
current->arguments.push_back(_arguments[i]);
current->handled = true;
if (!current->variadic)
{
// If the current command is not variadic, then no more arguments
// should be added to it. In this case, switch back to the default
// command.
current = find_default();
}
}
}
}
// First, parse dominant arguments since they succeed even if required
// arguments are missing.
for (auto command : _commands) {
if (command->handled && command->dominant && !command->parse(output, error)) {
error << howto_use(command);
return false;
}
}
// Next, check for any missing arguments.
for (auto command : _commands) {
if (command->required && !command->handled) {
error << howto_required(command);
return false;
}
}
// Finally, parse all remaining arguments.
for (auto command : _commands) {
if (command->handled && !command->dominant && !command->parse(output, error)) {
error << howto_use(command);
return false;
}
}
return true;
}
template<typename T>
T get(const std::string& name) const {
for (const auto& command : _commands) {
if (command->name == name) {
auto cmd = dynamic_cast<CmdArgument<T>*>(command);
if (cmd == nullptr) {
throw std::runtime_error("Invalid usage of the parameter " + name + " detected.");
}
return cmd->value;
}
}
throw std::runtime_error("The parameter " + name + " could not be found.");
}
template<typename T>
T get_default() const {
return get<T>("");
}
template<typename T>
T get_if(const std::string& name, std::function<T(T)> callback) const {
auto value = get<T>(name);
return callback(value);
}
int requirements() const {
int count = 0;
for (const auto& command : _commands) {
if (command->required) {
++count;
}
}
return count;
}
int commands() const {
return static_cast<int>(_commands.size());
}
inline const std::string& app_name() const {
return _appname;
}
protected:
CmdBase* find(const std::string& name) {
for (auto command : _commands) {
if (command->is(name)) {
return command;
}
}
return nullptr;
}
CmdBase* find_default() {
for (auto command : _commands) {
if (command->name == "") {
return command;
}
}
return nullptr;
}
std::string usage() const {
std::stringstream ss { };
ss << _general_help_text << "\n\n";
ss << "Available parameters:\n\n";
for (const auto& command : _commands) {
ss << " " << command->command << "\t" << command->alternative;
if (command->required == true) {
ss << "\t(required)";
}
ss << "\n " << command->description;
if (command->required == false) {
ss << "\n " << "This parameter is optional. The default value is '" + command->print_value() << "'.";
}
ss << "\n\n";
}
return ss.str();
}
void print_help(std::stringstream& ss) const {
if (has_help()) {
ss << "For more help use --help or -h.\n";
}
}
std::string howto_required(CmdBase* command) const {
std::stringstream ss { };
ss << "The parameter " << command->name << " is required.\n";
ss << command->description << '\n';
print_help(ss);
return ss.str();
}
std::string howto_use(CmdBase* command) const {
std::stringstream ss { };
ss << "The parameter " << command->name << " has invalid arguments.\n";
ss << command->description << '\n';
print_help(ss);
return ss.str();
}
std::string no_default() const {
std::stringstream ss { };
ss << "No default parameter has been specified.\n";
ss << "The given argument must be used with a parameter.\n";
print_help(ss);
return ss.str();
}
const std::string &get_general_help_text() const {
return _general_help_text;
}
void set_general_help_text(const std::string &generalHelpText) {
_general_help_text = generalHelpText;
}
private:
std::string _appname;
std::string _general_help_text;
std::vector<std::string> _arguments;
std::vector<CmdBase*> _commands;
};
}