SeqAn3 3.1.0
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>
35
36namespace seqan3
37{
38
154{
155public:
159 argument_parser() = delete;
160 argument_parser(argument_parser const &) = default;
164
182 int const argc,
183 char const * const * const argv,
185 std::vector<std::string> subcommands = {}) :
186 version_check_dev_decision{version_updates},
187 subcommands{std::move(subcommands)}
188 {
189 if (!std::regex_match(app_name, app_name_regex))
190 {
191 throw design_error{("The application name must only contain alpha-numeric characters or '_' and '-' "
192 "(regex: \"^[a-zA-Z0-9_-]+$\").")};
193 }
194
195 for (auto & sub : this->subcommands)
196 {
197 if (!std::regex_match(sub, app_name_regex))
198 {
199 throw design_error{"The subcommand name must only contain alpha-numeric characters or '_' and '-' "
200 "(regex: \"^[a-zA-Z0-9_-]+$\")."};
201 }
202 }
203
204 info.app_name = std::move(app_name);
205
206 init(argc, argv);
207 }
208
211 {
212 // wait for another 3 seconds
213 if (version_check_future.valid())
214 version_check_future.wait_for(std::chrono::seconds(3));
215 }
217
241 template <typename option_type, validator validator_type = detail::default_validator<option_type>>
245 std::invocable<validator_type, option_type>
247 void add_option(option_type & value,
248 char const short_id,
249 std::string const & long_id,
250 std::string const & desc,
252 validator_type option_validator = validator_type{}) // copy to bind rvalues
253 {
254 if (sub_parser != nullptr)
255 throw design_error{"You may only specify flags for the top-level parser."};
256
257 verify_identifiers(short_id, long_id);
258 // copy variables into the lambda because the calls are pushed to a stack
259 // and the references would go out of scope.
260 std::visit([=, &value] (auto & f) { f.add_option(value, short_id, long_id, desc, spec, option_validator); },
261 format);
262 }
263
272 void add_flag(bool & value,
273 char const short_id,
274 std::string const & long_id,
275 std::string const & desc,
277 {
278 verify_identifiers(short_id, long_id);
279 // copy variables into the lambda because the calls are pushed to a stack
280 // and the references would go out of scope.
281 std::visit([=, &value] (auto & f) { f.add_flag(value, short_id, long_id, desc, spec); }, format);
282 }
283
304 template <typename option_type, validator validator_type = detail::default_validator<option_type>>
308 std::invocable<validator_type, option_type>
310 void add_positional_option(option_type & value,
311 std::string const & desc,
312 validator_type option_validator = validator_type{}) // copy to bind rvalues
313 {
314 if (sub_parser != nullptr)
315 throw design_error{"You may only specify flags for the top-level parser."};
316
317 if (has_positional_list_option)
318 throw design_error{"You added a positional option with a list value before so you cannot add "
319 "any other positional options."};
320
321 if constexpr (sequence_container<option_type> && !std::same_as<option_type, std::string>)
322 has_positional_list_option = true; // keep track of a list option because there must be only one!
323
324 // copy variables into the lambda because the calls are pushed to a stack
325 // and the references would go out of scope.
326 std::visit([=, &value] (auto & f) { f.add_positional_option(value, desc, option_validator); }, format);
327 }
329
395 void parse()
396 {
397 if (parse_was_called)
398 throw design_error("The function parse() must only be called once!");
399
400 detail::version_checker app_version{info.app_name, info.version, info.url};
401
402 if (std::holds_alternative<detail::format_parse>(format) && !subcommands.empty() && sub_parser == nullptr)
403 {
404 throw too_few_arguments{detail::to_string("You either forgot or misspelled the subcommand! Please specify"
405 " which sub-program you want to use: one of ", subcommands,
406 ". Use -h/--help for more information.")};
407 }
408
409 if (app_version.decide_if_check_is_performed(version_check_dev_decision, version_check_user_decision))
410 {
411 // must be done before calling parse on the format because this might std::exit
412 std::promise<bool> app_version_prom;
413 version_check_future = app_version_prom.get_future();
414 app_version(std::move(app_version_prom));
415 }
416
417 std::visit([this] (auto & f) { f.parse(info); }, format);
418 parse_was_called = true;
419 }
420
424 {
425 if (sub_parser == nullptr)
426 {
427 throw design_error("No subcommand was provided at the construction of the argument parser!");
428 }
429
430 return *sub_parser;
431 }
432
459 template <typename id_type>
461 requires std::same_as<id_type, char> || std::constructible_from<std::string, id_type>
463 bool is_option_set(id_type const & id) const
464 {
465 if (!parse_was_called)
466 throw design_error{"You can only ask which options have been set after calling the function `parse()`."};
467
468 // the detail::format_parse::find_option_id call in the end expects either a char or std::string
469 using char_or_string_t = std::conditional_t<std::same_as<id_type, char>, char, std::string>;
470 char_or_string_t short_or_long_id = {id}; // e.g. convert char * to string here if necessary
471
472 if constexpr (!std::same_as<id_type, char>) // long id was given
473 {
474 if (short_or_long_id.size() == 1)
475 {
476 throw design_error{"Long option identifiers must be longer than one character! If " + short_or_long_id +
477 "' was meant to be a short identifier, please pass it as a char ('') not a string"
478 " (\"\")!"};
479 }
480 }
481
482 if (std::find(used_option_ids.begin(), used_option_ids.end(), std::string{id}) == used_option_ids.end())
483 throw design_error{"You can only ask for option identifiers that you added with add_option() before."};
484
485 // we only need to search for an option before the `end_of_options_indentifier` (`--`)
486 auto end_of_options = std::find(cmd_arguments.begin(), cmd_arguments.end(), end_of_options_indentifier);
487 auto option_it = detail::format_parse::find_option_id(cmd_arguments.begin(), end_of_options, short_or_long_id);
488 return option_it != end_of_options;
489 }
490
493
501 {
502 std::visit([&] (auto & f) { f.add_section(title, spec); }, format);
503 }
504
512 {
513 std::visit([&] (auto & f) { f.add_subsection(title, spec); }, format);
514 }
515
525 void add_line(std::string const & text, bool is_paragraph = false, option_spec const spec = option_spec::standard)
526 {
527 std::visit([&] (auto & f) { f.add_line(text, is_paragraph, spec); }, format);
528 }
529
548 void add_list_item(std::string const & key,
549 std::string const & desc,
551 {
552 std::visit([&] (auto & f) { f.add_list_item(key, desc, spec); }, format);
553 }
555
605
606private:
608 bool parse_was_called{false};
609
611 bool has_positional_list_option{false};
612
614 update_notifications version_check_dev_decision{};
615
617 std::optional<bool> version_check_user_decision;
618
620 friend struct ::seqan3::detail::test_accessor;
621
623 std::future<bool> version_check_future;
624
626 std::regex app_name_regex{"^[a-zA-Z0-9_-]+$"};
627
629 static constexpr std::string_view const end_of_options_indentifier{"--"};
630
632 std::unique_ptr<argument_parser> sub_parser{nullptr};
633
635 std::vector<std::string> subcommands{};
636
644 std::variant<detail::format_parse,
645 detail::format_help,
646 detail::format_short_help,
647 detail::format_version,
648 detail::format_html,
649 detail::format_man,
650 detail::format_copyright/*,
651 detail::format_ctd*/> format{detail::format_help{{}, false}}; // Will be overwritten in any case.
652
654 std::set<std::string> used_option_ids{"h", "hh", "help", "advanced-help", "export-help", "version", "copyright"};
655
657 std::vector<std::string> cmd_arguments{};
658
691 void init(int argc, char const * const * const argv)
692 {
693 if (argc <= 1) // no arguments provided
694 {
695 format = detail::format_short_help{};
696 return;
697 }
698
699 bool special_format_was_set{false};
700
701
702 for (int i = 1, argv_len = argc; i < argv_len; ++i) // start at 1 to skip binary name
703 {
704 std::string arg{argv[i]};
705
706 if (std::ranges::find(subcommands, arg) != subcommands.end())
707 {
708 sub_parser = std::make_unique<argument_parser>(info.app_name + "-" + arg,
709 argc - i,
710 argv + i,
712 break;
713 }
714
715 if (arg == "-h" || arg == "--help")
716 {
717 format = detail::format_help{subcommands, false};
718 init_standard_options();
719 special_format_was_set = true;
720 }
721 else if (arg == "-hh" || arg == "--advanced-help")
722 {
723 format = detail::format_help{subcommands, true};
724 init_standard_options();
725 special_format_was_set = true;
726 }
727 else if (arg == "--version")
728 {
729 format = detail::format_version{};
730 special_format_was_set = true;
731 }
732 else if (arg.substr(0, 13) == "--export-help") // --export-help=man is also allowed
733 {
734 std::string export_format;
735
736 if (arg.size() > 13)
737 {
738 export_format = arg.substr(14);
739 }
740 else
741 {
742 if (argv_len <= i + 1)
743 throw too_few_arguments{"Option --export-help must be followed by a value."};
744 export_format = {argv[i+1]};
745 }
746
747 if (export_format == "html")
748 format = detail::format_html{subcommands};
749 else if (export_format == "man")
750 format = detail::format_man{subcommands};
751 // TODO (smehringer) use when CTD support is available
752 // else if (export_format == "ctd")
753 // format = detail::format_ctd{};
754 else
755 throw validation_error{"Validation failed for option --export-help: "
756 "Value must be one of [html, man]"};
757 init_standard_options();
758 special_format_was_set = true;
759 }
760 else if (arg == "--copyright")
761 {
762 format = detail::format_copyright{};
763 special_format_was_set = true;
764 }
765 else if (arg == "--version-check")
766 {
767 if (++i >= argv_len)
768 throw too_few_arguments{"Option --version-check must be followed by a value."};
769
770 arg = argv[i];
771
772 if (arg == "1" || arg == "true")
773 version_check_user_decision = true;
774 else if (arg == "0" || arg == "false")
775 version_check_user_decision = false;
776 else
777 throw validation_error{"Value for option --version-check must be true (1) or false (0)."};
778
779 // in case --version-check is specified it shall not be passed to format_parse()
780 argc -= 2;
781 }
782 else
783 {
784 cmd_arguments.push_back(std::move(arg));
785 }
786 }
787
788 if (!special_format_was_set)
789 format = detail::format_parse(argc, cmd_arguments);
790 }
791
793 void init_standard_options()
794 {
795 add_subsection("Basic options:");
796 add_list_item("\\fB-h\\fP, \\fB--help\\fP", "Prints the help page.");
797 add_list_item("\\fB-hh\\fP, \\fB--advanced-help\\fP",
798 "Prints the help page including advanced options.");
799 add_list_item("\\fB--version\\fP", "Prints the version information.");
800 add_list_item("\\fB--copyright\\fP", "Prints the copyright/license information.");
801 add_list_item("\\fB--export-help\\fP (std::string)",
802 "Export the help page information. Value must be one of [html, man].");
803 if (version_check_dev_decision == update_notifications::on)
804 add_list_item("\\fB--version-check\\fP (bool)", "Whether to check for the newest app version. Default: true.");
805 }
806
812 template <typename id_type>
813 bool id_exists(id_type const & id)
814 {
815 if (detail::format_parse::is_empty_id(id))
816 return false;
817 return (!(used_option_ids.insert(std::string({id}))).second);
818 }
819
829 void verify_identifiers(char const short_id, std::string const & long_id)
830 {
831 auto constexpr allowed = is_alnum || is_char<'_'> || is_char<'@'>;
832
833 if (id_exists(short_id))
834 throw design_error("Option Identifier '" + std::string(1, short_id) + "' was already used before.");
835 if (id_exists(long_id))
836 throw design_error("Option Identifier '" + long_id + "' was already used before.");
837 if (long_id.length() == 1)
838 throw design_error("Long IDs must be either empty, or longer than one character.");
839 if (!allowed(short_id) && !is_char<'\0'>(short_id))
840 throw design_error("Option identifiers may only contain alphanumeric characters, '_', or '@'.");
841 if (long_id.size() > 0 && is_char<'-'>(long_id[0]))
842 throw design_error("First character of long ID cannot be '-'.");
843
844 std::for_each(long_id.begin(), long_id.end(), [&allowed] (char c)
845 {
846 if (!(allowed(c) || is_char<'-'>(c)))
847 throw design_error("Long identifiers may only contain alphanumeric characters, '_', '-', or '@'.");
848 });
849 if (detail::format_parse::is_empty_id(short_id) && detail::format_parse::is_empty_id(long_id))
850 throw design_error("Option Identifiers cannot both be empty.");
851 }
852};
853
854} // namespace seqan3
T begin(T... args)
The SeqAn command line parser.
Definition: argument_parser.hpp:154
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:272
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:310
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:181
argument_parser & operator=(argument_parser &&)=default
Defaulted.
~argument_parser()
The destructor.
Definition: argument_parser.hpp:210
argument_parser_meta_data info
Aggregates all parser related meta data (see seqan3::argument_parser_meta_data struct).
Definition: argument_parser.hpp:604
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:463
argument_parser(argument_parser &&)=default
Defaulted.
void parse()
Initiates the actual command line parsing.
Definition: argument_parser.hpp:395
argument_parser()=delete
Deleted.
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:247
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:525
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:548
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:500
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:511
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:423
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
Argument parser exception thrown when too few arguments are provided.
Definition: exceptions.hpp:76
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:249
@ standard
The default were no checking or special displaying is happening.
Definition: auxiliary.hpp:250
constexpr auto 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
Checks whether the the type can be used in an add_(positional_)option call on the argument parser.
A more refined container concept than seqan3::container.
Stream concepts.
The main SeqAn3 namespace.
Definition: cigar_operation_table.hpp:2
update_notifications
Indicates whether application allows automatic update notifications by the seqan3::argument_parser.
Definition: auxiliary.hpp:268
@ off
Automatic update notifications should be disabled.
@ on
Automatic update notifications should be enabled.
Provides character predicates for tokenisation.
T regex_match(T... args)
T length(T... args)
Stores all parser related meta information of the seqan3::argument_parser.
Definition: auxiliary.hpp:287
std::string version
The version information MAJOR.MINOR.PATH (e.g. 3.1.3)
Definition: auxiliary.hpp:295
std::string app_name
The application name that will be displayed on the help page.
Definition: auxiliary.hpp:293
std::string url
A link to your github/gitlab project with the newest release.
Definition: auxiliary.hpp:307
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.
Provides the version check functionality.
T visit(T... args)