-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathargument_parser.hpp
More file actions
1644 lines (1456 loc) · 63.5 KB
/
argument_parser.hpp
File metadata and controls
1644 lines (1456 loc) · 63.5 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
// Copyright (c) 2023-2025 Jakub Musiał
// This file is part of the CPP-AP project (https://github.com/SpectraL519/cpp-ap).
// Licensed under the MIT License. See the LICENSE file in the project root for full license information.
/**
* @file ap/argument_parser.hpp
* @brief Main library header file. Defines the `argument_parser` class.
*/
#pragma once
#include "ap/argument.hpp"
#include "ap/argument_group.hpp"
#include "ap/detail/argument_token.hpp"
#include "ap/types.hpp"
#include <algorithm>
#include <format>
#include <iostream>
#include <ranges>
#include <span>
#ifdef AP_TESTING
namespace ap_testing {
struct argument_parser_test_fixture;
} // namespace ap_testing
#endif
namespace ap {
class argument_parser;
/// @brief The enumeration of default arguments provided by the library.
enum class default_argument : std::uint8_t {
/**
* @brief A positional argument representing a single input file path.
* Equivalent to:
* @code{.cpp}
* parser.add_positional_argument("input")
* .action<ap::action_type::observe>(ap::action::check_file_exists())
* .help("Input file path");
* @endcode
*/
p_input,
/**
* @brief A positional argument representing a single output file path.
* Equivalent to:
* @code{.cpp}
* parser.add_positional_argument("output")
* .help("Output file path");
* @endcode
*/
p_output,
/**
* @brief An optional argument representing the program's help flag.
* Equivalent to:
* @code{.cpp}
* parser.add_optional_argument<ap::none_type>("help")
* .action<ap::action_type::on_flag>(ap::action::print_help(parser, EXIT_SUCCESS))
* .help("Display the help message");
* @endcode
*/
o_help,
/**
* @brief An optional argument representing the program's version flag.
* Equivalent to:
* @code{.cpp}
* arg_parser.add_optional_argument<none_type>("version", "v")
* .action<action_type::on_flag>([&arg_parser]() {
* arg_parser.print_version();
* std::exit(EXIT_SUCCESS);
* })
* .help("Dsiplay program version info");
* @endcode
*/
o_version,
/**
* @brief A positional argument representing multiple input file paths.
* Equivalent to:
* @code{.cpp}
* parser.add_positional_argument("input", "i")
* .nargs(1ull)
* .action<ap::action_type::observe>(ap::action::check_file_exists())
* .help("Input file path");
* @endcode
*/
o_input,
/**
* @brief A positional argument representing multiple output file paths.
* Equivalent to:
* @code{.cpp}
* parser.add_positional_argument("output", "o")
* .nargs(1ull)
* .help("Output file path");
* @endcode
*/
o_output,
/**
* @brief A positional argument representing multiple input file paths.
* Equivalent to:
* @code{.cpp}
* parser.add_positional_argument("input", "i")
* .nargs(ap::nargs::at_least(1ull))
* .action<ap::action_type::observe>(ap::action::check_file_exists())
* .help("Input file path");
* @endcode
*/
o_multi_input,
/**
* @brief A positional argument representing multiple output file paths.
* Equivalent to:
* @code{.cpp}
* parser.add_positional_argument("output", "o")
* .nargs(ap::nargs::at_least(1ull))
* .help("Output file path");
* @endcode
*/
o_multi_output
};
/// @brief The enumeration of policies for handling unknown arguments.
enum class unknown_policy : std::uint8_t {
fail, ///< Throw an exception when an unknown argument is encountered.
warn, ///< Issue a warning when an unknown argument is encountered.
ignore, ///< Ignore unknown arguments.
as_values ///< Treat unknown arguments as positional values.
};
namespace detail {
void add_default_argument(const default_argument, argument_parser&) noexcept;
} // namespace detail
/**
* @brief The main argument parser class.
*
* This class provides methods to define positional and optional arguments, set parser options,
* and parse the command-line input.
*
* Example usage:
* @code{.cpp}
* #include <ap/argument_parser.hpp>
*
* int main(int argc, char* argv[]) {
* // Create the argument parser instance
* ap::argument_parser parser("fcopy");
* parser.program_version({ .major = 1, .minor = 0, .patch = 0 })
* .program_description("A simple file copy utility.")
* .default_arguments(
* ap::default_argument::o_help,
* ap::default_argument::o_input,
* ap::default_argument::o_output
* )
* .verbose()
* .unknown_arguments_policy(ap::unknown_policy::ignore)
* .try_parse_args(argc, argv);
*
* // Access parsed argument values
* const std::string input_file = parser.value("input");
* const std::string output_file = parser.value("output");
*
* // Application logic here
* std::cout << "Copying from " << input_file << " to " << output_file << std::endl;
*
* return 0;
* }
* @endcode
*/
class argument_parser {
public:
argument_parser(const argument_parser&) = delete;
argument_parser& operator=(const argument_parser&) = delete;
argument_parser(argument_parser&&) = delete;
argument_parser& operator=(argument_parser&&) = delete;
argument_parser(const std::string_view name) : argument_parser(name, "") {}
~argument_parser() = default;
/**
* @brief Set the program version.
* @param version The version of the program.
* @return Reference to the argument parser.
*/
argument_parser& program_version(const version& version) noexcept {
this->_program_version.emplace(version.str());
return *this;
}
/**
* @brief Set the program version.
* @param version The version of the program.
* @return Reference to the argument parser.
*/
argument_parser& program_version(std::string_view version) {
if (util::contains_whitespaces(version))
throw invalid_configuration("The program version cannot contain whitespace characters!"
);
this->_program_version.emplace(version);
return *this;
}
/**
* @brief Set the program description.
* @param description The description of the program.
* @return Reference to the argument parser.
*/
argument_parser& program_description(std::string_view description) noexcept {
this->_program_description.emplace(description);
return *this;
}
/**
* @brief Set the verbosity mode.
* @note The default verbosity mode value is `false`.
* @param v The verbosity mode value.
* @return Reference to the argument parser.
*/
argument_parser& verbose(const bool v = true) noexcept {
this->_verbose = v;
return *this;
}
/**
* @brief Set the unknown argument flags handling policy.
* @param policy The unknown arguments policy value.
* @return Reference to the argument parser.
* @note The default unknown arguments policy value is `ap::unknown_policy::fail`.
*/
argument_parser& unknown_arguments_policy(const unknown_policy policy) noexcept {
this->_unknown_policy = policy;
return *this;
}
/**
* @brief Add default arguments to the argument parser.
* @tparam AR Type of the positional argument discriminator range.
* @param arg_discriminators A range of default positional argument discriminators.
* @note `arg_discriminators` must be a `std::ranges::range` with the `ap::default_argument` value type.
* @return Reference to the argument parser.
*/
template <util::c_range_of<default_argument> AR>
argument_parser& default_arguments(const AR& arg_discriminators) noexcept {
for (const auto arg_discriminator : arg_discriminators)
detail::add_default_argument(arg_discriminator, *this);
return *this;
}
/**
* @brief Add default arguments to the argument parser.
* @param arg_discriminators A list of default positional argument discriminators.
* @return Reference to the argument parser.
*/
argument_parser& default_arguments(
const std::initializer_list<default_argument>& arg_discriminators
) noexcept {
return this->default_arguments<>(arg_discriminators);
}
/**
* @brief Add default arguments to the argument parser.
* @param arg_discriminators A list of default positional argument discriminators.
* @return Reference to the argument parser.
*/
argument_parser& default_arguments(
const std::same_as<default_argument> auto... arg_discriminators
) noexcept {
(detail::add_default_argument(arg_discriminators, *this), ...);
return *this;
}
/**
* @brief Adds a positional argument to the parser's configuration.
* @tparam T Type of the argument value.
* @param name The name of the argument.
* @return Reference to the added positional argument.
* @throws ap::invalid_configuration
*/
template <util::c_argument_value_type T = std::string>
positional_argument<T>& add_positional_argument(const std::string_view name) {
return this->add_positional_argument<T>(this->_gr_positional_args, name);
}
/**
* @brief Adds a positional argument to the parser's configuration and binds it to the given group.
* @tparam T Type of the argument value.
* @param primary_name The name of the argument.
* @return Reference to the added positional argument.
* @throws ap::invalid_configuration
*/
template <util::c_argument_value_type T = std::string>
positional_argument<T>& add_positional_argument(
argument_group& group, const std::string_view name
) {
this->_validate_group(group);
this->_verify_arg_name_pattern(name);
const detail::argument_name arg_name(std::make_optional<std::string>(name));
if (this->_is_arg_name_used(arg_name))
throw invalid_configuration::argument_name_used(arg_name);
auto& new_arg_ptr =
this->_positional_args.emplace_back(std::make_shared<positional_argument<T>>(arg_name));
group._add_argument(new_arg_ptr);
return static_cast<positional_argument<T>&>(*new_arg_ptr);
}
/**
* @brief Adds an optional argument to the parser's configuration.
* @tparam T Type of the argument value.
* @param name The name of the argument.
* @param name_discr The discriminator value specifying whether the given name should be treated as primary or secondary.
* @return Reference to the added optional argument.
* @throws ap::invalid_configuration
*/
template <util::c_argument_value_type T = std::string>
optional_argument<T>& add_optional_argument(
const std::string_view name,
const detail::argument_name_discriminator name_discr = n_primary
) {
return this->add_optional_argument<T>(this->_gr_optional_args, name, name_discr);
}
/**
* @brief Adds an optional argument to the parser's configuration.
* @tparam T Type of the argument value.
* @param primary_name The primary name of the argument.
* @param secondary_name The secondary name of the argument.
* @return Reference to the added optional argument.
* @throws ap::invalid_configuration
*/
template <util::c_argument_value_type T = std::string>
optional_argument<T>& add_optional_argument(
const std::string_view primary_name, const std::string_view secondary_name
) {
return this->add_optional_argument<T>(
this->_gr_optional_args, primary_name, secondary_name
);
}
/**
* @brief Adds an optional argument to the parser's configuration and binds it to the given group.
* @tparam T Type of the argument value.
* @param group The argument group to bind the new argument to.
* @param name The name of the argument.
* @param name_discr The discriminator value specifying whether the given name should be treated as primary or secondary.
* @return Reference to the added optional argument.
* @throws std::logic_error, ap::invalid_configuration
*/
template <util::c_argument_value_type T = std::string>
optional_argument<T>& add_optional_argument(
argument_group& group,
const std::string_view name,
const detail::argument_name_discriminator name_discr = n_primary
) {
this->_validate_group(group);
this->_verify_arg_name_pattern(name);
const auto arg_name =
name_discr == n_primary
? detail::
argument_name{std::make_optional<std::string>(name), std::nullopt, this->_flag_prefix_char}
: detail::argument_name{
std::nullopt, std::make_optional<std::string>(name), this->_flag_prefix_char
};
if (this->_is_arg_name_used(arg_name))
throw invalid_configuration::argument_name_used(arg_name);
auto& new_arg_ptr =
this->_optional_args.emplace_back(std::make_shared<optional_argument<T>>(arg_name));
group._add_argument(new_arg_ptr);
return static_cast<optional_argument<T>&>(*new_arg_ptr);
}
/**
* @brief Adds an optional argument to the parser's configuration and binds it to the given group.
* @tparam T Type of the argument value.
* @param group The argument group to bind the new argument to.
* @param primary_name The primary name of the argument.
* @param secondary_name The secondary name of the argument.
* @return Reference to the added optional argument.
* @throws ap::invalid_configuration
*/
template <util::c_argument_value_type T = std::string>
optional_argument<T>& add_optional_argument(
argument_group& group,
const std::string_view primary_name,
const std::string_view secondary_name
) {
this->_validate_group(group);
this->_verify_arg_name_pattern(primary_name);
this->_verify_arg_name_pattern(secondary_name);
const detail::argument_name arg_name(
std::make_optional<std::string>(primary_name),
std::make_optional<std::string>(secondary_name),
this->_flag_prefix_char
);
if (this->_is_arg_name_used(arg_name))
throw invalid_configuration::argument_name_used(arg_name);
auto& new_arg_ptr =
this->_optional_args.emplace_back(std::make_shared<optional_argument<T>>(arg_name));
group._add_argument(new_arg_ptr);
return static_cast<optional_argument<T>&>(*new_arg_ptr);
}
/**
* @brief Adds a boolean flag argument (an optional argument with `value_type = bool`) to the parser's configuration.
* @tparam StoreImplicitly A boolean value used as the `implicit_values` parameter of the argument.
* @note The argument's `default_values` attribute will be set to `not StoreImplicitly`.
* @param name The primary name of the flag.
* @param name_discr The discriminator value specifying whether the given name should be treated as primary or secondary.
* @return Reference to the added boolean flag argument.
*/
template <bool StoreImplicitly = true>
optional_argument<bool>& add_flag(
const std::string_view name,
const detail::argument_name_discriminator name_discr = n_primary
) {
return this->add_optional_argument<bool>(name, name_discr)
.default_values(not StoreImplicitly)
.implicit_values(StoreImplicitly)
.nargs(0ull);
}
/**
* @brief Adds a boolean flag argument (an optional argument with `value_type = bool`) to the parser's configuration.
* @tparam StoreImplicitly A boolean value used as the `implicit_values` parameter of the argument.
* @note The argument's `default_values` attribute will be set to `not StoreImplicitly`.
* @param primary_name The primary name of the flag.
* @param secondary_name The secondary name of the flag.
* @return Reference to the added boolean flag argument.
*/
template <bool StoreImplicitly = true>
optional_argument<bool>& add_flag(
const std::string_view primary_name, const std::string_view secondary_name
) {
return this->add_optional_argument<bool>(primary_name, secondary_name)
.default_values(not StoreImplicitly)
.implicit_values(StoreImplicitly)
.nargs(0ull);
}
/**
* @brief Adds a boolean flag argument (an optional argument with `value_type = bool`) to the parser's configuration and binds it to the given group.
* @tparam StoreImplicitly A boolean value used as the `implicit_values` parameter of the argument.
* @note The argument's `default_values` attribute will be set to `not StoreImplicitly`.
* @param group The argument group to bind the new argument to.
* @param name The primary name of the flag.
* @param name_discr The discriminator value specifying whether the given name should be treated as primary or secondary.
* @return Reference to the added boolean flag argument.
*/
template <bool StoreImplicitly = true>
optional_argument<bool>& add_flag(
argument_group& group,
const std::string_view name,
const detail::argument_name_discriminator name_discr = n_primary
) {
return this->add_optional_argument<bool>(group, name, name_discr)
.default_values(not StoreImplicitly)
.implicit_values(StoreImplicitly)
.nargs(0ull);
}
/**
* @brief Adds a boolean flag argument (an optional argument with `value_type = bool`) to the parser's configuration and binds it to the given group.
* @tparam StoreImplicitly A boolean value used as the `implicit_values` parameter of the argument.
* @note The argument's `default_values` attribute will be set to `not StoreImplicitly`.
* @param group The argument group to bind the new argument to.
* @param primary_name The primary name of the flag.
* @param secondary_name The secondary name of the flag.
* @return Reference to the added boolean flag argument.
*/
template <bool StoreImplicitly = true>
optional_argument<bool>& add_flag(
argument_group& group,
const std::string_view primary_name,
const std::string_view secondary_name
) {
return this->add_optional_argument<bool>(group, primary_name, secondary_name)
.default_values(not StoreImplicitly)
.implicit_values(StoreImplicitly)
.nargs(0ull);
}
/**
* @brief Adds an argument group with the given name to the parser's configuration.
* @param name Name of the group.
* @return Reference to the added argument group.
*/
argument_group& add_group(const std::string_view name) noexcept {
return *this->_argument_groups.emplace_back(argument_group::create(*this, name));
}
/**
* @brief Adds an subparser with the given name to the parser's configuration.
* @param name Name of the subparser.
* @return Reference to the added subparser.
*/
argument_parser& add_subparser(const std::string_view name) {
const auto subparser_it = std::ranges::find(
this->_subparsers, name, [](const auto& subparser) { return subparser->_name; }
);
if (subparser_it != this->_subparsers.end())
throw std::logic_error(std::format(
"A subparser with the given name () already exists in parser '{}'",
(*subparser_it)->_name,
this->_program_name
));
return *this->_subparsers.emplace_back(
std::unique_ptr<argument_parser>(new argument_parser(name, this->_program_name))
);
}
/**
* @brief Parses the command-line arguments.
*
* Equivalent to:
* ```cpp
* parse_args(std::span(argv + 1, static_cast<std::size_t>(argc - 1)))
* ```
*
* @param argc Number of command-line arguments.
* @param argv Array of command-line argument values.
* @throws ap::invalid_configuration, ap::parsing_failure
* @attention The first argument (the program name) is ignored.
*/
void parse_args(int argc, char* argv[]) {
this->parse_args(std::span(argv + 1, static_cast<std::size_t>(argc - 1)));
}
/**
* @brief Parses the command-line arguments.
* @tparam AR The argument range type.
* @param argv_rng A range of command-line argument values.
* @note `argv_rng` must be a `std::ranges::forward_range` with a value type convertible to `std::string`.
* @throws ap::invalid_configuration, ap::parsing_failure
* @attention This overload of the `parse_args` function assumes that the program name argument has already been discarded.
*/
template <util::c_forward_range_of<std::string, util::type_validator::convertible> AR>
void parse_args(const AR& argv_rng) {
parsing_state state(*this);
this->_parse_args_impl(std::ranges::begin(argv_rng), std::ranges::end(argv_rng), state);
if (not state.unknown_args.empty())
throw parsing_failure(std::format(
"Failed to deduce the argument for values [{}]", util::join(state.unknown_args)
));
}
/**
* @brief Parses the command-line arguments and exits on error.
*
* Equivalent to:
* ```cpp
* try_parse_args(std::span(argv + 1, static_cast<std::size_t>(argc - 1)))
* ```
*
* @param argc Number of command-line arguments.
* @param argv Array of command-line argument values.
* @note The first argument (the program name) is ignored.
*/
void try_parse_args(int argc, char* argv[]) {
this->try_parse_args(std::span(argv + 1, static_cast<std::size_t>(argc - 1)));
}
/**
* @brief Parses the command-line arguments and exits on error.
*
* Calls `parse_args(argv_rng)` in a try-catch block. If an error is thrown, then its
* message and the parser are printed to `std::cerr` and the function exists with
* `EXIT_FAILURE` status.
*
* @tparam AR The argument range type.
* @param argv_rng A range of command-line argument values.
* @note `argv_rng` must be a `std::ranges::forward_range` with a value type convertible to `std::string`.
* @attention This overload of the `try_parse_args` function assumes that the program name argument has already been discarded.
*/
template <util::c_forward_range_of<std::string, util::type_validator::convertible> AR>
void try_parse_args(const AR& argv_rng) {
try {
this->parse_args(argv_rng);
}
catch (const ap::argument_parser_exception& err) {
std::cerr << "[ap::error] " << err.what() << std::endl
<< this->resolved_parser() << std::endl;
std::exit(EXIT_FAILURE);
}
}
/**
* @brief Parses the known command-line arguments.
*
* Equivalent to:
* ```cpp
* try_parse_known_args(std::span(argv + 1, static_cast<std::size_t>(argc - 1)))
* ```
*
* An argument is considered "known" if it was defined using the parser's argument declaraion methods:
* - `add_positional_argument`
* - `add_optional_argument`
* - `add_flag`
*
* @param argc Number of command-line arguments.
* @param argv Array of command-line argument values.
* @throws ap::invalid_configuration, ap::parsing_failure
* @attention The first argument (the program name) is ignored.
*/
std::vector<std::string> parse_known_args(int argc, char* argv[]) {
return this->parse_known_args(std::span(argv + 1, static_cast<std::size_t>(argc - 1)));
}
/**
* @brief Parses the known command-line arguments.
*
* * An argument is considered "known" if it was defined using the parser's argument declaraion methods:
* - `add_positional_argument`
* - `add_optional_argument`
* - `add_flag`
*
* @tparam AR The argument range type.
* @param argv_rng A range of command-line argument values.
* @note `argv_rng` must be a `std::ranges::forward_range` with a value type convertible to `std::string`.
* @throws ap::invalid_configuration, ap::parsing_failure
* @attention This overload of the `parse_known_args` function assumes that the program name argument already been discarded.
*/
template <util::c_forward_range_of<std::string, util::type_validator::convertible> AR>
std::vector<std::string> parse_known_args(const AR& argv_rng) {
parsing_state state(*this, true);
this->_parse_args_impl(std::ranges::begin(argv_rng), std::ranges::end(argv_rng), state);
return std::move(state.unknown_args);
}
/**
* @brief Parses the known command-line arguments and exits on error.
*
* Equivalent to:
* ```cpp
* try_parse_known_args(std::span(argv + 1, static_cast<std::size_t>(argc - 1)))
* ```
*
* @param argc Number of command-line arguments.
* @param argv Array of command-line argument values.
* @return A vector of unknown argument values.
* @attention The first argument (the program name) is ignored.
*/
std::vector<std::string> try_parse_known_args(int argc, char* argv[]) {
return this->try_parse_known_args(std::span(argv + 1, static_cast<std::size_t>(argc - 1)));
}
/**
* @brief Parses known the command-line arguments and exits on error.
*
* Calls `parse_known_args(argv_rng)` in a try-catch block. If an error is thrown, then its message
* and the parser are printed to `std::cerr` and the function exists with `EXIT_FAILURE` status.
* Otherwise the result of `parse_known_args(argv_rng)` is returned.
*
* @tparam AR The argument range type.
* @param argv_rng A range of command-line argument values.
* @note `argv_rng` must be a `std::ranges::forward_range` with a value type convertible to `std::string`.
* @return A vector of unknown argument values.
* @attention This overload of the `try_parse_known_args` function assumes that the program name argument has already been discarded.
*/
template <util::c_forward_range_of<std::string, util::type_validator::convertible> AR>
std::vector<std::string> try_parse_known_args(const AR& argv_rng) {
try {
return this->parse_known_args(argv_rng);
}
catch (const ap::argument_parser_exception& err) {
std::cerr << "[ap::error] " << err.what() << std::endl
<< this->resolved_parser() << std::endl;
std::exit(EXIT_FAILURE);
}
}
/// @brief Returns the parser's name.
[[nodiscard]] std::string_view name() const noexcept {
return this->_name;
}
/**
* @brief Returns the parser's full program name.
*
* - For top-level parsers, this is the same as the parser's name.
* - For subparsers, the name is prefixed with its parent parser names.
*
* @example
* Top-level parser: `git`
* Subparser: `git submodule`
* Nested subparser : `git submodule init`
*/
[[nodiscard]] std::string_view program_name() const noexcept {
return this->_program_name;
}
/**
* @brief Check whether this parser was invoked.
* @return `true` if the parser was selected when parsing the command-line arguments, `false` otherwise.
* @note A parser is *invoked* as soon as the parser is selected during parsing, even if parsing is later delegated to one of its subparsers.
*/
[[nodiscard]] bool invoked() const noexcept {
return this->_invoked;
}
/**
* @brief Check whether the parser has finalized parsing its own arguments.
* @return `true` if parsing was completed for the parser, `false` otherwise.
*/
[[nodiscard]] bool finalized() const noexcept {
return this->_finalized;
}
/**
* @brief Returns the *deepest invoked parser*.
* @return Reference to the finalized parser that ultimately processed the arguments.
*/
[[nodiscard]] argument_parser& resolved_parser() noexcept {
const auto used_subparser_it = std::ranges::find_if(
this->_subparsers, [](const auto& subparser) { return subparser->_invoked; }
);
if (used_subparser_it == this->_subparsers.end())
return *this;
return (*used_subparser_it)->resolved_parser();
}
/**
* @brief Check if a specific argument was used in the command-line.
* @param arg_name The name of the argument.
* @return `true` if the argument was used on the command line, `false` otherwise.
*/
[[nodiscard]] bool is_used(std::string_view arg_name) const noexcept {
const auto arg = this->_get_argument(arg_name);
return arg ? arg->is_used() : false;
}
/**
* @brief Check if the given argument has a value.
* @param arg_name The name of the argument.
* @return `true` if the argument has a value, `false` otherwise.
*/
[[nodiscard]] bool has_value(std::string_view arg_name) const noexcept {
const auto arg = this->_get_argument(arg_name);
return arg ? arg->has_value() : false;
}
/**
* @brief Get the given argument's usage count.
* @param arg_name The name of the argument.
* @return The number of times the argument has been used.
*/
[[nodiscard]] std::size_t count(std::string_view arg_name) const noexcept {
const auto arg = this->_get_argument(arg_name);
return arg ? arg->count() : 0ull;
}
/**
* @brief Get the value of the given argument.
* @tparam T Type of the argument value.
* @param arg_name The name of the argument.
* @return The value of the argument.
* @throws ap::lookup_failure, ap::type_error
*/
template <util::c_argument_value_type T = std::string>
[[nodiscard]] T value(std::string_view arg_name) const {
const auto arg = this->_get_argument(arg_name);
if (not arg)
throw lookup_failure::argument_not_found(arg_name);
const auto& arg_value = arg->value();
try {
return std::any_cast<T>(arg_value);
}
catch (const std::bad_any_cast&) {
throw type_error::invalid_value_type<T>(arg->name());
}
}
/**
* @brief Get the value of the given argument, if it has any, or a fallback value, if not.
* @tparam T Type of the argument value.
* @tparam U The default value type.
* @param arg_name The name of the argument.
* @param fallback_value The fallback value.
* @return The value of the argument.
* @throws ap::lookup_failure, ap::type_error
*/
template <util::c_argument_value_type T = std::string, std::convertible_to<T> U>
[[nodiscard]] T value_or(std::string_view arg_name, U&& fallback_value) const {
const auto arg = this->_get_argument(arg_name);
if (not arg)
throw lookup_failure::argument_not_found(arg_name);
try {
const auto& arg_value = arg->value();
return std::any_cast<T>(arg_value);
}
catch (const std::logic_error&) {
// positional: no value parsed
// optional: no value parsed + no predefined value
return T{std::forward<U>(fallback_value)};
}
catch (const std::bad_any_cast&) {
throw type_error::invalid_value_type<T>(arg->name());
}
}
/**
* @brief Get all values of the given argument.
* @tparam T Type of the argument values.
* @param arg_name The name of the argument.
* @return The values of the argument as a vector.
* @throws ap::lookup_failure, ap::type_error
*/
template <util::c_argument_value_type T = std::string>
[[nodiscard]] std::vector<T> values(std::string_view arg_name) const {
const auto arg = this->_get_argument(arg_name);
if (not arg)
throw lookup_failure::argument_not_found(arg_name);
try {
std::vector<T> values;
// TODO: use std::ranges::to after transition to C++23
std::ranges::copy(
util::any_range_cast_view<T>(arg->values()), std::back_inserter(values)
);
return values;
}
catch (const std::bad_any_cast&) {
throw type_error::invalid_value_type<T>(arg->name());
}
}
/**
* @brief Prints the argument parser's help message to an output stream.
* @param verbose The verbosity mode value.
* @param os The output stream.
*/
void print_help(const bool verbose, std::ostream& os = std::cout) const noexcept {
os << "Program: " << this->_program_name;
if (this->_program_version)
os << " (" << this->_program_version.value() << ')';
os << '\n';
if (this->_program_description)
os << '\n'
<< std::string(this->_indent_width, ' ') << this->_program_description.value()
<< '\n';
this->_print_subparsers(os);
for (const auto& group : this->_argument_groups)
this->_print_group(os, *group, verbose);
}
/**
* @brief Prints the argument parser's version info to an output stream.
*
* If no version was spcified for the parser, `unspecified` will be printed.
*
* @param os The output stream.
*/
void print_version(std::ostream& os = std::cout) const noexcept {
os << this->_program_name << " : version " << this->_program_version.value_or("unspecified")
<< std::endl;
}
/**
* @brief Prints the argument parser's details to an output stream.
*
* An `os << parser` operation is equivalent to a `parser.print_help(_verbose, os)` call,
* where `_verbose` is the inner verbosity mode, which can be set with the @ref verbose function.
*
* @param os The output stream.
* @param parser The argument parser to print.
* @return The modified output stream.
*/
friend std::ostream& operator<<(std::ostream& os, const argument_parser& parser) noexcept {
parser.print_help(parser._verbose, os);
return os;
}
#ifdef AP_TESTING
/// @brief Friend struct for testing purposes.
friend struct ::ap_testing::argument_parser_test_fixture;
#endif
private:
using arg_ptr_t = std::shared_ptr<detail::argument_base>;
using arg_ptr_vec_t = std::vector<arg_ptr_t>;
using arg_ptr_vec_iter_t = typename arg_ptr_vec_t::iterator;
using arg_group_ptr_t = std::unique_ptr<argument_group>;
using arg_group_ptr_vec_t = std::vector<arg_group_ptr_t>;
using arg_parser_ptr_t = std::unique_ptr<argument_parser>;
using arg_parser_ptr_vec_t = std::vector<arg_parser_ptr_t>;
using arg_token_vec_t = std::vector<detail::argument_token>;
using arg_token_vec_iter_t = typename arg_token_vec_t::const_iterator;
/// @brief A collection of values used during the parsing process.
struct parsing_state {
parsing_state(argument_parser& parser, const bool parse_known_only = false)
: curr_arg(nullptr),
curr_pos_arg_it(parser._positional_args.begin()),
parse_known_only(parse_known_only) {}
/// @brief Update the parser-specific parameters of the state object.
/// @param parser The new parser.
void set_parser(argument_parser& parser) {
this->curr_arg = nullptr;
this->curr_pos_arg_it = parser._positional_args.begin();
}
arg_ptr_t curr_arg; ///< The currently processed argument.
arg_ptr_vec_iter_t
curr_pos_arg_it; ///< An iterator pointing to the next positional argument to be processed.
const bool
parse_known_only; ///< A flag indicating whether only known arguments should be parsed.
std::vector<std::string> unknown_args = {}; ///< A vector of unknown argument values.
};
argument_parser(const std::string_view name, const std::string_view parent_name)
: _name(name),
_program_name(
std::format("{}{}{}", parent_name, std::string(not parent_name.empty(), ' '), name)
),
_gr_positional_args(add_group("Positional Arguments")),
_gr_optional_args(add_group("Optional Arguments")) {
if (name.empty())
throw invalid_configuration("The program name cannot be empty!");
if (util::contains_whitespaces(name))
throw invalid_configuration("The program name cannot contain whitespace characters!");
}
/**
* @brief Verifies the pattern of an argument name and if it's invalid, an error is thrown
* @throws ap::invalid_configuration
*/
void _verify_arg_name_pattern(const std::string_view arg_name) const {
if (arg_name.empty())
throw invalid_configuration::invalid_argument_name(
arg_name, "An argument name cannot be empty."
);
if (util::contains_whitespaces(arg_name))
throw invalid_configuration::invalid_argument_name(
arg_name, "An argument name cannot contain whitespaces."
);
if (arg_name.front() == this->_flag_prefix_char)
throw invalid_configuration::invalid_argument_name(
arg_name,
std::format(
"An argument name cannot begin with a flag prefix character ({}).",
this->_flag_prefix_char
)
);
if (std::isdigit(arg_name.front()))
throw invalid_configuration::invalid_argument_name(
arg_name, "An argument name cannot begin with a digit."
);
}
/**
* @brief Returns a unary predicate function which checks if the given name matches the argument's name
* @param arg_name The name of the argument.
* @param m_type The match type used within the predicate.
* @return Argument predicate based on the provided name.
*/
[[nodiscard]] auto _name_match_predicate(
const std::string_view arg_name,
const detail::argument_name::match_type m_type = detail::argument_name::m_any
) const noexcept {
return [=](const arg_ptr_t& arg) { return arg->name().match(arg_name, m_type); };
}
/**
* @brief Returns a unary predicate function which checks if the given name matches the argument's name
* @param arg_name The name of the argument.
* @param m_type The match type used within the predicate.
* @return Argument predicate based on the provided name.
*/
[[nodiscard]] auto _name_match_predicate(