forked from helibproject/argmap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathargmap.h
996 lines (852 loc) · 28.3 KB
/
argmap.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
/* Copyright (C) 2012-2020 IBM Corp.
* This program is Licensed under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. See accompanying LICENSE file.
*/
// Copyright (C) 2023 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
// - Addition of aliases
#ifndef ARGMAP_ARGMAP_H
#define ARGMAP_ARGMAP_H
#include <algorithm>
#include <forward_list>
#include <fstream>
#include <functional>
#include <initializer_list>
#include <iomanip>
#include <iostream>
#include <memory>
#include <regex>
#include <set>
#include <sstream>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <vector>
#include <cctype>
/**
* @file ArgMap.h
* @brief Easier arg parsing.
**/
namespace argmap {
inline std::string join(const std::initializer_list<std::string>& words)
{
char comma[] = {'\0', ' ', '\0'};
std::ostringstream joined;
for (const auto& word : words) {
joined << comma << word;
comma[0] = ',';
}
return joined.str();
}
enum class ArgType
{
NAMED,
TOGGLE_TRUE,
TOGGLE_FALSE,
POSITIONAL,
DOTS
};
/* ArgProcessor: A virtual base class that acts as the interface to hold
* args in a map of different types.
*/
struct ArgProcessor
{
virtual ~ArgProcessor() = default;
virtual ArgType getArgType() = 0;
virtual bool process(const std::string& s) = 0;
}; // end of ArgProcessor
template <typename C>
class ArgProcessorContainer : public ArgProcessor
{
private:
C* container;
ArgType arg_type = ArgType::DOTS;
using T = typename C::value_type;
// For strings. Avoids a stream breaking on whitespace.
template <typename U = T,
typename S,
typename std::enable_if_t<std::is_same<U, S>::value, int> = 0>
bool doProcess(const S& s)
{
container->push_back(s);
return true;
}
// For non-string types, at the mercy of stringstream.
template <typename U = T,
typename S,
typename std::enable_if_t<!std::is_same<U, S>::value, int> = 0>
bool doProcess(const S& s)
{
std::istringstream iss(s);
U tmp_value;
bool rt = (iss >> tmp_value);
container->push_back(tmp_value);
return rt;
}
public:
ArgType getArgType() override { return arg_type; }
bool process(const std::string& s) override { return this->doProcess(s); }
explicit ArgProcessorContainer(C* c) : container(c) {}
}; // end of ArgProcessorContainer
// ArgProcessorValue: templated subclasses
template <typename T>
class ArgProcessorValue : public ArgProcessor
{
private:
T* value;
ArgType arg_type;
// For strings. Avoids a stream breaking on whitespace.
template <typename U = T,
typename S,
typename std::enable_if_t<std::is_same<U, S>::value, int> = 0>
bool doProcess(const S& s)
{
*value = s;
return true;
}
// For non-string types, at the mercy of stringstream.
template <typename U = T,
typename S,
typename std::enable_if_t<!std::is_same<U, S>::value, int> = 0>
bool doProcess(const S& s)
{
std::istringstream iss(s);
return static_cast<bool>(iss >> *value);
}
public:
ArgType getArgType() override { return arg_type; }
bool process(const std::string& s) override { return this->doProcess(s); }
explicit ArgProcessorValue(T* v, ArgType at) : value(v), arg_type(at) {}
}; // end of ArgProcessorValue
/**
* @brief class for handling names (and their aliases) to which processes to
*use.
**/
class NameToProcessMap
{
public:
using ArgProcessorPtr = std::shared_ptr<ArgProcessor>;
NameToProcessMap() = default;
void nameToProcessor(const std::string& name,
const ArgProcessorPtr& processor)
{
name_to_processor[name] = processor;
}
void aliasesToProcessor(const std::initializer_list<std::string>& aliases,
const ArgProcessorPtr& processor)
{
// Sanity check - Must have at least one alias
if (std::empty(aliases))
throw std::logic_error("`arg` given without at least one alias name");
// First name will be the name used
const auto& name = std::data(aliases)[0];
for (const auto& alias : aliases) {
// has this name already been added?
if (contains(alias))
throw std::logic_error("Key already in arg map (key: " + alias + ")");
// trying to add empty or whitespace name?
if (alias.empty() ||
std::any_of(alias.begin(), alias.end(), [](unsigned char c) {
return std::isspace(c);
}))
throw std::logic_error("Attempting to register an empty string or "
"string with whitespace '" +
alias + "'");
alias_to_name[alias] = name;
}
name_to_processor[name] = processor;
}
bool contains(const std::string& name) const
{
return alias_to_name.count(name) > 0;
}
auto find(const std::string& name) const
{
if (!contains(name))
return name_to_processor.end();
const auto& key = alias_to_name.at(name);
return name_to_processor.find(key);
}
auto end() const { return name_to_processor.end(); }
private:
std::unordered_map<std::string, std::string> alias_to_name;
std::unordered_map<std::string, std::shared_ptr<ArgProcessor>>
name_to_processor;
};
// requires latching logic.
class PositionalArgsList
{
private:
std::vector<std::string> positional_args;
bool optional_flag = false;
public:
void insert(const std::string& name, bool optional)
{
if (optional) {
this->optional_flag = true;
positional_args.push_back(name);
} else if (!optional_flag) {
positional_args.push_back(name);
} else {
throw std::logic_error(
"Attempting to have argument '" + name +
"' required after optional positional args given.");
}
}
auto begin() { return this->positional_args.begin(); }
auto end() { return this->positional_args.end(); }
bool empty() { return this->positional_args.empty(); }
}; // end of PositionalArgsList
/**
* @brief class for arg parsing.
**/
class ArgMap
{
private:
bool checkRequiredSetProvided(std::string& msg) const
{
if (this->required_set.empty())
return true;
std::ostringstream oss;
oss << "Required argument(s) not given:\n";
for (const auto& e : this->required_set)
oss << '\t' << e << '\n';
msg = oss.str();
return false;
}
ArgType arg_type = ArgType::NAMED;
char kv_separator = '=';
// Modes and other flags.
bool required_mode = false;
bool dots_enabled = false;
bool named_args_only = true;
bool ignore_unknown_args = false;
std::string progname;
std::string dots_name;
// Track addresses to stop assigning same variable to more than one .arg(...)
std::set<void*> addresses_used;
// Track what has been called previously whilst parsing.
std::set<std::string> previous_call_set;
// Store the args and handle aliases.
NameToProcessMap map;
struct DocItem
{
bool is_required = false;
std::string key_name;
std::string alias_string_list;
std::string doc_string;
DocItem(bool req,
const std::string& kname,
const std::string& aliases,
const std::string& dstring) :
is_required(req),
key_name(kname),
alias_string_list(aliases),
doc_string(dstring)
{
}
};
// Docs held in vector until called by methods such as doc and usage
std::vector<DocItem> docVec;
PositionalArgsList positional_args_list;
std::unique_ptr<ArgProcessor> dots_ap;
// Set for tracking required.
std::set<std::string> required_set;
// Set for tracking optional.
std::set<std::string> optional_set;
std::ostream* diagnostics_strm = nullptr;
std::set<std::string> help_tokens = {"-h", "--help"};
// Private for diagnostics
void printDiagnostics(const std::forward_list<std::string>& args) const;
//! @brief Arg parsing function
/**
* Arg parsing function (private)
* @param line Space-separated argument line to parse
* @param duplicates If true does not fail in case of duplicated arguments
* @param stop Callback function called in case of failure. (Default is Usage)
*/
void parseArgs(const std::forward_list<std::string>& args,
bool duplicates = true,
std::function<void(const std::string&)> stop = {});
public:
enum class Separator
{
COLON,
EQUALS,
WHITESPACE
};
/**
* @brief Add a new argument description
* Adds a new argument description with value of type T.
* Throws helib::RuntimeError if the arg key is duplicated or if the storing
* variable is used more than once
* @tparam T The type of the argument
* @param names The argument names, key name and its other aliases.
* @param value a variable where the argument will be stored. Also used as
* default value
* @return A reference to the modified ArgMap object
*/
template <typename T>
ArgMap& arg(const std::initializer_list<std::string>& names, T& value);
/**
* @brief Add a new argument description
* Adds a new argument description with value of type T.
* Throws helib::RuntimeError if the arg key is duplicated or if the storing
* variable is used more than once
* @tparam T The type of the argument
* @param name The argument name (key)
* @param value a variable where the argument will be stored. Also used as
* default value
* @return A reference to the modified ArgMap object
*/
template <typename T>
ArgMap& arg(const std::string& name, T& value);
/**
* @brief Add a new argument with docs
* Adds a new argument description with value of type T and docs.
* Throws helib::RuntimeError if the arg key is duplicated or if the storing
* variable is used more than once
* @tparam T The type of the argument
* @param name The argument name (key)
* @param value a variable where the argument will be stored. Also used as
* default value
* @param doc1 Description of the argument used when displaying usage
* @return A reference to the modified ArgMap object
*/
template <typename V>
ArgMap& arg(const std::string& name, V& value, const std::string& doc)
{
arg({name}, value, doc);
return *this;
}
/**
* @brief Add a new argument with docs
* Adds a new argument description with value of type T and docs.
* Throws helib::RuntimeError if the arg key is duplicated or if the storing
* variable is used more than once
* @tparam T The type of the argument
* @param names The argument names a key and other aliases
* @param value a variable where the argument will be stored. Also used as
* default value
* @param doc1 Description of the argument used when displaying usage
* @return A reference to the modified ArgMap object
*/
template <typename V>
ArgMap& arg(const std::initializer_list<std::string>& names,
V& value,
const std::string& doc);
/**
* @brief Add a new argument with docs and default description
* Adds a new argument description with value of type T, with docs and
* default description. Throws helib::RuntimeError if the arg key is
* duplicated or if the storing variable is used more than once
* @tparam V The type of the argument
* @param name The argument name (key)
* @param value a variable where the argument will be stored. Also used as
* default value
* @param doc1 Description of the argument used when displaying usage
* @param info The default value description (ignored if nullptr or "")
* @return A reference to the modified ArgMap object
*/
template <typename V>
ArgMap& arg(const std::string& name,
V& value,
const std::string& doc,
const char* info)
{
arg({name}, value, doc, info);
return *this;
}
/**
* @brief Add a new argument with docs and default description
* Adds a new argument description with value of type T, with docs and
* default description. Throws helib::RuntimeError if the arg key is
* duplicated or if the storing variable is used more than once
* @tparam V The type of the argument
* @param names The argument names a key and other aliases
* @param value a variable where the argument will be stored. Also used as
* default value
* @param doc1 Description of the argument used when displaying usage
* @param info The default value description (ignored if nullptr or "")
* @return A reference to the modified ArgMap object
*/
template <typename V>
ArgMap& arg(const std::initializer_list<std::string>& names,
V& value,
const std::string& doc,
const char* info);
/**
* @brief Adds variable number of positional arg types after defined arg types
* are exhausted. These are treated as optional.
* @param container holds the variable positional args. It must have a
* push_back method for insertion
* @return A reference to the ArgMap object
*/
template <typename C>
ArgMap& dots(C& container, const char* name);
/**
* @brief Parse the argv array
* Parse the argv array
* If it fails or -h is an argument it prints the usage and exits the program
* @param argc number of entries in argv
* @param argv array containing the arguments
* @return A reference to the ArgMap object
*/
ArgMap& parse(int argc, char** argv);
/**
* @brief Parse the configuration/parameters file
* Parsing a configuration file only functions with named arguments
* Parse the config file
* Throws RuntimeError on failure
* @param filepath the config file path
* @return A reference to the ArgMap object
*/
ArgMap& parse(const std::string& filepath);
/**
* @brief Swaps to optional arg mode (default)
* Swaps to optional arg mode. Following arguments will be considered optional
* @return A reference to the ArgMap object
*/
ArgMap& optional();
/**
* @brief Swaps to required arg mode
* Swaps to required arg mode. Following arguments will be considered required
* @return A reference to the ArgMap object
*/
ArgMap& required();
/**
* @brief Swaps to toggle arg type
* Swaps to required arg mode. Following arguments will be considered of
* toggle type
* @return A reference to the ArgMap object
*/
ArgMap& toggle(bool t = true);
/**
* @brief Swaps to named arg type (default)
* Swaps to required arg mode. Following arguments will be considered of named
* type
* @return A reference to the ArgMap object
*/
ArgMap& named();
/**
* @brief Sets parser to ignore unknown arguments
* Sets parser to ignore unknown arguments otherwise parser exists whenever
* an unknown argument is encountered
* @return A reference to the ArgMap object
*/
ArgMap& ignoreUnknown(bool t = false);
/**
* @brief Swaps to positional arg type
* Swaps to required arg mode. Following arguments will be considered of
* positional type
* @return A reference to the ArgMap object
*/
ArgMap& positional();
/**
* @brief Provide custom help toggle args. (defaults are "-h", "--help")
* Overwrite default help toggle args to custom ones for parsing.
* @return A reference to the ArgMap object
*/
inline ArgMap& helpArgs(const std::initializer_list<std::string>& s)
{
this->help_tokens = s;
return *this;
}
inline ArgMap& helpArgs(const std::string& s)
{
this->help_tokens = {s};
return *this;
}
/**
* @brief Turns on diagnostics printout when parsing
* Swaps to required arg mode. Following arguments will be considered of
* positional type
* @return A reference to the ArgMap object
*/
ArgMap& diagnostics(std::ostream& ostrm = std::cout);
/**
* @brief Sets the key-value separator
* Sets the named args key-value pair separator character
* @param s the separator enum must be set either to COLON or EQUALS(default).
* @return A reference to the ArgMap object
*/
ArgMap& separator(Separator s);
/**
* @brief Adds a note to usage
* Adds a note to the arg usage description
* @param s The note string
* @return A reference to the ArgMap object
*/
ArgMap& note(const std::string& s);
/**
* @brief Print usage and exit
* Prints the usage and exits the program
* @param msg An additional message to print before showing usage
*/
void usage(const std::string& msg = "") const;
/**
* @brief Return arg docs
* Returns the argument documentation as a string
* @return the argument documentation string
*/
std::string doc() const;
}; // End of class ArgMap
// strip whitespaces before and after strings.
inline void strip(std::string& s)
{
auto whitespaceCond = [](unsigned char c) { return !std::isspace(c); };
auto left_it = std::find_if(s.begin(), s.end(), whitespaceCond);
s.erase(s.begin(), left_it);
auto right_it = std::find_if(s.rbegin(), s.rend(), whitespaceCond);
s.erase(right_it.base(), s.end());
}
// Correct the list from argv by splitting on the separator.
inline void splitOnSeparator(std::forward_list<std::string>& args_lst, char sep)
{
if (sep == ' ')
return;
for (auto it = args_lst.begin(); it != args_lst.end(); ++it) {
if (it->size() == 1)
continue;
std::size_t pos = it->find(sep);
if (pos == std::string::npos)
continue;
if (pos == 0) {
std::string sub = it->substr(1, std::string::npos);
*it = sep;
args_lst.insert_after(it, sub);
} else {
std::string sub = it->substr(pos);
*it = it->substr(0, pos);
args_lst.insert_after(it, sub);
}
}
}
template <typename T>
inline ArgMap& ArgMap::arg(const std::initializer_list<std::string>& names,
T& value)
{
// have we seen this addr before?
if (addresses_used.count(&value) != 0)
throw std::logic_error("Attempting to register variable twice");
addresses_used.insert(&value);
auto processor =
std::make_shared<ArgProcessorValue<T>>(&value, this->arg_type);
map.aliasesToProcessor(names, processor);
// Key name is the designated name representing the whole alias group
// by our convention this is the first alias name given to arg
const auto& key_name = std::data(names)[0];
if (this->arg_type == ArgType::POSITIONAL) {
this->positional_args_list.insert(key_name, !this->required_mode);
}
// Only take the first alias a.k.a. key name
if (this->required_mode) {
// The user should make toggles correct in the code with optional
if (this->arg_type == ArgType::TOGGLE_TRUE ||
this->arg_type == ArgType::TOGGLE_FALSE)
throw std::logic_error("Toggle argument types cannot be required.");
this->required_set.insert(key_name);
} else {
// It is optional
this->optional_set.insert(key_name);
}
return *this;
}
template <typename T>
inline ArgMap& ArgMap::arg(const std::string& name, T& value)
{
arg({name}, value);
return *this;
}
template <typename V>
inline ArgMap& ArgMap::arg(const std::initializer_list<std::string>& names,
V& value,
const std::string& doc)
{
arg(names, value);
std::ostringstream doc_stream;
doc_stream << doc << " [ default=" << value << " ]";
docVec.emplace_back(required_mode,
std::data(names)[0],
join(names),
doc_stream.str());
return *this;
}
template <typename V>
inline ArgMap& ArgMap::arg(const std::initializer_list<std::string>& names,
V& value,
const std::string& doc,
const char* info)
{
arg(names, value);
docVec.emplace_back(required_mode, std::data(names)[0], join(names), doc);
if (info != nullptr && info[0] != '\0')
docVec.back().doc_string.append(" [ default=").append(info).append(" ]");
return *this;
}
template <typename C>
inline ArgMap& ArgMap::dots(C& container, const char* name)
{
if (this->dots_enabled)
throw std::logic_error(".dots() can only be called once.");
this->dots_enabled = true;
this->dots_name = name;
// Have it out of the map as it may be called many times and has no
// name/token.
this->dots_ap = std::make_unique<ArgProcessorContainer<C>>(&container);
return *this;
}
inline ArgMap& ArgMap::note(const std::string& s)
{
docVec.back().doc_string.append("\t\t").append(s);
return *this;
}
inline void ArgMap::usage(const std::string& msg) const
{
if (!msg.empty())
std::cerr << msg << '\n';
auto docVecCopy = docVec;
std::stable_partition(
docVecCopy.begin(),
docVecCopy.end(),
[this](const auto& item) {
const auto& it = map.find(item.key_name);
if (it == map.end())
throw std::logic_error("Not found in map '" + item.key_name +
"' during partition.");
return it->second->getArgType() != ArgType::POSITIONAL;
});
std::cerr << "Usage: " << this->progname;
for (auto& doc : docVecCopy) {
auto it = map.find(doc.key_name);
if (it == map.end())
throw std::logic_error("Not found in map '" + doc.key_name +
"'during printing to stream.");
if (it->second->getArgType() == ArgType::NAMED)
doc.key_name.append(1, this->kv_separator).append("<arg>");
if (doc.is_required) {
std::cerr << " " << doc.key_name;
} else {
std::cerr << " [" << doc.key_name << "]";
}
}
if (this->dots_enabled)
std::cerr << " [" << this->dots_name << " ...]";
std::cerr << '\n' << doc() << std::endl;
exit(EXIT_FAILURE);
}
inline ArgMap& ArgMap::separator(Separator s)
{
switch (s) {
case Separator::EQUALS:
this->kv_separator = '=';
break;
case Separator::COLON:
this->kv_separator = ':';
break;
case Separator::WHITESPACE:
this->kv_separator = ' ';
break;
default:
throw std::logic_error("Unknown option for kv separator.");
}
return *this;
}
inline ArgMap& ArgMap::optional()
{
this->required_mode = false;
return *this;
}
inline ArgMap& ArgMap::required()
{
this->required_mode = true;
return *this;
}
inline ArgMap& ArgMap::toggle(bool t)
{
this->named_args_only = false;
this->arg_type = t ? ArgType::TOGGLE_TRUE : ArgType::TOGGLE_FALSE;
return *this;
}
inline ArgMap& ArgMap::named()
{
this->arg_type = ArgType::NAMED;
return *this;
}
inline ArgMap& ArgMap::ignoreUnknown(bool t)
{
this->ignore_unknown_args = t;
return *this;
}
inline ArgMap& ArgMap::positional()
{
this->named_args_only = false;
this->arg_type = ArgType::POSITIONAL;
return *this;
}
inline ArgMap& ArgMap::diagnostics(std::ostream& ostrm)
{
this->diagnostics_strm = &ostrm;
return *this;
}
inline void ArgMap::printDiagnostics(
const std::forward_list<std::string>& args) const
{
if (this->diagnostics_strm == nullptr)
return;
auto writeToStream = [this](auto collection) {
for (const auto& item : collection) {
*this->diagnostics_strm << item << '\n';
}
};
*this->diagnostics_strm << "Args pre-parse:\n";
writeToStream(args);
*this->diagnostics_strm << "Required args set:\n";
writeToStream(required_set);
*this->diagnostics_strm << "Optional args set:\n";
writeToStream(optional_set);
*this->diagnostics_strm << std::flush;
}
inline std::string ArgMap::doc() const
{
std::stringstream ss;
auto maxSzElem =
std::max_element(docVec.begin(),
docVec.end(),
[](const auto& x, const auto& y) {
return x.alias_string_list.size() < y.alias_string_list.size();
});
for (const auto& doc_item : docVec) {
ss << " " << std::left << std::setw(maxSzElem->alias_string_list.length() + 1)
<< doc_item.alias_string_list << std::setw(0) << doc_item.doc_string << '\n';
}
return ss.str();
}
inline void ArgMap::parseArgs(const std::forward_list<std::string>& args,
bool duplicates,
std::function<void(const std::string&)> stop)
{
if (stop == nullptr) {
stop = std::bind(&ArgMap::usage, this, std::placeholders::_1);
}
auto pos_args_it = this->positional_args_list.begin();
for (auto it = args.begin(); it != args.end(); ++it) {
const std::string token = *it;
if (this->help_tokens.count(token))
stop("");
// Check if not called before
if (!duplicates && this->previous_call_set.count(token))
stop("Attempting to set same variable '" + token + "' twice.");
// Select ArgProcessor
auto map_it = this->map.find(token);
std::shared_ptr<ArgProcessor> ap =
(map_it == this->map.end()) ? nullptr : map_it->second;
if (ap && ap->getArgType() != ArgType::POSITIONAL) {
switch (ap->getArgType()) {
case ArgType::NAMED:
// Process value (parse and set)
if (++it == args.end())
stop("Dangling value for named argument '" + token + "'.");
if (this->kv_separator == ' ') {
if (!ap->process(*it))
stop("Whitespace separator issue. Value:'" + *it + "'");
} else {
if (++it == args.end())
stop("Dangling value for named argument '" + token +
"' after separator.");
if (!ap->process(*it))
stop("Not a valid value '" + *it + "'.");
}
break;
case ArgType::TOGGLE_TRUE:
if (!ap->process("1"))
stop("");
break;
case ArgType::TOGGLE_FALSE:
if (!ap->process("0"))
stop("");
break;
default:
throw std::logic_error("Unknown ArgType.");
}
// Remove from required_set (if it is there)
this->required_set.erase(token);
// Previously called.
this->previous_call_set.insert(token);
} else if (pos_args_it != this->positional_args_list.end()) {
// POSITIONAL args are treated differently as it is technically
// never a recognised token.
std::shared_ptr<ArgProcessor> pos_ap = map.find(*pos_args_it)->second;
if (!pos_ap->process(*it))
throw std::logic_error(
"Positional name does not match an ArgMap name.");
// Remove from required_set (if it is there)
this->required_set.erase(*pos_args_it);
++pos_args_it;
} else if (this->dots_enabled) {
this->dots_ap->process(token);
} else {
if(!this->ignore_unknown_args) {
std::string msg = "Unknown argument \'" + token + "\'";
if (!this->positional_args_list.empty())
msg.append("\nThere could be too many positional arguments");
stop(msg);
}
}
}
std::string msg;
if (!checkRequiredSetProvided(msg))
stop(msg);
}
inline ArgMap& ArgMap::parse(int argc, char** argv)
{
this->progname = std::string(argv[0]);
std::forward_list<std::string> args(argv + 1, argv + argc);
splitOnSeparator(args, this->kv_separator);
std::for_each(args.begin(), args.end(), strip);
printDiagnostics(args);
parseArgs(args);
return *this;
}
inline ArgMap& ArgMap::parse(const std::string& filepath)
{
if (this->kv_separator == ' ') { // Not from files.
throw std::logic_error("Whitespace separator not possible from files.");
}
if (!this->named_args_only) {
throw std::logic_error("Toggle and Positional arguments not possible from "
"files. Only named arguments.");
}
std::ifstream file(filepath);
this->progname = filepath;
if (!file.is_open()) {
throw std::runtime_error("Could not open file '" + filepath + "'.");
}
std::forward_list<std::string> args;
auto it = args.before_begin();
std::regex re_comment_lines(R"((^\s*\#)|(^\s+$))");
std::string line;
while (getline(file, line)) {
if (line.empty() || std::regex_search(line, re_comment_lines)) {
continue; // ignore comment lines and empties.
}
it = args.insert_after(it, line);
}
splitOnSeparator(args, this->kv_separator);
std::for_each(args.begin(), args.end(), strip);
printDiagnostics(args);
parseArgs(args, false, [&filepath](const std::string& msg) {
throw std::runtime_error("Could not parse params file: '" + filepath +
"'. " + msg);
});
return *this;
}
} // namespace argmap
#endif // ifndef ARGMAP_ARGMAP_H