SeqAn3 3.4.0-rc.1
The Modern C++ library for sequence analysis.
Loading...
Searching...
No Matches
argument_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 <future>
13#include <iostream>
14#include <regex>
15#include <set>
16#include <sstream>
17#include <string>
18#include <variant>
19#include <vector>
20
21// #include <seqan3/argument_parser/detail/format_ctd.hpp>
30
31namespace seqan3
32{
33
145{
146public:
150 argument_parser() = delete;
155
173 int const argc,
174 char const * const * const argv,
176 std::vector<std::string> subcommands = {}) :
177 version_check_dev_decision{version_updates},
178 subcommands{std::move(subcommands)}
179 {
180 if (!std::regex_match(app_name, app_name_regex))
181 {
182 throw design_error{("The application name must only contain alpha-numeric characters or '_' and '-' "
183 "(regex: \"^[a-zA-Z0-9_-]+$\").")};
184 }
185
186 for (auto & sub : this->subcommands)
187 {
188 if (!std::regex_match(sub, app_name_regex))
189 {
190 throw design_error{"The subcommand name must only contain alpha-numeric characters or '_' and '-' "
191 "(regex: \"^[a-zA-Z0-9_-]+$\")."};
192 }
193 }
194
195 info.app_name = std::move(app_name);
196
197 init(argc, argv);
198 }
199
202 {
203 // wait for another 3 seconds
204 if (version_check_future.valid())
205 version_check_future.wait_for(std::chrono::seconds(3));
206 }
208
232 template <typename option_type, validator validator_type = detail::default_validator<option_type>>
235 && std::invocable<validator_type, option_type>
236 void add_option(option_type & value,
237 char const short_id,
238 std::string const & long_id,
239 std::string const & desc,
241 validator_type option_validator = validator_type{}) // copy to bind rvalues
242 {
243 if (sub_parser != nullptr)
244 throw design_error{"You may only specify flags for the top-level parser."};
245
246 verify_identifiers(short_id, long_id);
247 // copy variables into the lambda because the calls are pushed to a stack
248 // and the references would go out of scope.
250 [=, &value](auto & f)
251 {
252 f.add_option(value, short_id, long_id, desc, spec, option_validator);
253 },
254 format);
255 }
256
268 void add_flag(bool & value,
269 char const short_id,
270 std::string const & long_id,
271 std::string const & desc,
273 {
274 if (value)
275 throw design_error("A flag's default value must be false.");
276
277 verify_identifiers(short_id, long_id);
278 // copy variables into the lambda because the calls are pushed to a stack
279 // and the references would go out of scope.
281 [=, &value](auto & f)
282 {
283 f.add_flag(value, short_id, long_id, desc, spec);
284 },
285 format);
286 }
287
308 template <typename option_type, validator validator_type = detail::default_validator<option_type>>
311 && std::invocable<validator_type, option_type>
312 void add_positional_option(option_type & value,
313 std::string const & desc,
314 validator_type option_validator = validator_type{}) // copy to bind rvalues
315 {
316 if (sub_parser != nullptr)
317 throw design_error{"You may only specify flags for the top-level parser."};
318
319 if (has_positional_list_option)
320 throw design_error{"You added a positional option with a list value before so you cannot add "
321 "any other positional options."};
322
323 if constexpr (detail::is_container_option<option_type>)
324 has_positional_list_option = true; // keep track of a list option because there must be only one!
325
326 // copy variables into the lambda because the calls are pushed to a stack
327 // and the references would go out of scope.
329 [=, &value](auto & f)
330 {
331 f.add_positional_option(value, desc, option_validator);
332 },
333 format);
334 }
336
402 void parse()
403 {
404 if (parse_was_called)
405 throw design_error("The function parse() must only be called once!");
406
407 detail::version_checker app_version{info.app_name, info.version, info.url};
408
409 if (std::holds_alternative<detail::format_parse>(format) && !subcommands.empty() && sub_parser == nullptr)
410 {
411 throw too_few_arguments{detail::to_string("You either forgot or misspelled the subcommand! Please specify"
412 " which sub-program you want to use: one of ",
413 subcommands,
414 ". Use -h/--help for more information.")};
415 }
416
417 if (app_version.decide_if_check_is_performed(version_check_dev_decision, version_check_user_decision))
418 {
419 // must be done before calling parse on the format because this might std::exit
420 std::promise<bool> app_version_prom;
421 version_check_future = app_version_prom.get_future();
422 app_version(std::move(app_version_prom));
423 }
424
426 [this](auto & f)
427 {
428 f.parse(info);
429 },
430 format);
431 parse_was_called = true;
432 }
433
437 {
438 if (sub_parser == nullptr)
439 {
440 throw design_error("No subcommand was provided at the construction of the argument parser!");
441 }
442
443 return *sub_parser;
444 }
445
472 template <typename id_type>
473 requires std::same_as<id_type, char> || std::constructible_from<std::string, id_type> bool
474 is_option_set(id_type const & id) const
475 {
476 if (!parse_was_called)
477 throw design_error{"You can only ask which options have been set after calling the function `parse()`."};
478
479 // the detail::format_parse::find_option_id call in the end expects either a char or std::string
480 using char_or_string_t = std::conditional_t<std::same_as<id_type, char>, char, std::string>;
481 char_or_string_t short_or_long_id = {id}; // e.g. convert char * to string here if necessary
482
483 if constexpr (!std::same_as<id_type, char>) // long id was given
484 {
485 if (short_or_long_id.size() == 1)
486 {
487 throw design_error{"Long option identifiers must be longer than one character! If " + short_or_long_id
488 + "' was meant to be a short identifier, please pass it as a char ('') not a string"
489 " (\"\")!"};
490 }
491 }
492
493 if (std::find(used_option_ids.begin(), used_option_ids.end(), std::string{id}) == used_option_ids.end())
494 throw design_error{"You can only ask for option identifiers that you added with add_option() before."};
495
496 // we only need to search for an option before the `end_of_options_indentifier` (`--`)
497 auto end_of_options = std::find(cmd_arguments.begin(), cmd_arguments.end(), end_of_options_indentifier);
498 auto option_it = detail::format_parse::find_option_id(cmd_arguments.begin(), end_of_options, short_or_long_id);
499 return option_it != end_of_options;
500 }
501
504
512 {
514 [&](auto & f)
515 {
516 f.add_section(title, spec);
517 },
518 format);
519 }
520
528 {
530 [&](auto & f)
531 {
532 f.add_subsection(title, spec);
533 },
534 format);
535 }
536
546 void add_line(std::string const & text, bool is_paragraph = false, option_spec const spec = option_spec::standard)
547 {
549 [&](auto & f)
550 {
551 f.add_line(text, is_paragraph, spec);
552 },
553 format);
554 }
555
574 void
576 {
578 [&](auto & f)
579 {
580 f.add_list_item(key, desc, spec);
581 },
582 format);
583 }
585
635
636private:
638 bool parse_was_called{false};
639
641 bool has_positional_list_option{false};
642
644 update_notifications version_check_dev_decision{};
645
647 std::optional<bool> version_check_user_decision;
648
650 friend struct ::seqan3::detail::test_accessor;
651
653 std::future<bool> version_check_future;
654
656 std::regex app_name_regex{"^[a-zA-Z0-9_-]+$"};
657
659 static constexpr std::string_view const end_of_options_indentifier{"--"};
660
662 std::unique_ptr<argument_parser> sub_parser{nullptr};
663
665 std::vector<std::string> subcommands{};
666
674 std::variant<detail::format_parse,
675 detail::format_help,
676 detail::format_short_help,
677 detail::format_version,
678 detail::format_html,
679 detail::format_man,
680 detail::format_copyright/*,
681 detail::format_ctd*/> format{detail::format_help{{}, false}}; // Will be overwritten in any case.
682
684 std::set<std::string> used_option_ids{"h", "hh", "help", "advanced-help", "export-help", "version", "copyright"};
685
687 std::vector<std::string> cmd_arguments{};
688
721 void init(int argc, char const * const * const argv)
722 {
723 if (argc <= 1) // no arguments provided
724 {
725 format = detail::format_short_help{};
726 return;
727 }
728
729 bool special_format_was_set{false};
730
731 for (int i = 1, argv_len = argc; i < argv_len; ++i) // start at 1 to skip binary name
732 {
733 std::string arg{argv[i]};
734
735 if (std::ranges::find(subcommands, arg) != subcommands.end())
736 {
737 sub_parser = std::make_unique<argument_parser>(info.app_name + "-" + arg,
738 argc - i,
739 argv + i,
741 break;
742 }
743
744 if (arg == "-h" || arg == "--help")
745 {
746 format = detail::format_help{subcommands, false};
747 init_standard_options();
748 special_format_was_set = true;
749 }
750 else if (arg == "-hh" || arg == "--advanced-help")
751 {
752 format = detail::format_help{subcommands, true};
753 init_standard_options();
754 special_format_was_set = true;
755 }
756 else if (arg == "--version")
757 {
758 format = detail::format_version{};
759 special_format_was_set = true;
760 }
761 else if (arg.substr(0, 13) == "--export-help") // --export-help=man is also allowed
762 {
763 std::string export_format;
764
765 if (arg.size() > 13)
766 {
767 export_format = arg.substr(14);
768 }
769 else
770 {
771 if (argv_len <= i + 1)
772 throw too_few_arguments{"Option --export-help must be followed by a value."};
773 export_format = argv[i + 1];
774 }
775
776 if (export_format == "html")
777 format = detail::format_html{subcommands};
778 else if (export_format == "man")
779 format = detail::format_man{subcommands};
780 // TODO (smehringer) use when CTD support is available
781 // else if (export_format == "ctd")
782 // format = detail::format_ctd{};
783 else
784 throw validation_error{"Validation failed for option --export-help: "
785 "Value must be one of [html, man]"};
786 init_standard_options();
787 special_format_was_set = true;
788 }
789 else if (arg == "--copyright")
790 {
791 format = detail::format_copyright{};
792 special_format_was_set = true;
793 }
794 else if (arg == "--version-check")
795 {
796 if (++i >= argv_len)
797 throw too_few_arguments{"Option --version-check must be followed by a value."};
798
799 arg = argv[i];
800
801 if (arg == "1" || arg == "true")
802 version_check_user_decision = true;
803 else if (arg == "0" || arg == "false")
804 version_check_user_decision = false;
805 else
806 throw validation_error{"Value for option --version-check must be true (1) or false (0)."};
807
808 // in case --version-check is specified it shall not be passed to format_parse()
809 argc -= 2;
810 }
811 else
812 {
813 cmd_arguments.push_back(std::move(arg));
814 }
815 }
816
817 if (!special_format_was_set)
818 format = detail::format_parse(argc, cmd_arguments);
819 }
820
822 void init_standard_options()
823 {
824 add_subsection("Basic options:");
825 add_list_item("\\fB-h\\fP, \\fB--help\\fP", "Prints the help page.");
826 add_list_item("\\fB-hh\\fP, \\fB--advanced-help\\fP", "Prints the help page including advanced options.");
827 add_list_item("\\fB--version\\fP", "Prints the version information.");
828 add_list_item("\\fB--copyright\\fP", "Prints the copyright/license information.");
829 add_list_item("\\fB--export-help\\fP (std::string)",
830 "Export the help page information. Value must be one of [html, man].");
831 if (version_check_dev_decision == update_notifications::on)
832 add_list_item("\\fB--version-check\\fP (bool)",
833 "Whether to check for the newest app version. Default: true.");
834 }
835
841 template <typename id_type>
842 bool id_exists(id_type const & id)
843 {
844 if (detail::format_parse::is_empty_id(id))
845 return false;
846 return (!(used_option_ids.insert(std::string({id}))).second);
847 }
848
858 void verify_identifiers(char const short_id, std::string const & long_id)
859 {
860 constexpr auto allowed = is_alnum || is_char<'_'> || is_char<'@'>;
861
862 if (id_exists(short_id))
863 throw design_error("Option Identifier '" + std::string(1, short_id) + "' was already used before.");
864 if (id_exists(long_id))
865 throw design_error("Option Identifier '" + long_id + "' was already used before.");
866 if (long_id.length() == 1)
867 throw design_error("Long IDs must be either empty, or longer than one character.");
868 if (!allowed(short_id) && !is_char<'\0'>(short_id))
869 throw design_error("Option identifiers may only contain alphanumeric characters, '_', or '@'.");
870 if (long_id.size() > 0 && is_char<'-'>(long_id[0]))
871 throw design_error("First character of long ID cannot be '-'.");
872
873 std::for_each(long_id.begin(),
874 long_id.end(),
875 [&allowed](char c)
876 {
877 if (!(allowed(c) || is_char<'-'>(c)))
878 throw design_error(
879 "Long identifiers may only contain alphanumeric characters, '_', '-', or '@'.");
880 });
881 if (detail::format_parse::is_empty_id(short_id) && detail::format_parse::is_empty_id(long_id))
882 throw design_error("Option Identifiers cannot both be empty.");
883 }
884};
885
886} // namespace seqan3
T begin(T... args)
The SeqAn command line parser.
Definition argument_parser.hpp:145
void add_positional_option(option_type &value, std::string const &desc, validator_type option_validator=validator_type{})
Adds a positional option to the seqan3::argument_parser.
Definition argument_parser.hpp:312
void add_flag(bool &value, char const short_id, std::string const &long_id, std::string const &desc, option_spec const spec=option_spec::standard)
Adds a flag to the seqan3::argument_parser.
Definition argument_parser.hpp:268
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 argument_parser.hpp:474
argument_parser(argument_parser const &)=delete
Deleted. Holds std::future.
void add_option(option_type &value, char const short_id, std::string const &long_id, std::string const &desc, option_spec const spec=option_spec::standard, validator_type option_validator=validator_type{})
Adds an option to the seqan3::argument_parser.
Definition argument_parser.hpp:236
argument_parser(std::string const app_name, int const argc, char const *const *const argv, update_notifications version_updates=update_notifications::on, std::vector< std::string > subcommands={})
Initializes an seqan3::argument_parser object from the command line arguments.
Definition argument_parser.hpp:172
argument_parser & operator=(argument_parser &&)=default
Defaulted.
~argument_parser()
The destructor.
Definition argument_parser.hpp:201
argument_parser & operator=(argument_parser const &)=delete
Deleted. Holds std::future.
argument_parser_meta_data info
Aggregates all parser related meta data (see seqan3::argument_parser_meta_data struct).
Definition argument_parser.hpp:634
argument_parser(argument_parser &&)=default
Defaulted.
void parse()
Initiates the actual command line parsing.
Definition argument_parser.hpp:402
argument_parser()=delete
Deleted.
void add_line(std::string const &text, bool is_paragraph=false, option_spec const spec=option_spec::standard)
Adds an help page text line to the seqan3::argument_parser.
Definition argument_parser.hpp:546
void add_list_item(std::string const &key, std::string const &desc, option_spec const spec=option_spec::standard)
Adds an help page list item (key-value) to the seqan3::argument_parser.
Definition argument_parser.hpp:575
void add_section(std::string const &title, option_spec const spec=option_spec::standard)
Adds an help page section to the seqan3::argument_parser.
Definition argument_parser.hpp:511
void add_subsection(std::string const &title, option_spec const spec=option_spec::standard)
Adds an help page subsection to the seqan3::argument_parser.
Definition argument_parser.hpp:527
argument_parser & get_sub_parser()
Returns a reference to the sub-parser instance if subcommand parsing was enabled.
Definition argument_parser.hpp:436
Argument parser exception that is thrown whenever there is an design error directed at the developer ...
Definition exceptions.hpp:148
Argument parser exception thrown when too few arguments are provided.
Definition exceptions.hpp:76
T empty(T... args)
T end(T... args)
T find(T... args)
T for_each(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.
T get_future(T... args)
option_spec
Used to further specify argument_parser options/flags.
Definition auxiliary.hpp:245
@ standard
The default were no checking or special displaying is happening.
Definition auxiliary.hpp:246
constexpr auto is_alnum
Checks whether c is a alphanumeric character.
Definition predicate.hpp:194
constexpr auto is_char
Checks whether a given letter is the same as the template non-type argument.
Definition predicate.hpp:60
T insert(T... args)
Checks whether the the type can be used in an add_(positional_)option call on the argument parser.
The main SeqAn3 namespace.
Definition aligned_sequence_concept.hpp:26
update_notifications
Indicates whether application allows automatic update notifications by the seqan3::argument_parser.
Definition auxiliary.hpp:264
@ off
Automatic update notifications should be disabled.
@ on
Automatic update notifications should be enabled.
SeqAn specific customisations in the standard namespace.
T push_back(T... args)
T regex_match(T... args)
T length(T... args)
Stores all parser related meta information of the seqan3::argument_parser.
Definition auxiliary.hpp:283
std::string version
The version information MAJOR.MINOR.PATH (e.g. 3.1.3)
Definition auxiliary.hpp:291
std::string app_name
The application name that will be displayed on the help page.
Definition auxiliary.hpp:289
std::string url
A link to your github/gitlab project with the newest release.
Definition auxiliary.hpp:303
T substr(T... args)
Checks if program is run interactively and retrieves dimensions of terminal (Transferred from seqan2)...
Forward declares seqan3::detail::test_accessor.
Auxiliary for pretty printing of exception messages.
T valid(T... args)
Provides the version check functionality.
T visit(T... args)
T wait_for(T... args)
Hide me