-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathargparse.h
More file actions
2924 lines (2673 loc) · 118 KB
/
Copy pathargparse.h
File metadata and controls
2924 lines (2673 loc) · 118 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
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
/**
MIT License
Copyright(c) 2021 simfeo
Permission is hereby granted, free of charge, to any person obtaining a copy
of this softwareand 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 :
The above copyright noticeand this permission notice shall be included in all
copies or substantial portions of the Software.
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
// define your own macro ARGPARSE_NAMESPACE_NAME
// if you doesn't like default namespace "argparse"
#ifndef ARGPARSE_NAMESPACE_NAME
#define ARGPARSE_NAMESPACE_NAME argparse
#endif
#include <string>
#include <sstream>
#include <vector>
#include <tuple>
#include <map>
#include <algorithm>
#include <stdexcept>
#include <limits>
#include <initializer_list>
#include <functional>
#include <regex>
#include <cctype>
#if __cplusplus > 201402L || _MSVC_LANG > 201402L
#include <any>
// std::any is available from C++17. The spec structs expose an any-typed
// default_value only when it is present.
#define ARGPARSE_HAS_ANY 1
#endif
// std::filesystem is available from C++17. The path-existence validators
// (SetExistingFile / ...) are only compiled when it is present.
#if __cplusplus >= 201703L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
#include <filesystem>
#define ARGPARSE_HAS_FILESYSTEM 1
#endif
/// @brief namespace of argument parser constants and Classes
/// can be changed if ARGPARSE_NAMESPACE_NAME macro specified during compilation.
/// By default is namespace name is "argparse"
namespace ARGPARSE_NAMESPACE_NAME
{
/// @brief internal helpers. A named, inline namespace (rather than an
/// anonymous one) so the symbols have external linkage and get emitted in
/// module consumers; inline keeps #include across multiple TUs valid.
#ifdef __cpp_inline_variables
#define ARGPARSE_DETAIL_CONST inline constexpr
#else
#define ARGPARSE_DETAIL_CONST const
#endif
namespace detail
{
ARGPARSE_DETAIL_CONST size_t kSizeTypeEnd = static_cast<size_t>(-1);
ARGPARSE_DETAIL_CONST size_t kHelpWidth = 80;
ARGPARSE_DETAIL_CONST size_t kHelpNameWidthPercent = 30;
inline bool iEquals(const std::string& a, const std::string& b)
{
if (a.size() != b.size())
{
return false;
}
for (size_t i = 0; i < a.size(); ++i)
{
if (std::tolower(static_cast<unsigned char>(a[i]))
!= std::tolower(static_cast<unsigned char>(b[i])))
{
return false;
}
}
return true;
}
inline bool isNumber(const std::string& inStr)
{
const bool hasNegSign = inStr.at(0) == '-';
size_t dotPos = 0, expPos = 0;
size_t startPos = static_cast<size_t>(hasNegSign);
for (size_t curPos = startPos; curPos < inStr.size(); ++curPos)
{
const char curChar = inStr.at(curPos);
if (curChar >= '0' && curChar <= '9')
{
continue;
}
else if (curChar == '.'
&& !dotPos && curPos != startPos && curPos != inStr.size() - 1)
{
dotPos = curPos;
}
else if ((curChar == 'e' || curChar == 'E')
&& !expPos && curPos != startPos && curPos != inStr.size() - 1)
{
expPos = curPos;
if (!dotPos)
{
return false;
}
}
else
{
return false;
}
}
return true;
}
inline size_t getStringStreamLength(std::stringstream& showDesc)
{
showDesc.seekp(0, std::ios::end);
return showDesc.tellp();
}
}
using namespace detail;
#undef ARGPARSE_DETAIL_CONST
/// @brief Supported types for argument
/// If needed type is not in this list, then just use e_String
enum class ArgTypeCast : int
{
e_String,
e_int,
e_longlong,
e_double,
e_bool
};
// inline (external linkage) where available so the module wrapper can
// export them; plain const (internal linkage) otherwise. Behaviour for
// #include users is identical.
#ifdef __cpp_inline_variables
#define ARGPARSE_CONST inline constexpr
#else
#define ARGPARSE_CONST const
#endif
/// @brief constant to indicate arguments with various
/// count from 0 to infinite
ARGPARSE_CONST int kAnyArgCount = -1;
/// @brief constant to indicate arguments with various
/// count from 1 to infinite
ARGPARSE_CONST int kFromOneToInfiniteArgCount = -2;
/// @brief constant to indicate an argument that takes zero or one value
/// (Python's nargs='?').
ARGPARSE_CONST int kZeroOrOneArgCount = -3;
#undef ARGPARSE_CONST
/// @brief Argument count value. Accepts either an integer (an exact count,
/// or one of the k...ArgCount constants) or a Python-style character:
/// '?' (zero-or-one), '*' (zero-or-more), '+' (one-or-more).
/// Implicitly convertible to int so it can be used anywhere a plain count is
/// expected. An invalid character throws std::runtime_error at definition time.
struct NArgs
{
int value;
NArgs(int n = 1) : value(n) {}
NArgs(char c) : value(FromChar(c)) {}
operator int() const { return value; }
static int FromChar(char c)
{
switch (c)
{
case '?': return kZeroOrOneArgCount;
case '*': return kAnyArgCount;
case '+': return kFromOneToInfiniteArgCount;
default:
throw std::runtime_error(
std::string("invalid nargs character '") + c
+ "'; expected '?', '*' or '+'");
}
}
};
/// @brief Argument name value. Accepts a std::string, a string literal, or a
/// single char -- so a short name can be written as 'f' as well as "f".
/// Implicitly converts to std::string, so it works anywhere a name is taken.
struct ArgName
{
std::string value;
ArgName() {}
ArgName(char c) : value(1, c) {}
ArgName(const char* s) : value(s ? s : "") {}
ArgName(const std::string& s) : value(s) {}
operator const std::string&() const { return value; }
};
class ArgumentParser;
class ArgumentsObject;
class ArgumentParsed;
/// @brief This class represents argument configuration
/// which should be passed to ArgumentParser objects instance
class Argument
{
/// @brief Default constructor. Private!
/// @param positionalName represents name for positional argument.
/// @param shortName represents short name for named argument which should be passed with one prefix.
/// @param longName represents long name for named argument which should be passed with double prefix.
/// @param argsCount integer number. You can use "kAnyArgCount", "kFromOneToInfiniteArgCount" for non strict count or any int constant.
/// @param argType type of argument. Defined via enum. Supported types are: int, long long, double and bool and string for all other cases.
/// @param required Is argument required. Will fail parsing, if required argument are not present.
/// @param help Your own custom help string start.
/// @param predicate Optional value validator: returns true for an accepted
/// value token; nullptr (the default) installs no validator.
/// @param validatorMessage Error text used when @p predicate rejects a value
/// ("" uses a generated default message).
Argument(const std::string& positionalName = "",
const std::string& shortName = "",
const std::string& longName = "",
const int argsCount = 1,
ArgTypeCast argType = ArgTypeCast::e_String,
const bool required = true,
const std::string& help = "",
std::function<bool(const std::string&)> predicate = nullptr,
const std::string& validatorMessage = ""
)
: m_required(required)
, m_nargs(argsCount)
, m_type(argType)
, m_positionalName(positionalName)
, m_shortName(shortName)
, m_longName(longName)
, m_help(help)
, m_validator(predicate)
, m_validatorMessage(validatorMessage)
{}
public:
/// @brief Default constructor positional arguments. You can use class Setters or pass your own values to public members directly.
/// @param shortName represents short name for named argument which should be passed with one prefix.
/// @param longName represents long name for named argument which should be passed with double prefix.
/// @param argsCount integer number. You can use "kAnyArgCount", "kFromOneToInfiniteArgCount" for non strict count or any int constant.
/// @param argType type of argument. Defined via enum. Supported types are: int, long long, double and bool and string for all other cases.
/// @param required Is argument required. Will fail parsing, if required argument are not present.
/// @param help Your own custom help string start.
/// @param predicate Optional value validator: returns true for an accepted
/// value token; nullptr (the default) installs no validator.
/// @param validatorMessage Error text used when @p predicate rejects a value
/// ("" uses a generated default message).
static Argument CreateNamedArgument(const ArgName& shortName = "",
const ArgName& longName = "",
NArgs argsCount = 1,
ArgTypeCast argType = ArgTypeCast::e_String,
const bool required = true,
const std::string& help = "",
std::function<bool(const std::string&)> predicate = nullptr,
const std::string& validatorMessage = "")
{
return Argument("", shortName, longName, argsCount, argType, required, help, predicate, validatorMessage);
}
/// @brief Default function for named arguments. You can use class Setters or pass your own values to public members directly.
/// @param positionalName represents name for positional argument.
/// @param argsCount integer number. You can use "kAnyArgCount", "kFromOneToInfiniteArgCount" for non strict count or any int constant.
/// @param argType type of argument. Defined via enum. Supported types are: int, long long, double and bool and string for all other cases.
/// @param required Is argument required. Will fail parsing, if required argument are not present.
/// @param help Your own custom help string start.
/// @param predicate Optional value validator: returns true for an accepted
/// value token; nullptr (the default) installs no validator.
/// @param validatorMessage Error text used when @p predicate rejects a value
/// ("" uses a generated default message).
static Argument CreatePositionalArgument(const ArgName& positionalName = "",
NArgs argsCount = 1,
ArgTypeCast argType = ArgTypeCast::e_String,
const bool required = true,
const std::string& help = "",
std::function<bool(const std::string&)> predicate = nullptr,
const std::string& validatorMessage = "")
{
return Argument(positionalName, "", "", argsCount, argType, required, help, predicate, validatorMessage);
}
/// @brief required flag argument
/// If required argument is not set in command line
/// then parsing will fail.
///
/// IMPORTANT: ALL arguments -- named AND positional -- are REQUIRED by
/// default. This differs from Python's argparse, where named options are
/// optional by default. To make an argument optional call
/// SetRequired(false) (or pass required=false to the factory function).
/// Optional flags in particular almost always want SetRequired(false).
bool m_required = true;
/// @brief Setter function to flag,
/// @param required - bool value to indicate is argument required or not
/// @return reference to current argument
Argument& SetRequired(bool required)
{
m_required = required;
return *this;
}
/// @brief variable that indicates count of argument in input
/// use "kAnyArgCount" or "kFromOneToInfiniteArgCount" constants
/// for arguments with variable count. Any other arguments count
/// will be passed as strict arguments count.
/// 0 is for flags (arguments that doesn't carry any data)
/// set to 1 by default.
int m_nargs = 1;
/// @brief setter function for m_nargs with desired amount
/// @param amount argument count: an integer (exact count or a
/// k...ArgCount constant), or a Python-style character '?' / '*' / '+'.
/// @return reference to current argument
Argument& SetNumberOfArguments(NArgs amount)
{
m_nargs = amount;
return *this;
}
/// @brief Handy setter for an argument that takes zero or one value
/// (Python's nargs='?').
/// @return reference to current argument
Argument& SetZeroOrOneArgument()
{
m_nargs = kZeroOrOneArgCount;
return *this;
}
/// @brief Handy setter for argument count with self declared name
/// @return reference to current argument
Argument& SetAnyNumberOfArgumentsButAtLeastOne()
{
m_nargs = kFromOneToInfiniteArgCount;
return *this;
}
/// @brief Handy setter for argument count with self declared name
/// @return reference to current argument
Argument& SetAnyNumberOfArguments()
{
m_nargs = kAnyArgCount;
return *this;
}
/// @brief Handy setter for argument which is actually a flag (e.g. has no any parameters)
/// @return reference to current argument
Argument& SetArgumentIsFlag()
{
m_nargs = 0;
return *this;
}
/// @brief Variable that hold type of argument.
/// string by default
ArgTypeCast m_type = ArgTypeCast::e_String;
/// @brief Setter function for type of current argument
/// @param argType setter for type of current argument data.
/// Any non string types will be casted while parsing.
/// @return reference to current argument
Argument& SetType(ArgTypeCast argType)
{
m_type = argType;
return *this;
}
/// @brief name of positional argument
/// positional arguments name used only to access desired argument from code
std::string m_positionalName = "";
/// @brief Handy setter for positional argument
/// @param name name for positional argument. Empty by default
/// @return reference to current argument
Argument& SetPositionalName(const ArgName& name)
{
m_positionalName = name;
return *this;
}
/// @brief arguments short name
/// for non positional argument only
/// shot name used in input with 1 prefix
std::string m_shortName = "";
/// @brief Handy setter for short named argument.
/// Should been used with ordinary prefix in command line.
/// Can be auto-generated if possible when m_allowAbbrev in ArgumentParsed set to true.
/// @param name name for positional argument. Empty by default
/// @return reference to current argument
Argument& SetShortName(const ArgName& name)
{
m_shortName = name;
return *this;
}
/// @brief arguments long name.
/// for non positional arguments only
/// argument long name start with double prefix
std::string m_longName = "";
/// @brief Handy setter for long named argument.
/// Should been used with double prefix in command line.
/// Can be used for auto-generation of short name if it possible
/// and m_allowAbbrev in ArgumentParsed is "true".
/// @param name name for positional argument. Empty by default
/// @return reference to current argument
Argument& SetLongName(const ArgName& name)
{
m_longName = name;
return *this;
}
/// @brief additional help info for argument
/// Will be part of generated help
std::string m_help = "";
/// @brief Handy setter for additional help
/// @param help string with additional help. Empty by default.
/// @return reference to current argument
Argument& SetHelp(const std::string& help)
{
m_help = help;
return *this;
}
/// @brief vector of strings to validate arguments input data.
/// Empty by default. Will fail parsing if string not is in input list
std::vector<std::string> m_choicesString = {};
/// @brief when true, string choices are matched case-insensitively
bool m_choicesIgnoreCase = false;
/// @brief Handy setter of valid choices for arguments with string type
/// @param choices vector or initializer list of valid strings
/// @param ignoreCase match case-insensitively (false by default)
/// @return reference to current argument
Argument& SetChoices(const std::vector<std::string>& choices, bool ignoreCase = false)
{
if (m_type != ArgTypeCast::e_String)
{
throw std::runtime_error("wrong type");
}
m_choicesString = choices;
m_choicesIgnoreCase = ignoreCase;
return *this;
}
/// @brief Overload so a braced list of string literals -- e.g.
/// SetChoices({"+", "-"}) -- resolves unambiguously to the string
/// choices instead of colliding with the int/double/long long overloads.
/// @param choices initializer list of string literals
/// @param ignoreCase match case-insensitively (false by default)
/// @return reference to current argument
Argument& SetChoices(std::initializer_list<const char*> choices, bool ignoreCase = false)
{
return SetChoices(std::vector<std::string>(choices.begin(), choices.end()), ignoreCase);
}
/// @brief vector of integers to validate arguments input data.
/// Empty by default. Will fail parsing if ints not is in input list
std::vector<int> m_choicesInt = {};
/// @brief Handy setter of valid choices for arguments with int type
/// @param choices vector or initializer list of valid ints
/// @return reference to current argument
Argument& SetChoices(const std::vector<int>& choices)
{
if (m_type != ArgTypeCast::e_int)
{
throw std::runtime_error("wrong type");
}
m_choicesInt = choices;
return *this;
}
/// @brief vector of long longs to validate arguments input data.
/// Empty by default. Will fail parsing if long longs not is in input list
std::vector<long long> m_choicesLongLong = {};
/// @brief Handy setter of valid choices for arguments with long long type
/// @param choices vector or initializer list of valid long longs
/// @return reference to current argument
Argument& SetChoices(const std::vector<long long>& choices)
{
if (m_type != ArgTypeCast::e_longlong)
{
throw std::runtime_error("wrong type");
}
m_choicesLongLong = choices;
return *this;
}
/// @brief vector of double to validate arguments input data.
/// Empty by default. Will fail parsing if double not is in input list
std::vector<double> m_choicesDouble = {};
/// @brief Handy setter of valid choices for arguments with double type
/// @param choices vector or initializer list of valid double
/// @return reference to current argument
Argument& SetChoices(const std::vector<double>& choices)
{
if (m_type != ArgTypeCast::e_double)
{
throw std::runtime_error("wrong type");
}
m_choicesDouble = choices;
return *this;
}
/// @brief Handy setter for single default argument of bool type
/// @param defaultArg default boolean value
/// @return reference to current argument
Argument& SetDefault(bool defaultArg)
{
if (m_type != ArgTypeCast::e_bool)
{
throw std::runtime_error("wrong type");
}
m_defaultBool.push_back(defaultArg);
m_hasDefault = true;
return *this;
}
/// @brief Handy setter for single default argument of int type
/// @param defaultArg default int value
/// @return reference to current argument
Argument& SetDefault(int defaultArg)
{
if (m_type != ArgTypeCast::e_int)
{
throw std::runtime_error("wrong type");
}
m_defaultInt.push_back(defaultArg);
m_hasDefault = true;
return *this;
}
/// @brief Handy setter for single default argument of long long type
/// @param defaultArg default long long value
/// @return reference to current argument
Argument& SetDefault(long long defaultArg)
{
if (m_type != ArgTypeCast::e_longlong)
{
throw std::runtime_error("wrong type");
}
m_defaultLongLong.push_back(defaultArg);
m_hasDefault = true;
return *this;
}
/// @brief Handy setter for single default argument of double type
/// @param defaultArg default double value
/// @return reference to current argument
Argument& SetDefault(double defaultArg)
{
if (m_type != ArgTypeCast::e_double)
{
throw std::runtime_error("wrong type");
}
m_defaultDouble.push_back(defaultArg);
m_hasDefault = true;
return *this;
}
/// @brief Handy setter for single default argument of string type
/// @param defaultArg default string value
/// @return reference to current argument
Argument& SetDefault(std::string defaultArg)
{
if (m_type != ArgTypeCast::e_String)
{
throw std::runtime_error("wrong type");
}
m_defaultString.push_back(defaultArg);
m_hasDefault = true;
return *this;
}
/// @brief Handy setter for vector of default arguments of bool type
/// @param defaultArg vector of default boolean values
/// @return reference to current argument
Argument& SetDefault(const std::vector<bool>& defaultArg)
{
if (m_type != ArgTypeCast::e_bool)
{
throw std::runtime_error("wrong type");
}
m_defaultBool = defaultArg;
m_hasDefault = true;
return *this;
}
/// @brief Handy setter for vector of default arguments of int type
/// @param defaultArg vector of default int values
/// @return reference to current argument
Argument& SetDefault(const std::vector<int>& defaultArg)
{
if (m_type != ArgTypeCast::e_int)
{
throw std::runtime_error("wrong type");
}
m_defaultInt = defaultArg;
m_hasDefault = true;
return *this;
}
/// @brief Handy setter for vector of default arguments of long long type
/// @param defaultArg vector of default long values
/// @return reference to current argument
Argument& SetDefault(const std::vector<long long>& defaultArg)
{
if (m_type != ArgTypeCast::e_longlong)
{
throw std::runtime_error("wrong type");
}
m_defaultLongLong = defaultArg;
m_hasDefault = true;
return *this;
}
/// @brief Handy setter for vector of default arguments of double type
/// @param defaultArg vector of default double values
/// @return reference to current argument
Argument& SetDefault(const std::vector<double>& defaultArg)
{
if (m_type != ArgTypeCast::e_double)
{
throw std::runtime_error("wrong type");
}
m_defaultDouble = defaultArg;
m_hasDefault = true;
return *this;
}
/// @brief Handy setter for vector of default arguments of string type
/// @param defaultArg vector of default string values
/// @return reference to current argument
Argument& SetDefault(const std::vector<std::string>& defaultArg)
{
if (m_type != ArgTypeCast::e_String)
{
throw std::runtime_error("wrong type");
}
m_defaultString = defaultArg;
m_hasDefault = true;
return *this;
}
/// @brief Getter to indicate does argument has any default value
/// @return reference to current argument
bool HasDefault() const
{
return m_hasDefault;
}
/// @brief Bind a variable to this argument. After a successful
/// ParseArgs(), the parsed value is written directly into *target, so
/// you no longer have to pull it out with GetArg(name).GetAsX().
///
/// BindTo also sets this argument's type to match the bound variable,
/// so a separate SetType() call is not needed (and should not be used
/// to contradict it).
///
/// IMPORTANT: *target must outlive the ParseArgs() call. If the
/// argument is optional and absent (with no default), the bound
/// variable is left untouched -- initialize it yourself for a default.
/// @param target pointer to the variable that receives the parsed value
/// @return reference to current argument
Argument& BindTo(bool* target);
Argument& BindTo(int* target);
Argument& BindTo(long long* target);
Argument& BindTo(double* target);
Argument& BindTo(std::string* target);
Argument& BindTo(std::vector<bool>* target);
Argument& BindTo(std::vector<int>* target);
Argument& BindTo(std::vector<long long>* target);
Argument& BindTo(std::vector<double>* target);
Argument& BindTo(std::vector<std::string>* target);
/// @brief Does this argument have a bound variable (see BindTo)
/// @return true if BindTo(...) was called on this argument
bool HasBinding() const
{
return static_cast<bool>(m_binding);
}
/// @brief Apply the binding (if any) from a parsed result. Called by
/// ArgumentParser after a successful parse; a no-op when unbound.
/// @param parsed the parsed values for this argument
void ApplyBinding(const ArgumentParsed& parsed) const
{
if (m_binding)
{
m_binding(parsed);
}
}
/// @brief Install a validator: each parsed value token must satisfy
/// @p predicate, otherwise parsing fails. Runs on the raw value (so it
/// works for any type; convert inside the predicate if needed).
/// @param predicate returns true for an accepted value
/// @param message custom error text (a default is used when empty)
/// @return reference to current argument
Argument& SetValidator(std::function<bool(const std::string&)> predicate,
const std::string& message = "")
{
m_validator = std::move(predicate);
m_validatorMessage = message;
return *this;
}
/// @brief Whether a value passes this argument's validator (true if none).
bool RunValidator(const std::string& value) const
{
return !m_validator || m_validator(value);
}
/// @brief Custom validator error message ("" means use the default).
const std::string& ValidatorMessage() const
{
return m_validatorMessage;
}
/// @brief Restrict an integer argument to the inclusive range [lo, hi].
/// Sets the type to e_int and installs a validator.
Argument& SetRange(int lo, int hi)
{
m_type = ArgTypeCast::e_int;
return SetRangeLL(lo, hi);
}
/// @brief Restrict a long long argument to the inclusive range [lo, hi].
Argument& SetRange(long long lo, long long hi)
{
m_type = ArgTypeCast::e_longlong;
return SetRangeLL(lo, hi);
}
/// @brief Restrict a double argument to the inclusive range [lo, hi].
Argument& SetRange(double lo, double hi)
{
m_type = ArgTypeCast::e_double;
return SetValidator(
[lo, hi](const std::string& s) {
try { double v = std::stod(s); return v >= lo && v <= hi; }
catch (...) { return false; }
},
"value out of range [" + std::to_string(lo) + ", " + std::to_string(hi) + "]");
}
/// @brief Restrict an integer argument to [0, max].
Argument& SetRange(int max) { return SetRange(0, max); }
/// @brief Restrict a long long argument to [0, max].
Argument& SetRange(long long max) { return SetRange(0LL, max); }
/// @brief Restrict a double argument to [0, max].
Argument& SetRange(double max) { return SetRange(0.0, max); }
/// @brief Require a strictly positive number (> 0). Type-agnostic.
Argument& SetPositive(const std::string& message = "")
{
return SetValidator(
[](const std::string& s) {
try { return std::stod(s) > 0.0; } catch (...) { return false; }
},
message.empty() ? "value must be positive" : message);
}
/// @brief Require a non-negative number (>= 0). Type-agnostic.
Argument& SetNonNegative(const std::string& message = "")
{
return SetValidator(
[](const std::string& s) {
try { return std::stod(s) >= 0.0; } catch (...) { return false; }
},
message.empty() ? "value must be non-negative" : message);
}
/// @brief Require the value to fully match an ECMAScript regular
/// expression. An invalid pattern throws std::regex_error at definition.
Argument& SetPattern(const std::string& pattern, const std::string& message = "")
{
std::regex re(pattern);
return SetValidator(
[re](const std::string& s) { return std::regex_match(s, re); },
message.empty() ? ("value does not match pattern \"" + pattern + "\"") : message);
}
#ifdef ARGPARSE_HAS_FILESYSTEM
/// @brief Require the value to name an existing regular file (C++17+).
Argument& SetExistingFile(const std::string& message = "")
{
return SetValidator(
[](const std::string& s) {
std::error_code ec; return std::filesystem::is_regular_file(s, ec);
},
message.empty() ? "file does not exist" : message);
}
/// @brief Require the value to name an existing directory (C++17+).
Argument& SetExistingDirectory(const std::string& message = "")
{
return SetValidator(
[](const std::string& s) {
std::error_code ec; return std::filesystem::is_directory(s, ec);
},
message.empty() ? "directory does not exist" : message);
}
/// @brief Require the value to name an existing path (C++17+).
Argument& SetExistingPath(const std::string& message = "")
{
return SetValidator(
[](const std::string& s) {
std::error_code ec; return std::filesystem::exists(s, ec);
},
message.empty() ? "path does not exist" : message);
}
/// @brief Require the value to name a path that does NOT exist (C++17+).
Argument& SetNonexistentPath(const std::string& message = "")
{
return SetValidator(
[](const std::string& s) {
std::error_code ec; return !std::filesystem::exists(s, ec);
},
message.empty() ? "path already exists" : message);
}
#endif
private:
/// @brief Shared integer-range validator for SetRange(int) / SetRange(long long).
Argument& SetRangeLL(long long lo, long long hi)
{
return SetValidator(
[lo, hi](const std::string& s) {
try { long long v = std::stoll(s); return v >= lo && v <= hi; }
catch (...) { return false; }
},
"value out of range [" + std::to_string(lo) + ", " + std::to_string(hi) + "]");
}
/// @brief type-erased sink installed by BindTo(...); empty when unbound
std::function<void(const ArgumentParsed&)> m_binding = nullptr;
/// @brief value predicate installed by SetValidator(...); empty when unset
std::function<bool(const std::string&)> m_validator = nullptr;
std::string m_validatorMessage = "";
bool m_hasDefault = false;
std::vector<bool> m_defaultBool = {};
std::vector<int> m_defaultInt = {};
std::vector<long long> m_defaultLongLong = {};
std::vector<double> m_defaultDouble = {};
std::vector<std::string> m_defaultString = {};
friend ArgumentsObject;
};
/// @brief Helper function to create named argument
/// @param shortName Short name if needed. Will be used with single prefix.
/// Short name could be auto-generated if possible when m_allowAbbrev in ArgumentParsed set to true)
/// @param longName Full name of argument
/// @param argsCount Count of arguments
/// (use kFromOneToInfiniteArgCount or kAnyArgCount for various arguments count)
/// @param argType e_String, e_int, e_longlong, e_double, e_bool
/// @param required Marker if argument should be passed or ignored if missed.
/// @param help Initial part of help for current argument in case of auto-generated help.
/// @param predicate Optional value validator: returns true for an accepted
/// value token; nullptr (the default) installs no validator.
/// @param validatorMessage Error text used when @p predicate rejects a value
/// ("" uses a generated default message).
/// @return instance of Argument
/// @note inline: this is a free function in a header, so it must have
/// inline linkage to be safely included in more than one translation unit.
inline Argument CreateNamedArgument(const ArgName& shortName = "",
const ArgName& longName = "",
NArgs argsCount = 1,
ArgTypeCast argType = ArgTypeCast::e_String,
const bool required = true,
const std::string& help = "",
std::function<bool(const std::string&)> predicate = nullptr,
const std::string& validatorMessage = "")
{
return Argument::CreateNamedArgument(shortName, longName, argsCount, argType, required, help, predicate, validatorMessage);
}
/// @brief Helper function to create positional argument
/// @param positionalName Name of positional argument to access from code.
/// @param argsCount Count of arguments
/// (use kFromOneToInfiniteArgCount or kAnyArgCount for various arguments count)
/// @param argType e_String, e_int, e_longlong, e_double, e_bool
/// @param required Marker if argument should be passed or ignored if missed.
/// @param help Initial part of help for current argument in case of auto-generated help.
/// @param predicate Optional value validator: returns true for an accepted
/// value token; nullptr (the default) installs no validator.
/// @param validatorMessage Error text used when @p predicate rejects a value
/// ("" uses a generated default message).
/// @return instance of Argument
/// @note inline: see CreateNamedArgument -- required for multi-TU inclusion.
inline Argument CreatePositionalArgument(const ArgName& positionalName = "",
NArgs argsCount = 1,
ArgTypeCast argType = ArgTypeCast::e_String,
const bool required = true,
const std::string& help = "",
std::function<bool(const std::string&)> predicate = nullptr,
const std::string& validatorMessage = "")
{
return Argument::CreatePositionalArgument(positionalName, argsCount, argType, required, help, predicate, validatorMessage);
}
/// @brief Aggregate description of a named argument, for keyword-style
/// construction. Because it is a plain aggregate, C++20 designated
/// initializers give a Python-like call site:
/// @code
/// parser.AddArgument(argparse::CreateNamedArgument({
/// .longName = "numbers",
/// .nargs = argparse::kFromOneToInfiniteArgCount,
/// .type = argparse::ArgTypeCast::e_int,
/// .required = false,
/// .help = "some numbers",
/// .validator = [](const std::string&)->bool{ return false; },
/// .validator_message = "wrong input for numbers"}));
/// @endcode
/// The same struct also works with ordinary aggregate init in C++11/14/17.
struct NamedArgSpec
{
ArgName shortName = "";
ArgName longName = "";
NArgs nargs = 1;
ArgTypeCast type = ArgTypeCast::e_String;
bool required = true;
std::string help = "";
std::function<bool(const std::string&)> validator = nullptr;
std::string validator_message = "";
/// @brief allowed values, as strings; parsed to @ref type. Empty = no restriction.
std::vector<std::string> choices = {};
/// @brief regex the value must match (SetPattern). Empty = no pattern.
std::string pattern = "";
#ifdef ARGPARSE_HAS_ANY
/// @brief default value (C++17+); its stored type must match @ref type.
/// Empty = no default. Leave unset in C++11/14 and chain SetDefault instead.
std::any default_value{};
#endif
};
/// @brief Apply the choices/pattern/default_value spec fields to @p arg,
/// dispatching by @p type. Shared by the named and positional factories.
inline void ApplySpecExtras(Argument& arg, ArgTypeCast type,
const std::vector<std::string>& choices, const std::string& pattern
#ifdef ARGPARSE_HAS_ANY
, const std::any& defaultValue
#endif
)
{
if (!choices.empty())
{
switch (type)
{
case ArgTypeCast::e_String: arg.SetChoices(choices); break;
case ArgTypeCast::e_int:
{
std::vector<int> v; v.reserve(choices.size());
for (const std::string& s : choices) v.push_back(std::stoi(s));
arg.SetChoices(v); break;
}
case ArgTypeCast::e_longlong:
{
std::vector<long long> v; v.reserve(choices.size());
for (const std::string& s : choices) v.push_back(std::stoll(s));
arg.SetChoices(v); break;
}
case ArgTypeCast::e_double:
{
std::vector<double> v; v.reserve(choices.size());
for (const std::string& s : choices) v.push_back(std::stod(s));
arg.SetChoices(v); break;
}
case ArgTypeCast::e_bool:
throw std::runtime_error("choices are not supported for bool arguments");