Sharg 1.1.2-rc.1
The argument parser for bio-c++ tools.
Loading...
Searching...
No Matches
parser.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2006-2024, Knut Reinert & Freie Universität Berlin
2// SPDX-FileCopyrightText: 2016-2024, Knut Reinert & MPI für molekulare Genetik
3// SPDX-License-Identifier: BSD-3-Clause
4
10#pragma once
11
12#include <unordered_set>
13#include <variant>
14
15#include <sharg/config.hpp>
22
23namespace sharg
24{
25
154{
155public:
159 parser() = delete;
160 parser(parser const &) = delete;
161 parser & operator=(parser const &) = delete;
162 parser(parser &&) = default;
163 parser & operator=(parser &&) = default;
164
182 std::vector<std::string> arguments,
184 std::vector<std::string> const & subcommands = {}) :
185 version_check_dev_decision{version_updates},
186 arguments{std::move(arguments)}
187 {
188 add_subcommands(subcommands);
189 info.app_name = std::move(app_name);
190 }
191
194 int const argc,
195 char const * const * const argv,
197 std::vector<std::string> const & subcommands = {}) :
198 parser{std::move(app_name), std::vector<std::string>{argv, argv + argc}, version_updates, subcommands}
199 {}
200
203 {
204 // wait for another 3 seconds
205 if (version_check_future.valid())
206 version_check_future.wait_for(std::chrono::seconds(3));
207 }
209
238 template <typename option_type, typename validator_type>
241 void add_option(option_type & value, config<validator_type> const & config)
242 {
243 check_parse_not_called("add_option");
244 verify_option_config(config);
245
246 auto operation = [this, &value, config]()
247 {
248 auto visit_fn = [&value, &config](auto & f)
249 {
250 f.add_option(value, config);
251 };
252
253 std::visit(std::move(visit_fn), format);
254 };
255
256 operations.push_back(std::move(operation));
257 }
258
272 template <typename validator_type>
274 void add_flag(bool & value, config<validator_type> const & config)
275 {
276 check_parse_not_called("add_flag");
277 verify_flag_config(config);
278
279 if (value)
280 throw design_error("A flag's default value must be false.");
281
282 auto operation = [this, &value, config]()
283 {
284 auto visit_fn = [&value, &config](auto & f)
285 {
286 f.add_flag(value, config);
287 };
288
289 std::visit(std::move(visit_fn), format);
290 };
291
292 operations.push_back(std::move(operation));
293 }
294
322 template <typename option_type, typename validator_type>
325 void add_positional_option(option_type & value, config<validator_type> const & config)
326 {
327 check_parse_not_called("add_positional_option");
328 verify_positional_option_config(config);
329
330 if constexpr (detail::is_container_option<option_type>)
331 has_positional_list_option = true; // keep track of a list option because there must be only one!
332
333 auto operation = [this, &value, config]()
334 {
335 auto visit_fn = [&value, &config](auto & f)
336 {
337 f.add_positional_option(value, config);
338 };
339
340 std::visit(std::move(visit_fn), format);
341 };
342
343 operations.push_back(std::move(operation));
344 }
346
414 void parse()
415 {
416 if (parse_was_called)
417 throw design_error("The function parse() must only be called once!");
418
419 parse_was_called = true;
420
421 // User input sanitization must happen before version check!
422 verify_app_and_subcommand_names();
423
424 // Determine the format and subcommand.
425 determine_format_and_subcommand();
426
427 // Apply all defered operations to the parser, e.g., `add_option`, `add_flag`, `add_positional_option`.
428 for (auto & operation : operations)
429 operation();
430
431 // The version check, which might exit the program, must be called before calling parse on the format.
432 run_version_check();
433
434 // Parse the command line arguments.
435 parse_format();
436
437 // Exit after parsing any special format.
439 std::exit(EXIT_SUCCESS);
440 }
441
449 {
450 if (sub_parser == nullptr)
451 {
452 throw design_error("No subcommand was provided at the construction of the argument parser!");
453 }
454
455 return *sub_parser;
456 }
457
487 // clang-format off
488 template <typename id_type>
490 bool is_option_set(id_type const & id) const
491 // clang-format on
492 {
493 if (!parse_was_called)
494 throw design_error{"You can only ask which options have been set after calling the function `parse()`."};
495
496 detail::id_pair const id_pair{id};
497
498 if (id_pair.long_id.size() == 1u)
499 {
500 throw design_error{"Long option identifiers must be longer than one character! If " + id_pair.long_id
501 + "' was meant to be a short identifier, please pass it as a char ('') not a string"
502 " (\"\")!"};
503 }
504
505 auto const it = detail::id_pair::find(used_option_ids, id_pair);
506 if (it == used_option_ids.end())
507 throw design_error{"You can only ask for option identifiers that you added with add_option() before."};
508
509 // we only need to search for an option before the `option_end_identifier` (`--`)
510 auto option_end = std::ranges::find(format_arguments, option_end_identifier);
511 auto option_it = detail::format_parse::find_option_id(format_arguments.begin(), option_end, *it);
512 return option_it != option_end;
513 }
514
517
528 void add_section(std::string const & title, bool const advanced_only = false)
529 {
530 check_parse_not_called("add_section");
531
532 auto operation = [this, title, advanced_only]()
533 {
534 auto visit_fn = [&title, advanced_only](auto & f)
535 {
536 f.add_section(title, advanced_only);
537 };
538
539 std::visit(std::move(visit_fn), format);
540 };
541
542 operations.push_back(std::move(operation));
543 }
544
555 void add_subsection(std::string const & title, bool const advanced_only = false)
556 {
557 check_parse_not_called("add_subsection");
558
559 auto operation = [this, title, advanced_only]()
560 {
561 auto visit_fn = [&title, advanced_only](auto & f)
562 {
563 f.add_subsection(title, advanced_only);
564 };
565
566 std::visit(std::move(visit_fn), format);
567 };
568
569 operations.push_back(std::move(operation));
570 }
571
583 void add_line(std::string const & text, bool is_paragraph = false, bool const advanced_only = false)
584 {
585 check_parse_not_called("add_line");
586
587 auto operation = [this, text, is_paragraph, advanced_only]()
588 {
589 auto visit_fn = [&text, is_paragraph, advanced_only](auto & f)
590 {
591 f.add_line(text, is_paragraph, advanced_only);
592 };
593
594 std::visit(std::move(visit_fn), format);
595 };
596
597 operations.push_back(std::move(operation));
598 }
599
620 void add_list_item(std::string const & key, std::string const & desc, bool const advanced_only = false)
621 {
622 check_parse_not_called("add_list_item");
623
624 auto operation = [this, key, desc, advanced_only]()
625 {
626 auto visit_fn = [&key, &desc, advanced_only](auto & f)
627 {
628 f.add_list_item(key, desc, advanced_only);
629 };
630
631 std::visit(std::move(visit_fn), format);
632 };
633
634 operations.push_back(std::move(operation));
635 }
636
649 {
650 auto & parser_subcommands = this->subcommands;
651 parser_subcommands.insert(parser_subcommands.end(), subcommands.cbegin(), subcommands.cend());
652
653 std::ranges::sort(parser_subcommands);
654 auto const [first, last] = std::ranges::unique(parser_subcommands);
655 parser_subcommands.erase(first, last);
656 }
658
710
711private:
713 bool parse_was_called{false};
714
716 bool has_positional_list_option{false};
717
719 update_notifications version_check_dev_decision{};
720
722 std::optional<bool> version_check_user_decision;
723
725 friend struct ::sharg::detail::test_accessor;
726
728 std::future<bool> version_check_future;
729
731 std::regex app_name_regex{"^[a-zA-Z0-9_-]+$"};
732
734 static constexpr std::string_view const option_end_identifier{"--"};
735
737 std::unique_ptr<parser> sub_parser{nullptr};
738
740 std::vector<std::string> subcommands{};
741
749 std::variant<detail::format_parse,
750 detail::format_help,
751 detail::format_short_help,
752 detail::format_version,
753 detail::format_html,
754 detail::format_man,
755 detail::format_tdl,
756 detail::format_copyright>
757 format{detail::format_short_help{}};
758
760 std::unordered_set<detail::id_pair> used_option_ids{{'h', "help"},
761 {'\0' /*hh*/, "advanced-help"},
762 {'\0', "hh"},
763 {'\0', "export-help"},
764 {'\0', "version"},
765 {'\0', "copyright"}};
766
768 std::vector<std::string> format_arguments{};
769
771 std::vector<std::string> arguments{};
772
774 std::vector<std::string> executable_name{};
775
778
780 std::vector<std::function<void()>> operations;
781
809 void determine_format_and_subcommand()
810 {
811 assert(!arguments.empty());
812
813 auto it = arguments.begin();
814 std::string_view arg{*it};
815
816 executable_name.emplace_back(arg);
817
818 // Helper function for reading the next argument. This makes it more obvious that we are
819 // incrementing `it` (version-check, and export-help).
820 auto read_next_arg = [this, &it, &arg]() -> bool
821 {
822 assert(it != arguments.end());
823
824 if (++it == arguments.end())
825 return false;
826
827 arg = *it;
828 return true;
829 };
830
831 // Helper function for finding and processing subcommands.
832 auto found_subcommand = [this, &it, &arg]() -> bool
833 {
834 if (subcommands.empty())
835 return false;
836
837 if (std::ranges::find(subcommands, arg) != subcommands.end())
838 {
839 sub_parser = std::make_unique<parser>(info.app_name + "-" + arg.data(),
840 std::vector<std::string>{it, arguments.end()},
842
843 // Add the original calls to the front, e.g. ["raptor"],
844 // s.t. ["raptor", "build"] will be the list after constructing the subparser
845 sub_parser->executable_name.insert(sub_parser->executable_name.begin(),
846 executable_name.begin(),
847 executable_name.end());
848 return true;
849 }
850 else
851 {
852 // Positional options are forbidden by design.
853 // Flags and options, which both start with '-', are allowed for the top-level parser.
854 // Otherwise, this is an unknown subcommand.
855 if (!arg.starts_with('-'))
856 {
857 std::string message = "You specified an unknown subcommand! Available subcommands are: [";
858 for (std::string const & command : subcommands)
859 message += command + ", ";
860 message.replace(message.size() - 2, 2, "]. Use -h/--help for more information.");
861
862 throw user_input_error{message};
863 }
864 }
865
866 return false;
867 };
868
869 // Process the arguments.
870 for (; read_next_arg();)
871 {
872 // The argument is a known option.
873 if (options.contains(std::string{arg}))
874 {
875 // No futher checks are needed.
876 format_arguments.emplace_back(arg);
877
878 // Consume the next argument (the option value) if possible.
879 if (read_next_arg())
880 {
881 format_arguments.emplace_back(arg);
882 continue;
883 }
884 else // Too few arguments. This is handled by format_parse.
885 {
886 break;
887 }
888 }
889
890 // If we have a subcommand, all further arguments are passed to the subparser.
891 if (found_subcommand())
892 break;
893
894 if (arg == "-h" || arg == "--help")
895 {
896 format = detail::format_help{subcommands, version_check_dev_decision, false};
897 }
898 else if (arg == "-hh" || arg == "--advanced-help")
899 {
900 format = detail::format_help{subcommands, version_check_dev_decision, true};
901 }
902 else if (arg == "--version")
903 {
904 format = detail::format_version{};
905 }
906 else if (arg == "--copyright")
907 {
908 format = detail::format_copyright{};
909 }
910 else if (arg == "--export-help" || arg.starts_with("--export-help="))
911 {
912 arg.remove_prefix(std::string_view{"--export-help"}.size());
913
914 // --export-help man
915 if (arg.empty())
916 {
917 if (!read_next_arg())
918 throw too_few_arguments{"Option --export-help must be followed by a value."};
919 }
920 else // --export-help=man
921 {
922 arg.remove_prefix(1u);
923 }
924
925 if (arg == "html")
926 format = detail::format_html{subcommands, version_check_dev_decision};
927 else if (arg == "man")
928 format = detail::format_man{subcommands, version_check_dev_decision};
929 else if (arg == "ctd")
930 format = detail::format_tdl{detail::format_tdl::FileFormat::CTD};
931 else if (arg == "cwl")
932 format = detail::format_tdl{detail::format_tdl::FileFormat::CWL};
933 else
934 throw validation_error{"Validation failed for option --export-help: "
935 "Value must be one of "
936 + detail::supported_exports + "."};
937 }
938 else if (arg == "--version-check")
939 {
940 if (!read_next_arg())
941 throw too_few_arguments{"Option --version-check must be followed by a value."};
942
943 if (arg == "1" || arg == "true")
944 version_check_user_decision = true;
945 else if (arg == "0" || arg == "false")
946 version_check_user_decision = false;
947 else
948 throw validation_error{"Value for option --version-check must be true (1) or false (0)."};
949 }
950 else
951 {
952 // Flags, positional options, options using an alternative syntax (--optionValue, --option=value), etc.
953 format_arguments.emplace_back(arg);
954 }
955 }
956
957 // A special format was set. We do not need to parse the format_arguments.
959 return;
960
961 // All special options have been handled. If there are arguments left or we have a subparser,
962 // we call format_parse. Oterhwise, we print the short help (default variant).
963 if (!format_arguments.empty() || sub_parser)
964 format = detail::format_parse(format_arguments);
965 }
966
976 void verify_identifiers(char const short_id, std::string const & long_id)
977 {
978 auto is_valid = [](char const c) -> bool
979 {
980 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') // alphanumeric
981 || c == '@' || c == '_' || c == '-'; // additional characters
982 };
983
984 if (short_id == '\0' && long_id.empty())
985 throw design_error{"Short and long identifiers may not both be empty."};
986
987 if (short_id != '\0')
988 {
989 if (short_id == '-' || !is_valid(short_id))
990 throw design_error{"Short identifiers may only contain alphanumeric characters, '_', or '@'."};
991 if (detail::id_pair::contains(used_option_ids, short_id))
992 throw design_error{"Short identifier '" + std::string(1, short_id) + "' was already used before."};
993 }
994
995 if (!long_id.empty())
996 {
997 if (long_id.size() == 1)
998 throw design_error{"Long identifiers must be either empty or longer than one character."};
999 if (long_id[0] == '-')
1000 throw design_error{"Long identifiers may not use '-' as first character."};
1001 if (!std::ranges::all_of(long_id, is_valid))
1002 throw design_error{"Long identifiers may only contain alphanumeric characters, '_', '-', or '@'."};
1003 if (detail::id_pair::contains(used_option_ids, long_id))
1004 throw design_error{"Long identifier '" + long_id + "' was already used before."};
1005 }
1006
1007 used_option_ids.emplace(short_id, long_id);
1008 }
1009
1011 template <typename validator_t>
1012 void verify_option_config(config<validator_t> const & config)
1013 {
1014 verify_identifiers(config.short_id, config.long_id);
1015
1016 if (config.short_id != '\0')
1017 options.emplace(std::string{"-"} + config.short_id);
1018 if (!config.long_id.empty())
1019 options.emplace(std::string{"--"} + config.long_id);
1020
1021 if (config.required && !config.default_message.empty())
1022 throw design_error{"A required option cannot have a default message."};
1023 }
1024
1026 template <typename validator_t>
1027 void verify_flag_config(config<validator_t> const & config)
1028 {
1029 verify_identifiers(config.short_id, config.long_id);
1030
1031 if (!config.default_message.empty())
1032 throw design_error{"A flag may not have a default message because the default is always `false`."};
1033 }
1034
1036 template <typename validator_t>
1037 void verify_positional_option_config(config<validator_t> const & config) const
1038 {
1039 if (config.short_id != '\0' || config.long_id != "")
1040 throw design_error{"Positional options are identified by their position on the command line. "
1041 "Short or long ids are not permitted!"};
1042
1043 if (config.advanced || config.hidden)
1044 throw design_error{"Positional options are always required and therefore cannot be advanced nor hidden!"};
1045
1046 if (!subcommands.empty())
1047 throw design_error{"You may only specify flags and options for the top-level parser."};
1048
1049 if (has_positional_list_option)
1050 throw design_error{"You added a positional option with a list value before so you cannot add "
1051 "any other positional options."};
1052
1053 if (!config.default_message.empty())
1054 throw design_error{"A positional option may not have a default message because it is always required."};
1055 }
1056
1066 inline void check_parse_not_called(std::string_view const function_name) const
1067 {
1068 if (parse_was_called)
1069 throw design_error{detail::to_string(function_name.data(), " may only be used before calling parse().")};
1070 }
1071
1079 inline void verify_app_and_subcommand_names() const
1080 {
1081 // Before creating the detail::version_checker, we have to make sure that
1082 // malicious code cannot be injected through the app name.
1083 if (!std::regex_match(info.app_name, app_name_regex))
1084 {
1085 throw design_error{("The application name must only contain alpha-numeric characters or '_' and '-' "
1086 "(regex: \"^[a-zA-Z0-9_-]+$\").")};
1087 }
1088
1089 for (auto & sub : this->subcommands)
1090 {
1091 if (!std::regex_match(sub, app_name_regex))
1092 {
1093 throw design_error{"The subcommand name must only contain alpha-numeric characters or '_' and '-' "
1094 "(regex: \"^[a-zA-Z0-9_-]+$\")."};
1095 }
1096 }
1097 }
1098
1104 inline void run_version_check()
1105 {
1106 detail::version_checker app_version{info.app_name, info.version, info.url};
1107
1108 if (app_version.decide_if_check_is_performed(version_check_dev_decision, version_check_user_decision))
1109 {
1110 // must be done before calling parse on the format because this might std::exit
1111 std::promise<bool> app_version_prom;
1112 version_check_future = app_version_prom.get_future();
1113 app_version(std::move(app_version_prom));
1114 }
1115 }
1116
1127 inline void parse_format()
1128 {
1129 auto format_parse_fn = [this]<typename format_t>(format_t & f)
1130 {
1132 f.parse(info, executable_name);
1133 else
1134 f.parse(info);
1135 };
1136
1137 std::visit(std::move(format_parse_fn), format);
1138 }
1139};
1140
1141} // namespace sharg
T all_of(T... args)
T cbegin(T... args)
Parser exception that is thrown whenever there is an design error directed at the developer of the ap...
Definition exceptions.hpp:207
The Sharg command line parser.
Definition parser.hpp:154
void add_option(option_type &value, config< validator_type > const &config)
Adds an option to the sharg::parser.
Definition parser.hpp:241
void add_flag(bool &value, config< validator_type > const &config)
Adds a flag to the sharg::parser.
Definition parser.hpp:274
parser(std::string app_name, std::vector< std::string > arguments, update_notifications version_updates=update_notifications::on, std::vector< std::string > const &subcommands={})
Initializes an sharg::parser object from the command line arguments.
Definition parser.hpp:181
parser()=delete
Deleted.
parser(std::string app_name, int const argc, char const *const *const argv, update_notifications version_updates=update_notifications::on, std::vector< std::string > const &subcommands={})
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition parser.hpp:193
void add_subsection(std::string const &title, bool const advanced_only=false)
Adds an help page subsection to the sharg::parser.
Definition parser.hpp:555
bool is_option_set(id_type const &id) const
Checks whether the option identifier (id) was set on the command line by the user.
Definition parser.hpp:490
void add_subcommands(std::vector< std::string > const &subcommands)
Adds subcommands to the parser.
Definition parser.hpp:648
void add_positional_option(option_type &value, config< validator_type > const &config)
Adds a positional option to the sharg::parser.
Definition parser.hpp:325
parser_meta_data info
Aggregates all parser related meta data (see sharg::parser_meta_data struct).
Definition parser.hpp:709
parser(parser &&)=default
Defaulted.
void parse()
Initiates the actual command line parsing.
Definition parser.hpp:414
parser & operator=(parser const &)=delete
Deleted.
parser(parser const &)=delete
Deleted.
void add_list_item(std::string const &key, std::string const &desc, bool const advanced_only=false)
Adds an help page list item (key-value) to the sharg::parser.
Definition parser.hpp:620
parser & operator=(parser &&)=default
Defaulted.
void add_section(std::string const &title, bool const advanced_only=false)
Adds an help page section to the sharg::parser.
Definition parser.hpp:528
~parser()
The destructor.
Definition parser.hpp:202
parser & get_sub_parser()
Returns a reference to the sub-parser instance if subcommand parsing was enabled.
Definition parser.hpp:448
void add_line(std::string const &text, bool is_paragraph=false, bool const advanced_only=false)
Adds an help page text line to the sharg::parser.
Definition parser.hpp:583
Checks whether the the type can be used in an add_(positional_)option call on the parser.
Definition concept.hpp:91
Provides sharg::config class.
T data(T... args)
T empty(T... args)
T cend(T... args)
T exit(T... args)
T find(T... args)
Provides the format_help struct that print the help page to the command line and the two child format...
Provides the format_html struct and its helper functions.
Provides the format_man struct and its helper functions.
Provides the format_parse class.
Provides the format_tdl struct and its helper functions.
T format(T... args)
T get_future(T... args)
update_notifications
Indicates whether application allows automatic update notifications by the sharg::parser.
Definition auxiliary.hpp:26
@ off
Automatic update notifications should be disabled.
@ on
Automatic update notifications should be enabled.
T insert(T... args)
T is_same_v
T regex_match(T... args)
T replace(T... args)
T size(T... args)
T sort(T... args)
Option struct that is passed to the sharg::parser::add_option() function.
Definition config.hpp:43
Stores all parser related meta information of the sharg::parser.
Definition auxiliary.hpp:45
std::string app_name
The application name that will be displayed on the help page.
Definition auxiliary.hpp:51
std::string version
The version information MAJOR.MINOR.PATH (e.g. 3.1.3)
Definition auxiliary.hpp:54
std::string url
A link to your github/gitlab project with the newest release.
Definition auxiliary.hpp:71
T unique(T... args)
Provides the version check functionality.
T visit(T... args)
Hide me