SeqAn3 3.2.0-rc.1
The Modern C++ library for sequence analysis.
argument_parser.hpp
Go to the documentation of this file.
1// -----------------------------------------------------------------------------------------------------
2// Copyright (c) 2006-2021, Knut Reinert & Freie Universität Berlin
3// Copyright (c) 2016-2021, Knut Reinert & MPI für molekulare Genetik
4// This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License
5// shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md
6// -----------------------------------------------------------------------------------------------------
7
13#pragma once
14
15#include <future>
16#include <iostream>
17#include <set>
18#include <sstream>
19#include <string>
20#include <variant>
21#include <vector>
22#include <regex>
23
24// #include <seqan3/argument_parser/detail/format_ctd.hpp>
33
34namespace seqan3
35{
36
152{
153public:
157 argument_parser() = delete;
158 argument_parser(argument_parser const &) = default;
162
180 int const argc,
181 char const * const * const argv,
184 version_check_dev_decision{version_updates},
185 subcommands{std::move(subcommands)}
186 {
187 if (!std::regex_match(app_name, app_name_regex))
188 {
189 throw design_error{("The application name must only contain alpha-numeric characters or '_' and '-' "
190 "(regex: \"^[a-zA-Z0-9_-]+$\").")};
191 }
192
193 for (auto & sub : this->subcommands)
194 {
196 {
197 throw design_error{"The subcommand name must only contain alpha-numeric characters or '_' and '-' "
198 "(regex: \"^[a-zA-Z0-9_-]+$\")."};
199 }
200 }
201
202 info.app_name = std::move(app_name);
203
204 init(argc, argv);
205 }
206
209 {
210 // wait for another 3 seconds
213 }
215
239 template <typename option_type, validator validator_type = detail::default_validator<option_type>>
243 std::invocable<validator_type, option_type>
245 void add_option(option_type & value,
246 char const short_id,
247 std::string const & long_id,
248 std::string const & desc,
250 validator_type option_validator = validator_type{}) // copy to bind rvalues
251 {
252 if (sub_parser != nullptr)
253 throw design_error{"You may only specify flags for the top-level parser."};
254
255 verify_identifiers(short_id, long_id);
256 // copy variables into the lambda because the calls are pushed to a stack
257 // and the references would go out of scope.
258 std::visit([=, &value] (auto & f) { f.add_option(value, short_id, long_id, desc, spec, option_validator); },
259 format);
260 }
261
273 void add_flag(bool & value,
274 char const short_id,
275 std::string const & long_id,
276 std::string const & desc,
278 {
279 if (value)
280 throw design_error("A flag's default value must be false.");
281
282 verify_identifiers(short_id, long_id);
283 // copy variables into the lambda because the calls are pushed to a stack
284 // and the references would go out of scope.
285 std::visit([=, &value] (auto & f) { f.add_flag(value, short_id, long_id, desc, spec); }, format);
286 }
287
308 template <typename option_type, validator validator_type = detail::default_validator<option_type>>
312 std::invocable<validator_type, option_type>
314 void add_positional_option(option_type & value,
315 std::string const & desc,
316 validator_type option_validator = validator_type{}) // copy to bind rvalues
317 {
318 if (sub_parser != nullptr)
319 throw design_error{"You may only specify flags for the top-level parser."};
320
322 throw design_error{"You added a positional option with a list value before so you cannot add "
323 "any other positional options."};
324
325 if constexpr (detail::is_container_option<option_type>)
326 has_positional_list_option = true; // keep track of a list option because there must be only one!
327
328 // copy variables into the lambda because the calls are pushed to a stack
329 // and the references would go out of scope.
330 std::visit([=, &value] (auto & f) { f.add_positional_option(value, desc, option_validator); }, format);
331 }
333
399 void parse()
400 {
402 throw design_error("The function parse() must only be called once!");
403
405
406 if (std::holds_alternative<detail::format_parse>(format) && !subcommands.empty() && sub_parser == nullptr)
407 {
408 throw too_few_arguments{detail::to_string("You either forgot or misspelled the subcommand! Please specify"
409 " which sub-program you want to use: one of ", subcommands,
410 ". Use -h/--help for more information.")};
411 }
412
413 if (app_version.decide_if_check_is_performed(version_check_dev_decision, version_check_user_decision))
414 {
415 // must be done before calling parse on the format because this might std::exit
416 std::promise<bool> app_version_prom;
417 version_check_future = app_version_prom.get_future();
418 app_version(std::move(app_version_prom));
419 }
420
421 std::visit([this] (auto & f) { f.parse(info); }, format);
422 parse_was_called = true;
423 }
424
428 {
429 if (sub_parser == nullptr)
430 {
431 throw design_error("No subcommand was provided at the construction of the argument parser!");
432 }
433
434 return *sub_parser;
435 }
436
463 template <typename id_type>
465 requires std::same_as<id_type, char> || std::constructible_from<std::string, id_type>
467 bool is_option_set(id_type const & id) const
468 {
469 if (!parse_was_called)
470 throw design_error{"You can only ask which options have been set after calling the function `parse()`."};
471
472 // the detail::format_parse::find_option_id call in the end expects either a char or std::string
473 using char_or_string_t = std::conditional_t<std::same_as<id_type, char>, char, std::string>;
474 char_or_string_t short_or_long_id = {id}; // e.g. convert char * to string here if necessary
475
476 if constexpr (!std::same_as<id_type, char>) // long id was given
477 {
478 if (short_or_long_id.size() == 1)
479 {
480 throw design_error{"Long option identifiers must be longer than one character! If " + short_or_long_id +
481 "' was meant to be a short identifier, please pass it as a char ('') not a string"
482 " (\"\")!"};
483 }
484 }
485
487 throw design_error{"You can only ask for option identifiers that you added with add_option() before."};
488
489 // we only need to search for an option before the `end_of_options_indentifier` (`--`)
491 auto option_it = detail::format_parse::find_option_id(cmd_arguments.begin(), end_of_options, short_or_long_id);
492 return option_it != end_of_options;
493 }
494
497
505 {
506 std::visit([&] (auto & f) { f.add_section(title, spec); }, format);
507 }
508
516 {
517 std::visit([&] (auto & f) { f.add_subsection(title, spec); }, format);
518 }
519
529 void add_line(std::string const & text, bool is_paragraph = false, option_spec const spec = option_spec::standard)
530 {
531 std::visit([&] (auto & f) { f.add_line(text, is_paragraph, spec); }, format);
532 }
533
552 void add_list_item(std::string const & key,
553 std::string const & desc,
555 {
556 std::visit([&] (auto & f) { f.add_list_item(key, desc, spec); }, format);
557 }
559
609
610private:
612 bool parse_was_called{false};
613
616
619
622
624 friend struct ::seqan3::detail::test_accessor;
625
628
630 std::regex app_name_regex{"^[a-zA-Z0-9_-]+$"};
631
633 static constexpr std::string_view const end_of_options_indentifier{"--"};
634
637
640
655 detail::format_ctd*/> format{detail::format_help{{}, false}}; // Will be overwritten in any case.
656
658 std::set<std::string> used_option_ids{"h", "hh", "help", "advanced-help", "export-help", "version", "copyright"};
659
662
695 void init(int argc, char const * const * const argv)
696 {
697 if (argc <= 1) // no arguments provided
698 {
700 return;
701 }
702
703 bool special_format_was_set{false};
704
705
706 for (int i = 1, argv_len = argc; i < argv_len; ++i) // start at 1 to skip binary name
707 {
708 std::string arg{argv[i]};
709
711 {
712 sub_parser = std::make_unique<argument_parser>(info.app_name + "-" + arg,
713 argc - i,
714 argv + i,
716 break;
717 }
718
719 if (arg == "-h" || arg == "--help")
720 {
723 special_format_was_set = true;
724 }
725 else if (arg == "-hh" || arg == "--advanced-help")
726 {
729 special_format_was_set = true;
730 }
731 else if (arg == "--version")
732 {
734 special_format_was_set = true;
735 }
736 else if (arg.substr(0, 13) == "--export-help") // --export-help=man is also allowed
737 {
738 std::string export_format;
739
740 if (arg.size() > 13)
741 {
742 export_format = arg.substr(14);
743 }
744 else
745 {
746 if (argv_len <= i + 1)
747 throw too_few_arguments{"Option --export-help must be followed by a value."};
748 export_format = {argv[i+1]};
749 }
750
751 if (export_format == "html")
753 else if (export_format == "man")
755 // TODO (smehringer) use when CTD support is available
756 // else if (export_format == "ctd")
757 // format = detail::format_ctd{};
758 else
759 throw validation_error{"Validation failed for option --export-help: "
760 "Value must be one of [html, man]"};
762 special_format_was_set = true;
763 }
764 else if (arg == "--copyright")
765 {
767 special_format_was_set = true;
768 }
769 else if (arg == "--version-check")
770 {
771 if (++i >= argv_len)
772 throw too_few_arguments{"Option --version-check must be followed by a value."};
773
774 arg = argv[i];
775
776 if (arg == "1" || arg == "true")
778 else if (arg == "0" || arg == "false")
780 else
781 throw validation_error{"Value for option --version-check must be true (1) or false (0)."};
782
783 // in case --version-check is specified it shall not be passed to format_parse()
784 argc -= 2;
785 }
786 else
787 {
788 cmd_arguments.push_back(std::move(arg));
789 }
790 }
791
792 if (!special_format_was_set)
794 }
795
798 {
799 add_subsection("Basic options:");
800 add_list_item("\\fB-h\\fP, \\fB--help\\fP", "Prints the help page.");
801 add_list_item("\\fB-hh\\fP, \\fB--advanced-help\\fP",
802 "Prints the help page including advanced options.");
803 add_list_item("\\fB--version\\fP", "Prints the version information.");
804 add_list_item("\\fB--copyright\\fP", "Prints the copyright/license information.");
805 add_list_item("\\fB--export-help\\fP (std::string)",
806 "Export the help page information. Value must be one of [html, man].");
808 add_list_item("\\fB--version-check\\fP (bool)", "Whether to check for the newest app version. Default: true.");
809 }
810
816 template <typename id_type>
817 bool id_exists(id_type const & id)
818 {
820 return false;
821 return (!(used_option_ids.insert(std::string({id}))).second);
822 }
823
833 void verify_identifiers(char const short_id, std::string const & long_id)
834 {
835 auto constexpr allowed = is_alnum || is_char<'_'> || is_char<'@'>;
836
837 if (id_exists(short_id))
838 throw design_error("Option Identifier '" + std::string(1, short_id) + "' was already used before.");
839 if (id_exists(long_id))
840 throw design_error("Option Identifier '" + long_id + "' was already used before.");
841 if (long_id.length() == 1)
842 throw design_error("Long IDs must be either empty, or longer than one character.");
843 if (!allowed(short_id) && !is_char<'\0'>(short_id))
844 throw design_error("Option identifiers may only contain alphanumeric characters, '_', or '@'.");
845 if (long_id.size() > 0 && is_char<'-'>(long_id[0]))
846 throw design_error("First character of long ID cannot be '-'.");
847
848 std::for_each(long_id.begin(), long_id.end(), [&allowed] (char c)
849 {
850 if (!(allowed(c) || is_char<'-'>(c)))
851 throw design_error("Long identifiers may only contain alphanumeric characters, '_', '-', or '@'.");
852 });
854 throw design_error("Option Identifiers cannot both be empty.");
855 }
856};
857
858} // namespace seqan3
T begin(T... args)
The SeqAn command line parser.
Definition: argument_parser.hpp:152
update_notifications version_check_dev_decision
Set on construction and indicates whether the developer deactivates the version check calls completel...
Definition: argument_parser.hpp:618
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:273
std::regex app_name_regex
Validates the application name to ensure an escaped server call.
Definition: argument_parser.hpp:630
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:314
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:179
argument_parser & operator=(argument_parser &&)=default
Defaulted.
~argument_parser()
The destructor.
Definition: argument_parser.hpp:208
argument_parser_meta_data info
Aggregates all parser related meta data (see seqan3::argument_parser_meta_data struct).
Definition: argument_parser.hpp:608
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:467
std::unique_ptr< argument_parser > sub_parser
Stores the sub-parser in case subcommand parsing is enabled.
Definition: argument_parser.hpp:636
void verify_identifiers(char const short_id, std::string const &long_id)
Verifies that the short and the long identifiers are correctly formatted.
Definition: argument_parser.hpp:833
std::set< std::string > used_option_ids
List of option/flag identifiers that are already used.
Definition: argument_parser.hpp:658
argument_parser(argument_parser &&)=default
Defaulted.
bool has_positional_list_option
Keeps track of whether the user has added a positional list option to check if this was the very last...
Definition: argument_parser.hpp:615
bool id_exists(id_type const &id)
Checks whether the long identifier has already been used before.
Definition: argument_parser.hpp:817
void parse()
Initiates the actual command line parsing.
Definition: argument_parser.hpp:399
static constexpr std::string_view const end_of_options_indentifier
Signals the argument parser that no options follow this string but only positional arguments.
Definition: argument_parser.hpp:633
argument_parser()=delete
Deleted.
std::future< bool > version_check_future
The future object that keeps track of the detached version check call thread.
Definition: argument_parser.hpp:627
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:245
std::vector< std::string > subcommands
Stores the sub-parser names in case subcommand parsing is enabled.
Definition: argument_parser.hpp:639
bool parse_was_called
Keeps track of whether the parse function has been called already.
Definition: argument_parser.hpp:612
void init_standard_options()
Adds standard options to the help page.
Definition: argument_parser.hpp:797
void init(int argc, char const *const *const argv)
Initializes the seqan3::argument_parser class on construction.
Definition: argument_parser.hpp:695
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:529
std::vector< std::string > cmd_arguments
The command line arguments.
Definition: argument_parser.hpp:661
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:552
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:504
std::optional< bool > version_check_user_decision
Whether the user specified to perform the version check (true) or not (false), default unset.
Definition: argument_parser.hpp:621
std::variant< detail::format_parse, detail::format_help, detail::format_short_help, detail::format_version, detail::format_html, detail::format_man, detail::format_copyright > format
The format of the argument parser that decides the behavior when calling the seqan3::argument_parser:...
Definition: argument_parser.hpp:655
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:515
argument_parser & operator=(argument_parser const &)=default
Defaulted.
argument_parser & get_sub_parser()
Returns a reference to the sub-parser instance if subcommand parsing was enabled.
Definition: argument_parser.hpp:427
argument_parser(argument_parser const &)=default
Defaulted.
Argument parser exception that is thrown whenever there is an design error directed at the developer ...
Definition: exceptions.hpp:143
The format that prints the help page to std::cout.
Definition: format_help.hpp:40
The format that prints the help page as html to std::cout.
Definition: format_html.hpp:37
The format that prints the help page information formatted for a man page to std::cout.
Definition: format_man.hpp:38
The format that organizes the actual parsing of command line arguments.
Definition: format_parse.hpp:54
static iterator_type find_option_id(iterator_type begin_it, iterator_type end_it, id_type const &id)
Finds the position of a short/long identifier in format_parse::argv.
Definition: format_parse.hpp:185
static bool is_empty_id(id_type const &id)
Checks whether id is empty.
Definition: format_parse.hpp:155
The format that prints a short help message to std::cout.
Definition: format_help.hpp:399
The format that prints the version to std::cout.
Definition: format_help.hpp:431
A functor whose operator() performs the server http request and version checks.
Definition: version_check.hpp:59
Argument parser exception thrown when too few arguments are provided.
Definition: exceptions.hpp:76
Argument parser exception thrown when an argument could not be casted to the according type.
Definition: exceptions.hpp:124
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:247
@ standard
The default were no checking or special displaying is happening.
Definition: auxiliary.hpp:248
auto constexpr is_alnum
Checks whether c is a alphanumeric character.
Definition: predicate.hpp:202
constexpr ptrdiff_t find
Get the index of the first occurrence of a type in a pack.
Definition: traits.hpp:187
T insert(T... args)
Checks whether the the type can be used in an add_(positional_)option call on the argument parser.
std::string to_string(value_type &&...values)
Streams all parameters via the seqan3::debug_stream and returns a concatenated string.
Definition: to_string.hpp:29
The main SeqAn3 namespace.
Definition: aligned_sequence_concept.hpp:29
update_notifications
Indicates whether application allows automatic update notifications by the seqan3::argument_parser.
Definition: auxiliary.hpp:266
@ off
Automatic update notifications should be disabled.
@ on
Automatic update notifications should be enabled.
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:285
std::string version
The version information MAJOR.MINOR.PATH (e.g. 3.1.3)
Definition: auxiliary.hpp:293
std::string app_name
The application name that will be displayed on the help page.
Definition: auxiliary.hpp:291
std::string url
A link to your github/gitlab project with the newest release.
Definition: auxiliary.hpp:305
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)