CLI.hpp
42 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
#pragma once
// Distributed under the LGPL version 3.0 license. See accompanying
// file LICENSE or https://github.com/henryiii/CLI11 for details.
#include <string>
#include <memory>
#include <deque>
#include <iostream>
#include <functional>
#include <tuple>
#include <exception>
#include <stdexcept>
#include <algorithm>
#include <sstream>
#include <type_traits>
#include <set>
#include <iomanip>
#include <numeric>
#include <vector>
#include <locale>
// C standard library
// Only needed for existence checking
// Could be swapped for filesystem in C++17
#include <sys/types.h>
#include <sys/stat.h>
namespace CLI {
// Error definitions
struct Error : public std::runtime_error {
int exit_code;
bool print_help;
Error(std::string parent, std::string name, int exit_code=255, bool print_help=true) : runtime_error(parent + ": " + name), exit_code(exit_code), print_help(print_help) {}
};
struct Success : public Error {
Success() : Error("Success", "Successfully completed, should be caught and quit", 0, false) {}
};
struct CallForHelp : public Error {
CallForHelp() : Error("CallForHelp", "This should be caught in your main function, see examples", 0) {}
};
struct BadNameString : public Error {
BadNameString(std::string name) : Error("BadNameString", name, 1) {}
};
struct ParseError : public Error {
ParseError(std::string name) : Error("ParseError", name, 2) {}
};
struct OptionAlreadyAdded : public Error {
OptionAlreadyAdded(std::string name) : Error("OptionAlreadyAdded", name, 3) {}
};
struct OptionNotFound : public Error {
OptionNotFound(std::string name) : Error("OptionNotFound", name, 4) {}
};
struct RequiredError : public Error {
RequiredError(std::string name) : Error("RequiredError", name, 5) {}
};
struct PositionalError : public Error {
PositionalError(std::string name) : Error("PositionalError", name, 6) {}
};
struct HorribleError : public Error {
HorribleError(std::string name) : Error("HorribleError", "(You should never see this error) " + name, 7) {}
};
struct IncorrectConstruction : public Error {
IncorrectConstruction(std::string name) : Error("IncorrectConstruction", name, 8) {}
};
struct EmptyError : public Error {
EmptyError(std::string name) : Error("EmptyError", name, 9) {}
};
// Type tools
//
// Copied from C++14
#if __cplusplus < 201402L
template< bool B, class T = void >
using enable_if_t = typename std::enable_if<B,T>::type;
#else
using std::enable_if_t;
#endif
// If your compiler supports C++14, you can use that definition instead
template <typename T>
struct is_vector {
static const bool value = false;
};
template<class T, class A>
struct is_vector<std::vector<T, A> > {
static bool const value = true;
};
template <typename T>
struct is_bool {
static const bool value = false;
};
template<>
struct is_bool<bool> {
static bool const value = true;
};
namespace detail {
// Based generally on https://rmf.io/cxx11/almost-static-if
/// Simple empty scoped class
enum class enabler {};
/// An instance to use in EnableIf
constexpr enabler dummy = {};
/// Simple function to join a string
template <typename T>
std::string join(const T& v, std::string delim = ",") {
std::ostringstream s;
size_t start = 0;
for (const auto& i : v) {
if(start++ > 0)
s << delim;
s << i;
}
return s.str();
}
/// Was going to be based on
/// http://stackoverflow.com/questions/1055452/c-get-name-of-type-in-template
/// But this is cleaner and works better in this case
template<typename T,
enable_if_t<std::is_integral<T>::value && std::is_signed<T>::value, detail::enabler> = detail::dummy>
constexpr const char* type_name() {
return "INT";
}
template<typename T,
enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value, detail::enabler> = detail::dummy>
constexpr const char* type_name() {
return "UINT";
}
template<typename T,
enable_if_t<std::is_floating_point<T>::value, detail::enabler> = detail::dummy>
constexpr const char* type_name() {
return "FLOAT";
}
/// This one should not be used, since vector types print the internal type
template<typename T,
enable_if_t<is_vector<T>::value, detail::enabler> = detail::dummy>
constexpr const char* type_name() {
return "VECTOR";
}
template<typename T,
enable_if_t<!std::is_floating_point<T>::value && !std::is_integral<T>::value && !is_vector<T>::value
, detail::enabler> = detail::dummy>
constexpr const char* type_name() {
return "STRING";
}
void format_help(std::stringstream &out, std::string name, std::string discription, size_t wid) {
name = " " + name;
out << std::setw(wid) << std::left << name;
if(name.length()>=wid)
out << std::endl << std::setw(wid) << "";
out << discription << std::endl;
}
struct Combiner {
int num;
bool required;
bool defaulted;
std::vector<std::function<bool(std::string)>> validators;
/// Can be or-ed together
Combiner operator | (Combiner b) const {
Combiner self;
self.num = std::min(num, b.num) == -1 ? -1 : std::max(num, b.num);
self.required = required || b.required;
self.defaulted = defaulted || b.defaulted;
self.validators.reserve(validators.size() + b.validators.size());
self.validators.insert(self.validators.end(), validators.begin(), validators.end());
self.validators.insert(self.validators.end(), b.validators.begin(), b.validators.end());
return self;
}
/// Call to give the number of arguments expected on cli
Combiner operator() (int n) const {
Combiner self = *this;
self.num = n;
return self;
}
/// Call to give a validator
Combiner operator() (std::function<bool(std::string)> func) const {
Combiner self = *this;
self.validators.push_back(func);
return self;
}
};
bool _ExistingFile(std::string filename) {
// std::fstream f(name.c_str());
// return f.good();
// Fastest way according to http://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exist-using-standard-c-c11-c
struct stat buffer;
return (stat(filename.c_str(), &buffer) == 0);
}
bool _ExistingDirectory(std::string filename) {
struct stat buffer;
if(stat(filename.c_str(), &buffer) == 0 && (buffer.st_mode & S_IFDIR) )
return true;
return false;
}
bool _NonexistentPath(std::string filename) {
struct stat buffer;
return stat(filename.c_str(), &buffer) != 0;
}
template<typename T>
bool valid_first_char(T c) {
return std::isalpha(c) || c=='_';
}
template<typename T>
bool valid_later_char(T c) {
return std::isalnum(c) || c=='_' || c=='.' || c=='-';
}
inline bool valid_name_string(const std::string &str) {
if(str.size()<1 || !valid_first_char(str[0]))
return false;
for(auto c : str.substr(1))
if(!valid_later_char(c))
return false;
return true;
}
// Returns false if not a short option. Otherwise, sets opt name and rest and returns true
inline bool split_short(const std::string ¤t, std::string &name, std::string &rest) {
if(current.size()>1 && current[0] == '-' && valid_first_char(current[1])) {
name = current.substr(1,1);
rest = current.substr(2);
return true;
} else
return false;
}
// Returns false if not a long option. Otherwise, sets opt name and other side of = and returns true
inline bool split_long(const std::string ¤t, std::string &name, std::string &value) {
if(current.size()>2 && current.substr(0,2) == "--" && valid_first_char(current[2])) {
auto loc = current.find("=");
if(loc != std::string::npos) {
name = current.substr(2,loc-2);
value = current.substr(loc+1);
} else {
name = current.substr(2);
value = "";
}
return true;
} else
return false;
}
// Splits a string into multiple long and short names
inline std::vector<std::string> split_names(std::string current) {
std::vector<std::string> output;
size_t val;
while((val = current.find(",")) != std::string::npos) {
output.push_back(current.substr(0,val));
current = current.substr(val+1);
}
output.push_back(current);
return output;
}
inline std::tuple<std::vector<std::string>,std::vector<std::string>, std::string>
get_names(const std::vector<std::string> &input) {
std::vector<std::string> short_names;
std::vector<std::string> long_names;
std::string pos_name;
for(std::string name : input) {
if(name.length() == 0)
continue;
else if(name.length() > 1 && name[0] == '-' && name[1] != '-') {
if(name.length()==2 && valid_first_char(name[1]))
short_names.push_back(std::string(1,name[1]));
else
throw BadNameString("Invalid one char name: "+name);
} else if(name.length() > 2 && name.substr(0,2) == "--") {
name = name.substr(2);
if(valid_name_string(name))
long_names.push_back(name);
else
throw BadNameString("Bad long name: "+name);
} else if(name == "-" || name == "--") {
throw BadNameString("Must have a name, not just dashes");
} else {
if(pos_name.length() > 0)
throw BadNameString("Only one positional name allowed, remove: "+name);
pos_name = name;
}
}
return std::tuple<std::vector<std::string>,std::vector<std::string>, std::string>
(short_names, long_names, pos_name);
}
// Integers
template<typename T, enable_if_t<std::is_integral<T>::value, detail::enabler> = detail::dummy>
bool lexical_cast(std::string input, T& output) {
try{
output = (T) std::stoll(input);
return true;
} catch (std::invalid_argument) {
return false;
} catch (std::out_of_range) {
return false;
}
}
// Floats
template<typename T, enable_if_t<std::is_floating_point<T>::value, detail::enabler> = detail::dummy>
bool lexical_cast(std::string input, T& output) {
try{
output = (T) std::stold(input);
return true;
} catch (std::invalid_argument) {
return false;
} catch (std::out_of_range) {
return false;
}
}
// Vector
template<typename T,
enable_if_t<is_vector<T>::value, detail::enabler> = detail::dummy>
bool lexical_cast(std::string input, T& output) {
if(output.size() == input.size())
output.resize(input.size());
for(size_t i=0; i<input.size(); i++)
output[i] = input[i];
return true;
}
// String and similar
template<typename T,
enable_if_t<!std::is_floating_point<T>::value && !std::is_integral<T>::value && !is_vector<T>::value
, detail::enabler> = detail::dummy>
bool lexical_cast(std::string input, T& output) {
output = input;
return true;
}
}
// Defines for common Combiners (don't use combiners directly)
const detail::Combiner Nothing {0, false, false, {}};
const detail::Combiner Required {1, true, false, {}};
const detail::Combiner Default {1, false, true, {}};
const detail::Combiner Args {-1, false, false, {}};
const detail::Combiner Validators {1, false, false, {}};
// Warning about using these validators:
// The files could be added/deleted after the validation. This is not common,
// but if this is a possibility, check the file you open afterwards
const detail::Combiner ExistingFile {1, false, false, {detail::_ExistingFile}};
const detail::Combiner ExistingDirectory {1, false, false, {detail::_ExistingDirectory}};
const detail::Combiner NonexistentPath {1, false, false, {detail::_NonexistentPath}};
typedef std::vector<std::vector<std::string>> results_t;
typedef std::function<bool(results_t)> callback_t;
class App;
class Option {
friend App;
protected:
// Config
std::vector<std::string> snames;
std::vector<std::string> lnames;
std::string pname;
detail::Combiner opts;
std::string discription;
callback_t callback;
// These are for help strings
std::string defaultval;
std::string typeval;
// Results
results_t results {};
public:
Option(std::string name, std::string discription = "", detail::Combiner opts=Nothing, std::function<bool(results_t)> callback=[](results_t){return true;}) :
opts(opts), discription(discription), callback(callback){
std::tie(snames, lnames, pname) = detail::get_names(detail::split_names(name));
}
/// Clear the parsed results (mostly for testing)
void clear() {
results.clear();
}
/// True if option is required
bool required() const {
return opts.required;
}
/// The number of arguments the option expects
int expected() const {
return opts.num;
}
/// True if the argument can be given directly
bool positional() const {
return pname.length() > 0;
}
/// True if option has at least one non-positional name
bool nonpositional() const {
return (snames.size() + lnames.size()) > 0;
}
/// True if this should print the default string
bool defaulted() const {
return opts.defaulted;
}
/// True if option has discription
bool has_discription() const {
return discription.length() > 0;
}
/// Get the discription
const std::string& get_discription() const {
return discription;
}
/// The name and any extras needed for positionals
std::string help_positional() const {
std::string out = pname;
if(expected()<1)
out = out + "x" + std::to_string(expected());
else if(expected()==-1)
out = out + "...";
out = required() ? out : "["+out+"]";
return out;
}
// Just the pname
std::string get_pname() const {
return pname;
}
/// Process the callback
bool run_callback() const {
if(opts.validators.size()>0) {
for(const std::string & result : flatten_results())
for(const std::function<bool(std::string)> &vali : opts.validators)
if(!vali(result))
return false;
}
return callback(results);
}
/// If options share any of the same names, they are equal (not counting positional)
bool operator== (const Option& other) const {
for(const std::string &sname : snames)
for(const std::string &othersname : other.snames)
if(sname == othersname)
return true;
for(const std::string &lname : lnames)
for(const std::string &otherlname : other.lnames)
if(lname == otherlname)
return true;
return false;
}
/// Gets a , sep list of names. Does not include the positional name.
std::string get_name() const {
std::vector<std::string> name_list;
for(const std::string& sname : snames)
name_list.push_back("-"+sname);
for(const std::string& lname : lnames)
name_list.push_back("--"+lname);
return detail::join(name_list);
}
/// Check a name. Requires "-" or "--" for short / long, supports positional name
bool check_name(std::string name) const {
if(name.length()>2 && name.substr(0,2) == "--")
return check_lname(name.substr(2));
else if (name.length()>1 && name.substr(0,1) == "-")
return check_sname(name.substr(1));
else
return name == pname;
}
/// Requires "-" to be removed from string
bool check_sname(const std::string& name) const {
return std::find(std::begin(snames), std::end(snames), name) != std::end(snames);
}
/// Requires "--" to be removed from string
bool check_lname(const std::string& name) const {
return std::find(std::begin(lnames), std::end(lnames), name) != std::end(lnames);
}
/// Puts a result at position r
void add_result(int r, std::string s) {
results.at(r).push_back(s);
}
/// Starts a new results vector (used for r in add_result)
int get_new() {
results.emplace_back();
return results.size() - 1;
}
/// Count the total number of times an option was passed
int count() const {
int out = 0;
for(const std::vector<std::string>& v : results)
out += v.size();
return out;
}
/// Diagnostic representation
std::string string() const {
std::string val = "Option: " + get_name() + "\n"
+ " " + discription + "\n"
+ " [";
for(const auto& item : results) {
if(&item!=&results[0])
val+="],[";
val += detail::join(item);
}
val += "]";
return val;
}
/// The first half of the help print, name plus default, etc
std::string help_name() const {
std::stringstream out;
out << get_name();
if(expected() != 0) {
if(typeval != "")
out << " " << typeval;
if(defaultval != "")
out << "=" << defaultval;
if(expected() > 1)
out << " x " << expected();
if(expected() == -1)
out << " ...";
}
return out.str();
}
/// Produce a flattened vector of results, vs. a vector of vectors.
std::vector<std::string> flatten_results() const {
std::vector<std::string> output;
for(const std::vector<std::string> result : results)
output.insert(std::end(output), std::begin(result), std::end(result));
return output;
}
};
enum class Classifer {NONE, POSITIONAL_MARK, SHORT, LONG, SUBCOMMAND};
// Prototype return value test
template <typename T>
class Value {
friend App;
protected:
std::shared_ptr<std::unique_ptr<T>> value {new std::unique_ptr<T>()};
std::string name;
public:
Value(std::string name) : name(name) {}
operator bool() const {return (bool) *value;}
T& get() const {
if(*value)
return **value;
else
throw EmptyError(name);
}
/// Note this does not throw on assignment, though
/// afterwards it seems to work fine. Best to use
/// explicit * notation.
T& operator *() const {
return get();
}
};
/// Creates a command line program, with very few defaults.
/** To use, create a new Program() instance with argc, argv, and a help description. The templated
* add_option methods make it easy to prepare options. Remember to call `.start` before starting your
* program, so that the options can be evaluated and the help option doesn't accidentally run your program. */
class App {
protected:
std::string name;
std::string prog_discription;
std::vector<Option> options;
std::vector<std::string> missing_options;
std::deque<std::string> positionals;
std::vector<std::unique_ptr<App>> subcommands;
bool parsed{false};
App* subcommand = nullptr;
std::string progname = "program";
std::function<void()> app_callback;
public:
/// Set a callback for the end of parsing. Due to a bug in c++11,
/// it is not possible to overload on std::function (fixed in c++14
/// and backported to c++11 on newer compilers). Use capture by reference
/// to get a pointer to App if needed.
App* set_callback(std::function<void()> callback) {
app_callback = callback;
return this;
}
void run_callback() {
if(app_callback)
app_callback();
}
/// Reset the parsed data
void reset() {
parsed = false;
subcommand = nullptr;
for(Option& opt : options) {
opt.clear();
}
for(std::unique_ptr<App> &app : subcommands) {
app->reset();
}
}
/// Create a new program. Pass in the same arguments as main(), along with a help string.
App(std::string prog_discription="")
: prog_discription(prog_discription) {
add_flag("-h,--help", "Print this help message and exit");
}
App* add_subcommand(std::string name, std::string discription="") {
subcommands.emplace_back(new App(discription));
subcommands.back()->name = name;
return subcommands.back().get();
}
//------------ ADD STYLE ---------//
/// Add an option, will automatically understand the type for common types.
/** To use, create a variable with the expected type, and pass it in after the name.
* After start is called, you can use count to see if the value was passed, and
* the value will be initialized properly.
*
* Program::Required, Program::Default, and the validators are options, and can be `|`
* together. The positional options take an optional number of arguments.
*
* For example,
*
* std::string filename
* program.add_option("filename", filename, "discription of filename");
*/
Option* add_option(
std::string name,
callback_t callback,
std::string discription="",
detail::Combiner opts=Validators
) {
Option myopt{name, discription, opts, callback};
if(std::find(std::begin(options), std::end(options), myopt) == std::end(options))
options.push_back(myopt);
else
throw OptionAlreadyAdded(myopt.get_name());
return &options.back();
}
/// Add option for string
template<typename T, enable_if_t<!is_vector<T>::value, detail::enabler> = detail::dummy>
Option* add_option(
std::string name,
T &variable, ///< The variable to set
std::string discription="",
detail::Combiner opts=Validators
) {
if(opts.num!=1)
throw IncorrectConstruction("Must have Args(1) or be a vector.");
CLI::callback_t fun = [&variable](CLI::results_t res){
if(res.size()!=1) {
return false;
}
if(res[0].size()!=1) {
return false;
}
return detail::lexical_cast(res[0][0], variable);
};
Option* retval = add_option(name, fun, discription, opts);
retval->typeval = detail::type_name<T>();
if(opts.defaulted) {
std::stringstream out;
out << variable;
retval->defaultval = out.str();
}
return retval;
}
/// Add option for vector of results
template<typename T>
Option* add_option(
std::string name,
std::vector<T> &variable, ///< The variable vector to set
std::string discription="",
detail::Combiner opts=Args
) {
if(opts.num==0)
throw IncorrectConstruction("Must have Args or be a vector.");
CLI::callback_t fun = [&variable](CLI::results_t res){
bool retval = true;
variable.clear();
for(const auto &a : res)
for(const auto &b : a) {
variable.emplace_back();
retval &= detail::lexical_cast(b, variable.back());
}
return variable.size() > 0 && retval;
};
Option* retval = add_option(name, fun, discription, opts);
retval->typeval = detail::type_name<T>();
if(opts.defaulted) {
retval->defaultval = "[" + detail::join(variable) + "]";
}
return retval;
}
/// Multiple options are supported
template<typename T, typename... Args>
Option* add_option(
std::string name,
T &variable, ///< The variable to set
std::string discription,
detail::Combiner opts,
detail::Combiner opts2,
Args... args ///< More options
) {
return add_option(name, variable, discription, opts|opts2, args...);
}
/// Add option for flag
Option* add_flag(
std::string name,
std::string discription=""
) {
CLI::callback_t fun = [](CLI::results_t){
return true;
};
Option* opt = add_option(name, fun, discription, Nothing);
if(opt->positional())
throw IncorrectConstruction("Flags cannot be positional");
return opt;
}
/// Add option for flag
template<typename T,
enable_if_t<std::is_integral<T>::value && !is_bool<T>::value, detail::enabler> = detail::dummy>
Option* add_flag(
std::string name,
T &count, ///< A varaible holding the count
std::string discription=""
) {
count = 0;
CLI::callback_t fun = [&count](CLI::results_t res){
count = (T) res.size();
return true;
};
Option* opt = add_option(name, fun, discription, Nothing);
if(opt->positional())
throw IncorrectConstruction("Flags cannot be positional");
return opt;
}
/// Bool version only allows the flag once
template<typename T,
enable_if_t<is_bool<T>::value, detail::enabler> = detail::dummy>
Option* add_flag(
std::string name,
T &count, ///< A varaible holding true if passed
std::string discription=""
) {
count = false;
CLI::callback_t fun = [&count](CLI::results_t res){
count = true;
return res.size() == 1;
};
Option* opt = add_option(name, fun, discription, Nothing);
if(opt->positional())
throw IncorrectConstruction("Flags cannot be positional");
return opt;
}
/// Add set of options
template<typename T>
Option* add_set(
std::string name,
T &member, ///< The selected member of the set
std::set<T> options, ///< The set of posibilities
std::string discription="",
detail::Combiner opts=Validators
) {
if(opts.num!=1)
throw IncorrectConstruction("Must have Args(1).");
CLI::callback_t fun = [&member, options](CLI::results_t res){
if(res.size()!=1) {
return false;
}
if(res[0].size()!=1) {
return false;
}
bool retval = detail::lexical_cast(res[0][0], member);
if(!retval)
return false;
return std::find(std::begin(options), std::end(options), member) != std::end(options);
};
Option* retval = add_option(name, fun, discription, opts);
retval->typeval = detail::type_name<T>();
retval->typeval += " in {" + detail::join(options) + "}";
if(opts.defaulted) {
std::stringstream out;
out << member;
retval->defaultval = out.str();
}
return retval;
}
template<typename T, typename... Args>
Option* add_set(
std::string name,
T &member,
std::set<T> options, ///< The set of posibilities
std::string discription,
detail::Combiner opts,
detail::Combiner opts2,
Args... args
) {
return add_set(name, member, options, discription, opts|opts2, args...);
}
//------------ MAKE STYLE ---------//
/// Prototype for new output style
template<typename T = std::string,
enable_if_t<!is_vector<T>::value, detail::enabler> = detail::dummy>
Value<T> make_option(
std::string name,
std::string discription="",
detail::Combiner opts=Validators
) {
if(opts.num!=1)
throw IncorrectConstruction("Must have Args(1).");
Value<T> out(name);
std::shared_ptr<std::unique_ptr<T>> ptr = out.value;
CLI::callback_t fun = [ptr](CLI::results_t res){
if(res.size()!=1) {
return false;
}
if(res[0].size()!=1) {
return false;
}
ptr->reset(new T()); // resets the internal ptr
return detail::lexical_cast(res[0][0], **ptr);
};
Option* retval = add_option(name, fun, discription, opts);
retval->typeval = detail::type_name<T>();
return out;
}
template<typename T = std::string, typename... Args>
Value<T> make_option(
std::string name,
std::string discription,
detail::Combiner opts,
detail::Combiner opts2,
Args... args
) {
return make_option(name, discription, opts|opts2, args...);
}
/// Prototype for new output style with default
template<typename T,
enable_if_t<!is_vector<T>::value, detail::enabler> = detail::dummy>
Value<T> make_option(
std::string name,
const T& default_value,
std::string discription="",
detail::Combiner opts=Validators
) {
if(opts.num!=1)
throw IncorrectConstruction("Must have Args(1).");
Value<T> out(name);
std::shared_ptr<std::unique_ptr<T>> ptr = out.value;
ptr->reset(new T(default_value)); // resets the internal ptr
CLI::callback_t fun = [ptr](CLI::results_t res){
if(res.size()!=1) {
return false;
}
if(res[0].size()!=1) {
return false;
}
ptr->reset(new T()); // resets the internal ptr
return detail::lexical_cast(res[0][0], **ptr);
};
Option* retval = add_option(name, fun, discription, opts);
retval->typeval = detail::type_name<T>();
std::stringstream ot;
ot << default_value;
retval->defaultval = ot.str();
return out;
}
/// Prototype for new output style, vector
template<typename T,
enable_if_t<is_vector<T>::value, detail::enabler> = detail::dummy>
Value<T> make_option(
std::string name,
std::string discription="",
detail::Combiner opts=Args
) {
if(opts.num==0)
throw IncorrectConstruction("Must have Args or be a vector.");
Value<T> out(name);
std::shared_ptr<std::unique_ptr<T>> ptr = out.value;
CLI::callback_t fun = [ptr](CLI::results_t res){
ptr->reset(new T()); // resets the internal ptr
bool retval = true;
for(const auto &a : res)
for(const auto &b : a) {
(*ptr)->emplace_back();
retval &= detail::lexical_cast(b, (*ptr)->back());
}
return (*ptr)->size() > 0 && retval;
};
Option* retval = add_option(name, fun, discription, opts);
retval->typeval = detail::type_name<T>();
return out;
}
template<typename T, typename... Args>
Value<T> make_option(
std::string name,
const T& default_value,
std::string discription,
detail::Combiner opts,
detail::Combiner opts2,
Args... args
) {
return make_option(name, default_value, discription, opts|opts2, args...);
}
/// Prototype for new output style: flag
Value<int> make_flag(
std::string name,
std::string discription=""
) {
Value<int> out(name);
std::shared_ptr<std::unique_ptr<int>> ptr = out.value;
ptr->reset(new int()); // resets the internal ptr
**ptr = 0;
CLI::callback_t fun = [ptr](CLI::results_t res){
**ptr = (int) res.size();
return true;
};
Option* opt = add_option(name, fun, discription, Nothing);
if(opt->positional())
throw IncorrectConstruction("Flags cannot be positional");
return out;
}
/// Add set of options
template<typename T>
Value<T> make_set(
std::string name,
std::set<T> options, ///< The set of posibilities
std::string discription="",
detail::Combiner opts=Validators
) {
Value<T> out(name);
std::shared_ptr<std::unique_ptr<T>> ptr = out.value;
if(opts.num!=1)
throw IncorrectConstruction("Must have Args(1).");
CLI::callback_t fun = [ptr, options](CLI::results_t res){
if(res.size()!=1) {
return false;
}
if(res[0].size()!=1) {
return false;
}
ptr->reset(new T());
bool retval = detail::lexical_cast(res[0][0], **ptr);
if(!retval)
return false;
return std::find(std::begin(options), std::end(options), **ptr) != std::end(options);
};
Option* retval = add_option(name, fun, discription, opts);
retval->typeval = detail::type_name<T>();
retval->typeval += " in {" + detail::join(options) + "}";
return out;
}
template<typename T, typename... Args>
Value<T> make_set(
std::string name,
std::set<T> options,
std::string discription,
detail::Combiner opts,
detail::Combiner opts2,
Args... args
) {
return make_set(name, options, discription, opts|opts2, args...);
}
/// This allows subclasses to inject code before callbacks but after parse
virtual void pre_callback() {}
/// Parses the command line - throws errors
void parse(int argc, char **argv) {
progname = argv[0];
std::vector<std::string> args;
for(int i=argc-1; i>0; i--)
args.push_back(argv[i]);
parse(args);
}
void parse(std::vector<std::string> & args) {
parsed = true;
bool positional_only = false;
while(args.size()>0) {
Classifer classifer = positional_only ? Classifer::NONE : _recognize(args.back());
switch(classifer) {
case Classifer::POSITIONAL_MARK:
args.pop_back();
positional_only = true;
break;
case Classifer::SUBCOMMAND:
_parse_subcommand(args);
break;
case Classifer::LONG:
_parse_long(args);
break;
case Classifer::SHORT:
_parse_short(args);
break;
case Classifer::NONE:
positionals.push_back(args.back());
args.pop_back();
}
}
if (count("--help") > 0) {
throw CallForHelp();
}
for(Option& opt : options) {
while (opt.positional() && opt.count() < opt.expected() && positionals.size() > 0) {
opt.get_new();
opt.add_result(0, positionals.front());
positionals.pop_front();
}
if (opt.required() && opt.count() < opt.expected())
throw RequiredError(opt.get_name());
if (opt.count() > 0) {
if(!opt.run_callback())
throw ParseError(opt.get_name());
}
}
if(positionals.size()>0)
throw PositionalError("[" + detail::join(positionals) + "]");
pre_callback();
run_callback();
}
void _parse_subcommand(std::vector<std::string> &args) {
for(std::unique_ptr<App> &com : subcommands) {
if(com->name == args.back()){
args.pop_back();
com->parse(args);
subcommand = com.get();
return;
}
}
throw HorribleError("Subcommand");
}
void _parse_short(std::vector<std::string> &args) {
std::string current = args.back();
std::string name;
std::string rest;
if(!detail::split_short(current, name, rest))
throw HorribleError("Short");
args.pop_back();
auto op = std::find_if(std::begin(options), std::end(options), [name](const Option &v){return v.check_sname(name);});
if(op == std::end(options)) {
missing_options.push_back("-" + name);
return;
}
int vnum = op->get_new();
int num = op->expected();
if(num == 0)
op->add_result(vnum, "");
else if(rest!="") {
if (num > 0)
num--;
op->add_result(vnum, rest);
rest = "";
}
if(num == -1) {
while(args.size()>0 && _recognize(args.back()) == Classifer::NONE) {
op->add_result(vnum, args.back());
args.pop_back();
}
} else while(num>0 && args.size() > 0) {
num--;
std::string current = args.back();
args.pop_back();
op->add_result(vnum,current);
}
if(rest != "") {
rest = "-" + rest;
args.push_back(rest);
}
}
Classifer _recognize(std::string current) const {
std::string dummy1, dummy2;
if(current == "--")
return Classifer::POSITIONAL_MARK;
for(const std::unique_ptr<App> &com : subcommands) {
if(com->name == current)
return Classifer::SUBCOMMAND;
}
if(detail::split_long(current, dummy1, dummy2))
return Classifer::LONG;
if(detail::split_short(current, dummy1, dummy2))
return Classifer::SHORT;
return Classifer::NONE;
}
void _parse_long(std::vector<std::string> &args) {
std::string current = args.back();
std::string name;
std::string value;
if(!detail::split_long(current, name, value))
throw HorribleError("Long");
args.pop_back();
auto op = std::find_if(std::begin(options), std::end(options), [name](const Option &v){return v.check_lname(name);});
if(op == std::end(options)) {
missing_options.push_back("--" + name);
return;
}
int vnum = op->get_new();
int num = op->expected();
if(value != "") {
if(num!=-1) num--;
op->add_result(vnum, value);
} else if (num == 0) {
op->add_result(vnum, "");
}
if(num == -1) {
while(args.size() > 0 && _recognize(args.back()) == Classifer::NONE) {
op->add_result(vnum, args.back());
args.pop_back();
}
} else while(num>0 && args.size()>0) {
num--;
op->add_result(vnum,args.back());
args.pop_back();
}
return;
}
/// This must be called after the options are in but before the rest of the program.
/** Instead of throwing erros, this gives an error code
* if -h or an invalid option is passed. Continue with your program if returns -1 */
void run(int argc, char** argv) {
parse(argc, argv);
}
int exit(const Error& e) const {
if(e.exit_code != 0) {
std::cerr << "ERROR: ";
std::cerr << e.what() << std::endl;
if(e.print_help)
std::cerr << help();
} else {
if(e.print_help)
std::cout << help();
}
return e.exit_code;
}
/// Counts the number of times the given option was passed.
int count(std::string name) const {
for(const Option &opt : options) {
if(opt.check_name(name)) {
return opt.count();
}
}
throw OptionNotFound(name);
}
std::string help(size_t wid=30) const {
std::stringstream out;
if(name != "")
out << "Subcommand: " << name << " ";
out << prog_discription << std::endl;
out << "Usage: " << progname;
// Check for options
bool npos = false;
for(const Option &opt : options) {
if(opt.nonpositional()) {
npos = true;
break;
}
}
if(npos)
out << " [OPTIONS...]";
// Positionals
bool pos=false;
for(const Option &opt : options)
if(opt.positional()) {
out << " " << opt.help_positional();
if(opt.has_discription())
pos=true;
}
out << std::endl << std::endl;
// Positional discriptions
if(pos) {
out << "Positionals:" << std::endl;
for(const Option &opt : options)
if(opt.positional() && opt.has_discription())
detail::format_help(out, opt.get_pname(), opt.get_discription(), wid);
out << std::endl;
}
// Options
if(npos) {
out << "Options:" << std::endl;
for(const Option &opt : options) {
if(opt.nonpositional())
detail::format_help(out, opt.help_name(), opt.get_discription(), wid);
}
out << std::endl;
}
// Subcommands
if(subcommands.size()> 0) {
out << "Subcommands:" << std::endl;
for(const std::unique_ptr<App> &com : subcommands)
detail::format_help(out, com->get_name(), com->prog_discription, wid);
}
return out.str();
}
App* get_subcommand() {
return subcommand;
}
std::string get_name() const {
return name;
}
};
}