-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptparse.h
1362 lines (1141 loc) · 36.7 KB
/
optparse.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
/**
* Copyright (C) 2010 Johannes Weißl <[email protected]>
* License: your favourite BSD-style license
*/
#ifndef OPTPARSE_H
#define OPTPARSE_H
#include <algorithm>
#include <cstdlib>
#include <ciso646>
#include <complex>
#include <iostream>
#include <list>
#include <map>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
namespace optparse
{
class Callback;
class Option;
class OptionGroup;
class OptionParser;
// Class for automatic conversion from string -> anytype.
class Value
{
public:
Value() : str(), valid(false) {}
explicit Value(const std::string &v) : str(v), valid(true) {}
operator const char *()
{
return str.c_str();
}
operator bool()
{
bool t;
return (valid && (std::istringstream(str) >> t)) ? t : false;
}
operator short()
{
short t;
return (valid && (std::istringstream(str) >> t)) ? t : 0;
}
operator unsigned short()
{
unsigned short t;
return (valid && (std::istringstream(str) >> t)) ? t : 0;
}
operator int()
{
int t;
return (valid && (std::istringstream(str) >> t)) ? t : 0;
}
operator unsigned int()
{
unsigned int t;
return (valid && (std::istringstream(str) >> t)) ? t : 0;
}
operator long()
{
long t;
return (valid && (std::istringstream(str) >> t)) ? t : 0;
}
operator unsigned long()
{
unsigned long t;
return (valid && (std::istringstream(str) >> t)) ? t : 0;
}
operator float()
{
float t;
return (valid && (std::istringstream(str) >> t)) ? t : 0;
}
operator double()
{
double t;
return (valid && (std::istringstream(str) >> t)) ? t : 0;
}
operator long double()
{
long double t;
return (valid && (std::istringstream(str) >> t)) ? t : 0;
}
private:
const std::string str;
bool valid;
};
class Values
{
public:
Values() : _map() {}
const std::string &operator[](const std::string &d) const
{
std::map<std::string, std::string>::const_iterator it = _map.find(d);
static const std::string empty = "";
return (it != _map.end()) ? it->second : empty;
}
std::string &operator[](const std::string &d)
{
return _map[d];
}
bool is_set(const std::string &d) const
{
return _map.find(d) != _map.end();
}
bool is_set_by_user(const std::string &d) const
{
return _user_set.find(d) != _user_set.end();
}
void is_set_by_user(const std::string &d, bool yes)
{
if (yes)
{
_user_set.insert(d);
}
else
{
_user_set.erase(d);
}
}
Value get(const std::string &d) const
{
return (is_set(d)) ? Value((*this)[d]) : Value();
}
typedef std::vector<std::string>::iterator iterator;
typedef std::vector<std::string>::const_iterator const_iterator;
std::vector<std::string> &all(const std::string &d)
{
return _append_map[d];
}
const std::vector<std::string> all(const std::string &d) const
{
static const std::vector<std::string> empty;
return (_append_map.find(d) == _append_map.end()) ?
empty :
_append_map.at(d);
}
private:
std::map<std::string, std::string> _map;
std::map<std::string, std::vector<std::string> > _append_map;
std::set<std::string> _user_set;
};
namespace detail
{
class str_wrap
{
public:
str_wrap(const std::string &l, const std::string &r) : lwrap(l), rwrap(r) {}
explicit str_wrap(const std::string &w) : lwrap(w), rwrap(w) {}
std::string operator()(const std::string &s)
{
return lwrap + s + rwrap;
}
const std::string lwrap, rwrap;
};
template<typename InputIterator, typename UnaryOperator>
static std::string str_join_trans(const std::string &sep, InputIterator begin, InputIterator end, UnaryOperator op)
{
std::string buf;
for (InputIterator it = begin; it != end; ++it)
{
if (it != begin)
{
buf += sep;
}
buf += op(*it);
}
return buf;
}
template<class InputIterator>
static std::string str_join(const std::string &sep, InputIterator begin, InputIterator end)
{
return str_join_trans(sep, begin, end, str_wrap(""));
}
static std::string &str_replace_helper(std::string &s, const std::string &patt, const std::string &repl)
{
size_t pos = 0;
const size_t n = patt.length();
while (true)
{
pos = s.find(patt, pos);
if (pos == std::string::npos)
{
break;
}
s.replace(pos, n, repl);
pos += repl.size();
}
return s;
}
static std::string str_replace(const std::string &s, const std::string &patt, const std::string &repl)
{
std::string tmp = s;
str_replace_helper(tmp, patt, repl);
return tmp;
}
static std::string str_format(const std::string &s, size_t pre, size_t len, bool indent_first = true)
{
std::stringstream ss;
std::string p;
if (indent_first)
{
p = std::string(pre, ' ');
}
size_t pos = 0, linestart = 0;
size_t line = 0;
while (true)
{
bool wrap = false;
size_t new_pos = s.find_first_of(" \n\t", pos);
if (new_pos == std::string::npos)
{
break;
}
if (s[new_pos] == '\n')
{
pos = new_pos + 1;
wrap = true;
}
if (line == 1)
{
p = std::string(pre, ' ');
}
if (wrap or new_pos + pre > linestart + len)
{
ss << p << s.substr(linestart, pos - linestart - 1) << std::endl;
linestart = pos;
line++;
}
pos = new_pos + 1;
}
ss << p << s.substr(linestart) << std::endl;
return ss.str();
}
static std::string str_inc(const std::string &s)
{
std::stringstream ss;
long i = 0;
std::istringstream(s) >> i;
ss << i + 1;
return ss.str();
}
static unsigned int cols()
{
unsigned int n = 80;
#ifndef _WIN32
const char *s = getenv("COLUMNS");
if (s)
{
std::istringstream(s) >> n;
}
#endif
return n;
}
static std::string basename(const std::string &s)
{
const char seps[] =
#ifdef _WIN32
"/\\";
#else
"/";
#endif
std::string b = s;
size_t i = b.find_last_not_of(seps);
if (i == std::string::npos)
{
if (b[0] == '/')
{
b.erase(1);
}
return b;
}
b.erase(i + 1, b.length() - i - 1);
i = b.find_last_of(seps);
if (i != std::string::npos)
{
b.erase(0, i + 1);
}
return b;
}
static OptionParser &add_option_group_helper(OptionParser &parser,
const OptionGroup &group);
static Values &parse_args_helper(OptionParser &parser,
const std::vector<std::string> &v);
static std::string format_help_helper(const OptionParser &parser);
}
class Callback
{
public:
virtual void operator()(const Option &option,
const std::string &opt,
const std::string &val,
const OptionParser &parser) = 0;
virtual ~Callback() {}
};
class Option
{
public:
Option() : _action("store"), _type("string"), _nargs(1), _suppress_help(false), _callback(0) {}
Option &action(const std::string &a)
{
_action = a;
if (a == "store_const" or
a == "store_true" or
a == "store_false" or
a == "append_const" or
a == "count" or
a == "help" or
a == "version")
{
nargs(0);
}
return *this;
}
Option &type(const std::string &t)
{
_type = t;
return *this;
}
Option &dest(const std::string &d)
{
_dest = d;
return *this;
}
Option &set_default(const std::string &d)
{
_default = d;
return *this;
}
template<typename T>
Option &set_default(T t)
{
std::ostringstream ss;
ss << t;
_default = ss.str();
return *this;
}
Option &nargs(size_t n)
{
// This doesn't seem to be currently supported.
if (n > 1)
{
throw std::invalid_argument(
"nargs greater than 1 not supported");
}
_nargs = n;
return *this;
}
Option &set_const(const std::string &c)
{
_const = c;
return *this;
}
template<typename InputIterator>
Option &choices(InputIterator begin, InputIterator end)
{
_choices.assign(begin, end);
type("choice");
return *this;
}
Option &help(const std::string &h)
{
_help = h;
return *this;
}
Option &suppress_help(const bool suppress=true)
{
_suppress_help = suppress;
return *this;
}
Option &metavar(const std::string &m)
{
_metavar = m;
return *this;
}
Option &callback(Callback &c)
{
_callback = &c;
return *this;
}
const std::string &action() const
{
return _action;
}
const std::string &type() const
{
return _type;
}
const std::string &dest() const
{
return _dest;
}
const std::string &get_default() const
{
return _default;
}
size_t nargs() const
{
return _nargs;
}
const std::string &get_const() const
{
return _const;
}
const std::list<std::string> &choices() const
{
return _choices;
}
const std::string &help() const
{
return _help;
}
const std::string &metavar() const
{
return _metavar;
}
Callback *callback() const
{
return _callback;
}
private:
std::string check_type(const std::string &opt, const std::string &val) const
{
std::istringstream ss(val);
std::stringstream err;
if (type() == "int" or type() == "long")
{
long t;
if (not (ss >> t))
{
err << "option" << " " << opt << ": " << "invalid integer value" << ": '" << val << "'";
}
}
else if (type() == "float" or type() == "double")
{
double t;
if (not (ss >> t))
{
err << "option" << " " << opt << ": " << "invalid floating-point value" << ": '" << val << "'";
}
}
else if (type() == "choice")
{
if (find(choices().begin(), choices().end(), val) == choices().end())
{
std::list<std::string> tmp = choices();
std::transform(tmp.begin(), tmp.end(), tmp.begin(), detail::str_wrap("'"));
err << "option" << " " << opt << ": " << "invalid choice" << ": '" << val << "'"
<< " (" << "choose from" << " " << detail::str_join(", ", tmp.begin(), tmp.end()) << ")";
}
}
else if (type() == "complex")
{
std::complex<double> t;
if (not (ss >> t))
{
err << "option" << " " << opt << ": " << "invalid complex value" << ": '" << val << "'";
}
}
return err.str();
}
std::string format_option_help(const unsigned int indent=2) const
{
std::string mvar_short;
std::string mvar_long;
if (nargs() == 1)
{
std::string mvar = metavar();
if (mvar.empty())
{
mvar = type();
std::transform(mvar.begin(), mvar.end(), mvar.begin(), ::toupper);
}
mvar_short = " " + mvar;
mvar_long = "=" + mvar;
}
std::stringstream ss;
ss << std::string(indent, ' ');
if (not _short_opts.empty())
{
ss << detail::str_join_trans(", ", _short_opts.begin(), _short_opts.end(), detail::str_wrap("-", mvar_short));
if (not _long_opts.empty())
{
ss << ", ";
}
}
if (not _long_opts.empty())
{
ss << detail::str_join_trans(", ", _long_opts.begin(), _long_opts.end(), detail::str_wrap("--", mvar_long));
}
return ss.str();
}
std::string format_help(const unsigned int indent=2) const
{
std::stringstream ss;
std::string h = format_option_help(indent);
unsigned int width = detail::cols();
unsigned int opt_width = std::min(width * 3 / 10, 36u);
bool indent_first = false;
ss << h;
// If the option list is too long, start a new paragraph.
if (h.length() >= (opt_width - 1))
{
ss << std::endl;
indent_first = true;
}
else
{
ss << std::string(opt_width - h.length(), ' ');
if (help().empty())
ss << std::endl;
}
if (not help().empty())
{
std::string help_str = (not get_default().empty()) ? detail::str_replace(help(), "%default", get_default()) : help();
ss << detail::str_format(help_str, opt_width, width, indent_first);
}
return ss.str();
}
std::set<std::string> _short_opts;
std::set<std::string> _long_opts;
std::string _action;
std::string _type;
std::string _dest;
std::string _default;
size_t _nargs;
std::string _const;
std::list<std::string> _choices;
std::string _help;
bool _suppress_help;
std::string _metavar;
Callback *_callback;
friend class OptionParser;
friend OptionParser &detail::add_option_group_helper(
OptionParser &parser,
const OptionGroup &group);
};
class OptionParser
{
public:
OptionParser() :
_usage("%prog [options]"),
_add_help_option(true),
_add_version_option(true),
_interspersed_args(true)
{
}
virtual ~OptionParser()
{
}
OptionParser &usage(const std::string &u)
{
set_usage(u);
return *this;
}
OptionParser &version(const std::string &v)
{
_version = v;
return *this;
}
OptionParser &description(const std::string &d)
{
_description = d;
return *this;
}
OptionParser &add_help_option(bool h)
{
_add_help_option = h;
return *this;
}
OptionParser &add_version_option(bool v)
{
_add_version_option = v;
return *this;
}
OptionParser &prog(const std::string &p)
{
_prog = p;
return *this;
}
OptionParser &epilog(const std::string &e)
{
_epilog = e;
return *this;
}
OptionParser &set_defaults(const std::string &dest, const std::string &val)
{
_defaults[dest] = val;
return *this;
}
template<typename T>
OptionParser &set_defaults(const std::string &dest, T t)
{
std::ostringstream ss;
ss << t;
_defaults[dest] = ss.str();
return *this;
}
OptionParser &enable_interspersed_args()
{
_interspersed_args = true;
return *this;
}
OptionParser &disable_interspersed_args()
{
_interspersed_args = false;
return *this;
}
OptionParser &add_option_group(const OptionGroup &group)
{
return detail::add_option_group_helper(*this, group);
}
const std::string &usage() const
{
return _usage;
}
const std::string &version() const
{
return _version;
}
const std::string &description() const
{
return _description;
}
bool add_help_option() const
{
return _add_help_option;
}
bool add_version_option() const
{
return _add_version_option;
}
const std::string &prog() const
{
return _prog;
}
const std::string &epilog() const
{
return _epilog;
}
bool interspersed_args() const
{
return _interspersed_args;
}
Option &add_option(const std::vector<std::string> &opt)
{
_opts.resize(_opts.size() + 1);
Option &option = _opts.back();
std::string dest_fallback;
for (std::vector<std::string>::const_iterator it = opt.begin(); it != opt.end(); ++it)
{
if (it->substr(0, 2) == "--")
{
const std::string s = it->substr(2);
if (option.dest().empty())
option.dest(detail::str_replace(s, "-", "_"));
option._long_opts.insert(s);
_optmap_l[s] = &option;
}
else
{
const std::string s = it->substr(1, 1);
if (dest_fallback.empty())
dest_fallback = s;
option._short_opts.insert(s);
_optmap_s[s] = &option;
}
}
if (option.dest().empty())
{
option.dest(dest_fallback);
}
return option;
}
Option &add_option(const std::string &opt)
{
const std::string tmp[1] = {opt};
return add_option(std::vector<std::string>(tmp, tmp+1));
}
Option &add_option(const std::string &opt1, const std::string &opt2)
{
const std::string tmp[2] = {opt1, opt2};
return add_option(std::vector<std::string>(tmp, tmp+2));
}
Option &add_option(const std::string &opt1, const std::string &opt2, const std::string &opt3)
{
const std::string tmp[3] = {opt1, opt2, opt3};
return add_option(std::vector<std::string>(tmp, tmp+3));
}
Values &parse_args(int argc, char const *const *argv)
{
if (prog().empty())
{
prog(detail::basename(argv[0]));
}
return parse_args(&argv[1], &argv[argc]);
}
Values &parse_args(const std::vector<std::string> &arguments)
{
return detail::parse_args_helper(*this, arguments);
}
template<typename InputIterator>
Values &parse_args(InputIterator begin, InputIterator end)
{
return parse_args(std::vector<std::string>(begin, end));
}
const std::vector<std::string> &args() const
{
return _leftover;
}
std::string format_help() const
{
return detail::format_help_helper(*this);
}
std::string format_option_help(unsigned int indent=2) const
{
std::stringstream ss;
if (_opts.empty())
{
return ss.str();
}
for (std::list<Option>::const_iterator it = _opts.begin(); it != _opts.end(); ++it)
{
if (not it->_suppress_help)
{
ss << it->format_help(indent);
}
}
return ss.str();
}
void print_help() const
{
std::cout << format_help();
}
void set_usage(const std::string &u)
{
std::string lower = u;
std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
if (lower.compare(0, 7, "usage: ") == 0)
{
_usage = u.substr(7);
}
else
{
_usage = u;
}
}
std::string get_usage() const
{
return format_usage(detail::str_replace(usage(), "%prog", prog()));
}
void print_usage(std::ostream &out) const
{
std::string u = get_usage();
if (not u.empty())
{
out << u << std::endl;
}
}
void print_usage() const
{
print_usage(std::cout);
}
std::string get_version() const
{
return detail::str_replace(_version, "%prog", prog());
}
void print_version(std::ostream &out) const
{
out << get_version() << std::endl;
}
void print_version() const
{
print_version(std::cout);
}
virtual void error(const std::string &msg) const
{
print_usage(std::cerr);
std::cerr << prog() << ": " << "error" << ": " << msg << std::endl;
exit(2);
}
virtual void exit(int code) const
{
std::exit(code);
}
private:
const Option &lookup_short_opt(const std::string &opt) const
{
std::map<std::string, Option const *>::const_iterator it = _optmap_s.find(opt);
if (it == _optmap_s.end())
{
error("no such option" + std::string(": -") + opt);
static const Option empty;
return empty;
}
return *it->second;
}
const Option &lookup_long_opt(const std::string &opt) const
{
std::vector<std::string> matching;
for (std::map<std::string, Option const *>::const_iterator it = _optmap_l.begin(); it != _optmap_l.end(); ++it)
{
if (it->first == opt)
{
matching.push_back(it->first);
}
}
if (matching.size() > 1)
{
std::string x = detail::str_join(", ", matching.begin(), matching.end());
error("ambiguous option" + std::string(": --") + opt + " (" + x + "?)");
}
if (matching.size() == 0)
{
error("no such option" + std::string(": --") + opt);
static const Option empty;
return empty;
}
return *_optmap_l.find(matching.front())->second;
}
void handle_short_opt(const std::string &opt, const std::string &arg)
{
_remaining.pop_front();
std::string value;
const Option &option = lookup_short_opt(opt);
if (option._nargs == 1)