-
Notifications
You must be signed in to change notification settings - Fork 45
/
argagg.h
1705 lines (1424 loc) · 47.4 KB
/
argagg.h
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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* @file
* @brief
* Defines a very simple command line argument parser.
*
* @copyright
* Copyright (c) 2018 Viet The Nguyen
*
* @copyright
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* @copyright
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* @copyright
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#pragma once
#ifndef ARGAGG_ARGAGG_ARGAGG_HPP
#define ARGAGG_ARGAGG_ARGAGG_HPP
#ifdef __unix__
#include <stdio.h>
#include <unistd.h>
#endif // #ifdef __unix__
#include <algorithm>
#include <array>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <iterator>
#include <ostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
/**
* @brief
* There are only two hard things in Computer Science: cache invalidation and
* naming things (Phil Karlton).
*
* The names of types have to be succinct and clear. This has turned out to be
* a more difficult thing than I expected. Here you'll find a quick overview of
* the type names you'll find in this namespace (and thus "library").
*
* When a program is invoked it is passed a number of "command line arguments".
* Each of these "arguments" is a string (C-string to be more precise). An
* "option" is a command line argument that has special meaning. This library
* recognizes a command line argument as a potential option if it starts with a
* dash ('-') or double-dash ('--').
*
* A "parser" is a set of "definitions" (not a literal std::set but rather a
* std::vector). A parser is represented by the argagg::parser struct.
*
* A "definition" is a structure with four components that define what
* "options" are recognized. The four components are the name of the option,
* the strings that represent the option, the option's help text, and how many
* arguments the option should expect. "Flags" are the individual strings that
* represent the option ("-v" and "--verbose" are flags for the "verbose"
* option). A definition is represented by the argagg::definition struct.
*
* Note at this point that the word "option" can be used interchangeably to
* mean the notion of an option and the actual instance of an option given a
* set of command line arguments. To be unambiguous we use a "definition" to
* represent the notion of an option and an "option result" to represent an
* actual option parsed from a set of command line arguments. An "option
* result" is represented by the argagg::option_result struct.
*
* There's one more wrinkle to this: an option can show up multiple times in a
* given set of command line arguments. For example, "-n 1 -n 2 -n 3". This
* will parse into three distinct argagg::option_result instances, but all of
* them correspond to the same argagg::definition. We aggregate these into the
* argagg::option_results struct which represents "all parser results for a
* given option definition". This argagg::option_results is basically a
* std::vector of argagg::option_result.
*
* Options aren't the only thing parsed though. Positional arguments are also
* parsed. Thus a parser produces a result that contains both option results
* and positional arguments. The parser results are represented by the
* argagg::parser_results struct. All option results are stored in a mapping
* from option name to the argagg::option_results. All positional arguments are
* simply stored in a vector of C-strings.
*/
namespace argagg {
/**
* @brief
* This exception is thrown when a long option is parsed and is given an
* argument using the "=" syntax but the option doesn't expect an argument.
*/
struct unexpected_argument_error
: public std::runtime_error {
using std::runtime_error::runtime_error;
};
/**
* @brief
* This exception is thrown when an option is parsed unexpectedly such as when
* an argument was expected for a previous option or if an option was found
* that has not been defined.
*/
struct unexpected_option_error
: public std::runtime_error {
using std::runtime_error::runtime_error;
};
/**
* @brief
* This exception is thrown when an option requires an argument but is not
* provided one. This can happen if another flag was found after the option or
* if we simply reach the end of the command line arguments.
*/
struct option_lacks_argument_error
: public std::runtime_error {
using std::runtime_error::runtime_error;
};
/**
* @brief
* This exception is thrown when an option's flag is invalid. This can be the
* case if the flag is not prefixed by one or two hyphens or contains non
* alpha-numeric characters after the hypens. See is_valid_flag_definition()
* for more details.
*/
struct invalid_flag
: public std::runtime_error {
using std::runtime_error::runtime_error;
};
/**
* @brief
* This exception is thrown when an unknown option is requested by name from an
* argagg::parser_results through the indexing operator ([]).
*/
struct unknown_option
: public std::runtime_error {
using std::runtime_error::runtime_error;
};
/**
* @brief
* The set of template instantiations that convert C-strings to other types for
* the option_result::as(), option_results::as(), parser_results::as(), and
* parser_results::all_as() methods are placed in this namespace.
*/
namespace convert {
/**
* @brief
* Explicit instantiations of this function are used to convert arguments to
* types.
*/
template <typename T>
T arg(const char* arg);
/**
* @brief
* For simple types the main extension point for adding argument conversions
* is argagg::convert::arg<T>(). However, for complex types such as templated
* types partial specialization of a helper struct is required. This struct
* provides that extension point. The default, generic implementation of
* argagg::convert::arg<T>() calls converter<T>::convert().
*
* @see
* @ref argagg::csv
*/
template <typename T>
struct converter {
static T convert(const char* arg);
};
/**
* @brief
* A utility function for parsing an argument as a delimited list. To use,
* initialize a const char* pointer to the start of argument string. Then
* call parse_next_component(), providing that pointer, a mutable reference
* to where the parsed argument will go, and optionally the delimiting
* character. The argument string will be read up to the next delimiting
* character and then converted using
* <tt>argagg::convert::arg<decltype(out_arg)>()</tt>. The pointer is then
* incremented accordingly. If the delimiting character is no longer found
* then false is returned meaning that parsing the list can be considered
* finished.
*
* @code
#include <argagg/argagg.hpp>
struct position3 {
double x;
double y;
double z;
};
namespace argagg {
namespace convert {
template <>
position3 arg(const char* s)
{
position3 result {0.0, 0.0, 0.0};
if (!parse_next_component(s, result.x)) {
// could potentially throw an error if you require that at least two
// components exist in the list
return result;
}
if (!parse_next_component(s, result.y)) {
return result;
}
if (!parse_next_component(s, result.z)) {
return result;
}
return result;
}
} // namespace convert
} // namespace argagg
int main(int argc, char** argv)
{
argagg::parser argparser {{
{ "origin", {"-o", "--origin"},
"origin as position3 specifieid as a comma separated list of "
"components (e.g. '1,2,3')", 1},
}};
argagg::parser_results args = argparser.parse(argc, argv);
auto my_position = args["origin"].as<position3>();
// ...
return 0;
}
@endcode
*/
template <typename T>
bool parse_next_component(
const char*& s,
T& out_arg,
const char delim = ',');
}
/**
* @brief
* Represents a single option parse result.
*
* You can check if this has an argument by using the implicit boolean
* conversion.
*/
struct option_result {
/**
* @brief
* Argument parsed for this single option. If no argument was parsed this
* will be set to nullptr.
*/
const char* arg;
/**
* @brief
* Converts the argument parsed for this single option instance into the
* given type using the type matched conversion function
* argagg::convert::arg(). If there was not an argument parsed for this
* single option instance then a argagg::option_lacks_argument_error
* exception is thrown. The specific conversion function may throw other
* exceptions.
*/
template <typename T>
T as() const;
/**
* @brief
* Converts the argument parsed for this single option instance into the
* given type using the type matched conversion function
* argagg::convert::arg(). If there was not an argument parsed for this
* single option instance then the provided default value is returned
* instead. If the conversion function throws an exception then it is ignored
* and the default value is returned.
*/
template <typename T>
T as(const T& t) const;
/**
* @brief
* Since we have the argagg::option_result::as() API we might as well alias
* it as an implicit conversion operator. This performs implicit conversion
* using the argagg::option_result::as() method.
*
* @note
* An implicit boolean conversion specialization exists which returns false
* if there is no argument for this single option instance and true
* otherwise. This specialization DOES NOT convert the argument to a bool. If
* you need to convert the argument to a bool then use the as() API.
*/
template <typename T>
operator T () const;
/**
* @brief
* Explicitly define a unary not operator that wraps the implicit boolean
* conversion speciailization in case the compiler can't do it automatically.
*/
bool operator ! () const;
};
/**
* @brief
* Represents multiple option parse results for a single option. If treated as
* a single parse result it defaults to the last parse result. Note that an
* instance of this struct is always created even if no option results are
* parsed for a given definition. In that case it will simply be empty.
*
* To check if the associated option showed up at all simply use the implicit
* boolean conversion or check if count() is greater than zero.
*/
struct option_results {
/**
* @brief
* All option parse results for this option.
*/
std::vector<option_result> all;
/**
* @brief
* Gets the number of times the option shows up.
*/
std::size_t count() const;
/**
* @brief
* Gets a single option parse result by index.
*/
option_result& operator [] (std::size_t index);
/**
* @brief
* Gets a single option result by index.
*/
const option_result& operator [] (std::size_t index) const;
/**
* @brief
* Converts the argument parsed for the LAST option parse result for the
* parent definition to the provided type. For example, if this was for "-f 1
* -f 2 -f 3" then calling this method for an integer type will return 3. If
* there are no option parse results then a std::out_of_range exception is
* thrown. Any exceptions thrown by option_result::as() are not
* handled.
*/
template <typename T>
T as() const;
/**
* @brief
* Converts the argument parsed for the LAST option parse result for the
* parent definition to the provided type. For example, if this was for "-f 1
* -f 2 -f 3" then calling this method for an integer type will return 3. If
* there are no option parse results then the provided default value is
* returned instead.
*/
template <typename T>
T as(const T& t) const;
/**
* @brief
* Since we have the option_results::as() API we might as well alias
* it as an implicit conversion operator. This performs implicit conversion
* using the option_results::as() method.
*
* @note
* An implicit boolean conversion specialization exists which returns false
* if there is no argument for this single option instance and true
* otherwise. This specialization DOES NOT convert the argument to a bool. If
* you need to convert the argument to a bool then use the as() API.
*/
template <typename T>
operator T () const;
/**
* @brief
* Explicitly define a unary not operator that wraps the implicit boolean
* conversion speciailization in case the compiler can't do it automatically.
*/
bool operator ! () const;
};
/**
* @brief
* Represents all results of the parser including options and positional
* arguments.
*/
struct parser_results {
/**
* @brief
* Returns the name of the program from the original arguments list. This is
* always the first argument.
*/
const char* program;
/**
* @brief
* Maps from definition name to the structure which contains the parser
* results for that definition.
*/
std::unordered_map<std::string, option_results> options;
/**
* @brief
* Vector of positional arguments.
*/
std::vector<const char*> pos;
/**
* @brief
* Used to check if an option was specified at all.
*/
bool has_option(const std::string& name) const;
/**
* @brief
* Get the parser results for the given definition. If the definition never
* showed up then the exception from the unordered_map access will bubble
* through so check if the flag exists in the first place with has_option().
*/
option_results& operator [] (const std::string& name);
/**
* @brief
* Get the parser results for the given definition. If the definition never
* showed up then the exception from the unordered_map access will bubble
* through so check if the flag exists in the first place with has_option().
*/
const option_results& operator [] (const std::string& name) const;
/**
* @brief
* Gets the number of positional arguments.
*/
std::size_t count() const;
/**
* @brief
* Gets a positional argument by index.
*/
const char* operator [] (std::size_t index) const;
/**
* @brief
* Gets a positional argument converted to the given type.
*/
template <typename T>
T as(std::size_t i = 0) const;
/**
* @brief
* Gets all positional arguments converted to the given type.
*/
template <typename T>
std::vector<T> all_as() const;
};
/**
* @brief
* An option definition which essentially represents what an option is.
*/
struct definition {
/**
* @brief
* Name of the option. Option parser results are keyed by this name.
*/
const std::string name;
/**
* @brief
* List of strings to match that correspond to this option. Should be fully
* specified with hyphens (e.g. "-v" or "--verbose").
*/
std::vector<std::string> flags;
/**
* @brief
* Help string for this option.
*/
std::string help;
/**
* @brief
* Number of arguments this option requires. Must be 0 or 1. All other values
* have undefined behavior. Okay, the code actually works with positive
* values in general, but it's unorthodox command line behavior.
*/
unsigned int num_args;
/**
* @brief
* Returns true if this option does not want any arguments.
*/
bool wants_no_arguments() const;
/**
* @brief
* Returns true if this option requires arguments.
*/
bool requires_arguments() const;
};
/**
* @brief
* Checks whether or not a command line argument should be processed as an
* option flag. This is very similar to is_valid_flag_definition() but must
* allow for short flag groups (e.g. "-abc") and equal-assigned long flag
* arguments (e.g. "--output=foo.txt").
*/
bool cmd_line_arg_is_option_flag(
const char* s);
/**
* @brief
* Checks whether a flag in an option definition is valid. I suggest reading
* through the function source to understand what dictates a valid.
*/
bool is_valid_flag_definition(
const char* s);
/**
* @brief
* Tests whether or not a valid flag is short. Assumes the provided cstring is
* already a valid flag.
*/
bool flag_is_short(
const char* s);
/**
* @brief
* Contains two maps which aid in option parsing. The first map, @ref
* short_map, maps from a short flag (just a character) to a pointer to the
* original @ref definition that the flag represents. The second map, @ref
* long_map, maps from a long flag (an std::string) to a pointer to the
* original @ref definition that the flag represents.
*
* This object is usually a temporary that only exists during the parsing
* operation. It is typically constructed using @ref validate_definitions().
*/
struct parser_map {
/**
* @brief
* Maps from a short flag (just a character) to a pointer to the original
* @ref definition that the flag represents.
*/
std::array<const definition*, 256> short_map;
/**
* @brief
* Maps from a long flag (an std::string) to a pointer to the original @ref
* definition that the flag represents.
*/
std::unordered_map<std::string, const definition*> long_map;
/**
* @brief
* Returns true if the provided short flag exists in the map object.
*/
bool known_short_flag(
const char flag) const;
/**
* @brief
* If the short flag exists in the map object then it is returned by this
* method. If it doesn't then nullptr will be returned.
*/
const definition* get_definition_for_short_flag(
const char flag) const;
/**
* @brief
* Returns true if the provided long flag exists in the map object.
*/
bool known_long_flag(
const std::string& flag) const;
/**
* @brief
* If the long flag exists in the map object then it is returned by this
* method. If it doesn't then nullptr will be returned.
*/
const definition* get_definition_for_long_flag(
const std::string& flag) const;
};
/**
* @brief
* Validates a collection (specifically an std::vector) of @ref definition
* objects by checking if the contained flags are valid. If the set of @ref
* definition objects is not valid then an exception is thrown. Upon successful
* validation a @ref parser_map object is returned.
*/
parser_map validate_definitions(
const std::vector<definition>& definitions);
/**
* @brief
* A list of option definitions used to inform how to parse arguments.
*/
struct parser {
/**
* @brief
* Vector of the option definitions which inform this parser how to parse
* the command line arguments.
*/
std::vector<definition> definitions;
/**
* @brief
* Parses the provided command line arguments and returns the results as
* @ref parser_results.
*
* @note
* This method is not thread-safe and assumes that no modifications are made
* to the definitions member field during the extent of this method call.
*/
parser_results parse(int argc, const char** argv) const;
/**
* @brief
* Through strict interpretation of pointer casting rules, despite this being
* a safe operation, C++ doesn't allow implicit casts from <tt>char**</tt> to
* <tt>const char**</tt> so here's an overload that performs a const_cast,
* which is typically frowned upon but is safe here.
*/
parser_results parse(int argc, char** argv) const;
};
/**
* @brief
* A convenience output stream that will accumulate what is streamed to it and
* then, on destruction, format the accumulated string using the fmt program
* (via the argagg::fmt_string() function) to the provided std::ostream.
*
* Example use:
*
* @code
* {
* argagg::fmt_ostream f(std::cerr);
* f << "Usage: " << really_long_string << std::endl;
* } // on destruction here the formatted string will be streamed to std::cerr
* @endcode
*
* @note
* This only has formatting behavior if the <tt>__unix__</tt> preprocessor
* definition is defined since formatting relies on the POSIX API for forking,
* executing a process, and reading/writing to/from file descriptors. If that
* preprocessor definition is not defined then this class has the same overall
* behavior except the output string is not formatted (basically streams
* whatever the accumulated string is). See arggg::fmt_string().
*/
struct fmt_ostream : public std::ostringstream {
/**
* @brief
* Reference to the final output stream that the formatted string will be
* streamed to.
*/
std::ostream& output;
/**
* @brief
* Construct to output to the provided output stream when this object is
* destroyed.
*/
fmt_ostream(std::ostream& output);
/**
* @brief
* Special destructor that will format the accumulated string using fmt (via
* the argagg::fmt_string() function) and stream it to the std::ostream
* stored.
*/
~fmt_ostream();
};
/**
* @brief
* Processes the provided string using the fmt util and returns the resulting
* output as a string. Not the most efficient (in time or space) but gets the
* job done.
*
* This function is cowardly so if there are any errors encountered such as a
* syscall returning -1 then the input string is returned.
*
* @note
* This only has formatting behavior if the <tt>__unix__</tt> preprocessor
* definition is defined since it relies on the POSIX API for forking,
* executing a process, reading/writing to/from file descriptors, and the
* existence of the fmt util.
*/
std::string fmt_string(const std::string& s);
} // namespace argagg
/**
* @brief
* Writes the option help to the given stream.
*/
std::ostream& operator << (std::ostream& os, const argagg::parser& x);
// ---- end of declarations, header-only implementations follow ----
namespace argagg {
template <typename T>
T option_result::as() const
{
if (this->arg) {
return convert::arg<T>(this->arg);
} else {
throw option_lacks_argument_error("option has no argument");
}
}
template <typename T>
T option_result::as(const T& t) const
{
if (this->arg) {
try {
return convert::arg<T>(this->arg);
} catch (...) {
return t;
}
} else {
// I actually think this will never happen. To call this method you have
// to access a specific option_result for an option. If there's a
// specific option_result then the option was found. If the option
// requires an argument then it will definitely have an argument
// otherwise the parser would have complained.
return t;
}
}
template <typename T>
option_result::operator T () const
{
return this->as<T>();
}
template <> inline
option_result::operator bool () const
{
return this->arg != nullptr;
}
inline
bool option_result::operator ! () const
{
return !static_cast<bool>(*this);
}
inline
std::size_t option_results::count() const
{
return this->all.size();
}
inline
option_result& option_results::operator [] (std::size_t index)
{
return this->all[index];
}
inline
const option_result& option_results::operator [] (std::size_t index) const
{
return this->all[index];
}
template <typename T>
T option_results::as() const
{
if (this->all.size() == 0) {
throw std::out_of_range("no option arguments to convert");
}
return this->all.back().as<T>();
}
template <typename T>
T option_results::as(const T& t) const
{
if (this->all.size() == 0) {
return t;
}
return this->all.back().as<T>(t);
}
template <typename T>
option_results::operator T () const
{
return this->as<T>();
}
template <> inline
option_results::operator bool () const
{
return this->all.size() > 0;
}
inline
bool option_results::operator ! () const
{
return !static_cast<bool>(*this);
}
inline
bool parser_results::has_option(const std::string& name) const
{
const auto it = this->options.find(name);
return ( it != this->options.end()) && it->second.all.size() > 0;
}
inline
option_results& parser_results::operator [] (const std::string& name)
try {
return this->options.at(name);
} catch (const std::out_of_range& e) {
std::ostringstream msg;
msg << "no option named \"" << name << "\" in parser_results";
throw unknown_option(msg.str());
}
inline
const option_results&
parser_results::operator [] (const std::string& name) const
try {
return this->options.at(name);
} catch (const std::out_of_range& e) {
std::ostringstream msg;
msg << "no option named \"" << name << "\" in parser_results";
throw unknown_option(msg.str());
}
inline
std::size_t parser_results::count() const
{
return this->pos.size();
}
inline
const char* parser_results::operator [] (std::size_t index) const
{
return this->pos[index];
}
template <typename T>
T parser_results::as(std::size_t i) const
{
return convert::arg<T>(this->pos[i]);
}
template <typename T>
std::vector<T> parser_results::all_as() const
{
std::vector<T> v(this->pos.size());
std::transform(
this->pos.begin(), this->pos.end(), v.begin(),
[](const char* arg) {
return convert::arg<T>(arg);
});
return v;
}
inline
bool definition::wants_no_arguments() const
{
return this->num_args == 0;
}
inline
bool definition::requires_arguments() const
{
return this->num_args > 0;
}
inline
bool cmd_line_arg_is_option_flag(
const char* s)
{
auto len = std::strlen(s);
// The shortest possible flag has two characters: a hyphen and an
// alpha-numeric character.
if (len < 2) {
return false;
}
// All flags must start with a hyphen.
if (s[0] != '-') {
return false;
}
// Shift the name forward by a character to account for the initial hyphen.
// This means if s was originally "-v" then name will be "v".
const char* name = s + 1;
// Check if we're dealing with a long flag.
bool is_long = false;
if (s[1] == '-') {
is_long = true;
// Just -- is not a valid flag.
if (len == 2) {
return false;
}
// Shift the name forward to account for the extra hyphen. This means if s
// was originally "--output" then name will be "output".
name = s + 2;
}
// The first character of the flag name must be alpha-numeric. This is to
// prevent things like "---a" from being valid flags.
len = std::strlen(name);
if (!std::isalnum(name[0])) {
return false;
}
// At this point in is_valid_flag_definition() we would check if the short
// flag has only one character. At command line specification you can group
// short flags together or even add an argument to a short flag without a
// space delimiter. Thus we don't check if this has only one character
// because it might not.
// If this is a long flag then we expect all characters *up to* an equal sign
// to be alpha-numeric or a hyphen. After the equal sign you are specify the