Sharg 1.1.2-rc.1
The argument parser for bio-c++ tools.
Loading...
Searching...
No Matches
sharg::parser Class Reference

The Sharg command line parser. More...

#include <sharg/parser.hpp>

Public Member Functions

void parse ()
 Initiates the actual command line parsing.
 
parserget_sub_parser ()
 Returns a reference to the sub-parser instance if subcommand parsing was enabled.
 
template<typename id_type >
requires std::same_as<id_type, char> || std::constructible_from<std::string, id_type>
bool is_option_set (id_type const &id) const
 Checks whether the option identifier (id) was set on the command line by the user.
 
Constructors, destructor and assignment
 parser ()=delete
 Deleted.
 
 parser (parser const &)=delete
 Deleted.
 
parseroperator= (parser const &)=delete
 Deleted.
 
 parser (parser &&)=default
 Defaulted.
 
parseroperator= (parser &&)=default
 Defaulted.
 
 parser (std::string const &app_name, std::vector< std::string > const &arguments, update_notifications version_updates=update_notifications::on, std::vector< std::string > subcommands={})
 Initializes an sharg::parser object from the command line arguments.
 
 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={})
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
 ~parser ()
 The destructor.
 
Adding options

Add (positional) options and flags to the parser.

template<typename option_type , typename validator_type >
requires (parsable<option_type> || parsable<std::ranges::range_value_t<option_type>>) && std::invocable<validator_type, option_type>
void add_option (option_type &value, config< validator_type > const &config)
 Adds an option to the sharg::parser.
 
template<typename validator_type >
requires std::invocable<validator_type, bool>
void add_flag (bool &value, config< validator_type > const &config)
 Adds a flag to the sharg::parser.
 
template<typename option_type , typename validator_type >
requires (parsable<option_type> || parsable<std::ranges::range_value_t<option_type>>) && std::invocable<validator_type, option_type>
void add_positional_option (option_type &value, config< validator_type > const &config)
 Adds a positional option to the sharg::parser.
 
Structuring the Help Page
void add_section (std::string const &title, bool const advanced_only=false)
 Adds an help page section to the sharg::parser.
 
void add_subsection (std::string const &title, bool const advanced_only=false)
 Adds an help page subsection to the sharg::parser.
 
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.
 
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.
 
void add_subcommands (std::vector< std::string > const &subcommands)
 Adds subcommands to the parser.
 

Public Attributes

parser_meta_data info
 Aggregates all parser related meta data (see sharg::parser_meta_data struct).
 

Private Member Functions

void determine_format_and_subcommand ()
 Handles format and subcommand detection.
 
template<typename id_type >
bool id_exists (id_type const &id)
 Checks whether the long identifier has already been used before.
 
void verify_identifiers (char const short_id, std::string const &long_id)
 Verifies that the short and the long identifiers are correctly formatted.
 
template<typename validator_t >
void verify_option_config (config< validator_t > const &config)
 brief Verify the configuration given to a sharg::parser::add_option call.
 
template<typename validator_t >
void verify_flag_config (config< validator_t > const &config)
 brief Verify the configuration given to a sharg::parser::add_flag call.
 
template<typename validator_t >
void verify_positional_option_config (config< validator_t > const &config) const
 brief Verify the configuration given to a sharg::parser::add_positional_option call.
 
void check_parse_not_called (std::string_view const function_name) const
 Throws a sharg::design_error if parse() was already called.
 
void verify_app_and_subcommand_names () const
 Verifies that the app and subcommand names are correctly formatted.
 
void run_version_check ()
 Runs the version check if the user has not disabled it.
 
void parse_format ()
 Parses the command line arguments according to the format.
 

Private Attributes

bool parse_was_called {false}
 Keeps track of whether the parse function has been called already.
 
bool has_positional_list_option {false}
 Keeps track of whether the user has added a positional list option to check if this was the very last.
 
update_notifications version_check_dev_decision {}
 Set on construction and indicates whether the developer deactivates the version check calls completely.
 
std::optional< bool > version_check_user_decision
 Whether the user specified to perform the version check (true) or not (false), default unset.
 
std::future< bool > version_check_future
 The future object that keeps track of the detached version check call thread.
 
std::regex app_name_regex {"^[a-zA-Z0-9_-]+$"}
 Validates the application name to ensure an escaped server call.
 
std::unique_ptr< parsersub_parser {nullptr}
 Stores the sub-parser in case subcommand parsing is enabled.
 
std::vector< std::stringsubcommands {}
 Stores the sub-parser names in case subcommand parsing is enabled.
 
std::variant< detail::format_parse, detail::format_help, detail::format_short_help, detail::format_version, detail::format_html, detail::format_man, detail::format_tdl, detail::format_copyrightformat {detail::format_short_help{}}
 The format of the parser that decides the behavior when calling the sharg::parser::parse function.
 
std::unordered_set< std::stringused_ids {"h", "hh", "help", "advanced-help", "export-help", "version", "copyright"}
 List of option/flag identifiers (excluding -/–) that are already used.
 
std::vector< std::stringformat_arguments {}
 The command line arguments that will be passed to the format.
 
std::vector< std::stringarguments {}
 The original command line arguments.
 
std::vector< std::stringexecutable_name {}
 The command that lead to calling this parser, e.g. [./build/bin/raptor, build].
 
std::unordered_set< std::stringoptions {}
 Set of option identifiers (including -/–) that have been added via add_option.
 
std::vector< std::function< void()> > operations
 Vector of functions that stores all calls.
 

Static Private Attributes

static constexpr std::string_view const option_end_identifier {"--"}
 Signals the parser that no options follow this string but only positional arguments.
 

Friends

struct ::sharg::detail::test_accessor
 Befriend sharg::detail::test_accessor to grant access to version_check_future and format.
 

Detailed Description

The Sharg command line parser.

The sharg::parser is a general purpose argument parser that provides convenient access to the command line arguments passed to the program. It automatically generates a help page and can export manual-pages as well as HTML documentation.

Terminology

Since the terms option and arguments are frequently used in different contexts we want to first clarify our usage:

  • options [e.g. -i myfile, --infile myfile] refer to key-value pairs. The key is either a short indentifier, restricted to a single character -i, or a long identifier --infile.
  • positional options [e.g. arg1] refers to command line arguments that are specified without an identifier/key, are always required and are identified by their position.
  • flags [e.g. -b] refers to identifiers that are not followed by a value (booleans) and therefore only indicate whether they are set or not.

Add/get options, flags or positional Options

Adding an option is done in a single call. You simply need to provide a predeclared variable and some additional information like the identifier, description or advanced restrictions. To actually retrieve the value from the command line and enable every other mechanism you need to call the sharg::parser::parse function in the end.

// SPDX-FileCopyrightText: 2006-2024 Knut Reinert & Freie Universität Berlin
// SPDX-FileCopyrightText: 2016-2024 Knut Reinert & MPI für molekulare Genetik
// SPDX-License-Identifier: CC0-1.0
#include <sharg/all.hpp>
int main(int argc, char ** argv)
{
sharg::parser myparser{"Grade-Average", argc, argv}; // initialize
std::string name{"Max Muster"}; // define default values directly in the variable.
bool bonus{false};
std::vector<double> grades{}; // you can also specify a vector that is treated as a list option.
myparser.add_option(name, sharg::config{.short_id = 'n', .long_id = "name", .description = "Your name please."});
myparser.add_flag(bonus, sharg::config{.short_id = 'b', .long_id = "bonus", .description = "Got a bonus?."});
myparser.add_positional_option(grades, sharg::config{.description = "Please specify your grades."});
try
{
myparser.parse();
}
catch (sharg::parser_error const & ext) // the user did something wrong
{
std::cerr << "[PARSER ERROR] " << ext.what() << '\n'; // customize your error message
return -1;
}
if (bonus)
grades.push_back(1.0); // extra good grade
double avg{0};
for (auto g : grades)
avg += g;
avg = avg / grades.size();
std::cerr << name << " has an average grade of " << avg << '\n';
return 0;
}
Meta-header for the Parser module .
Parser exception that is thrown whenever there is an error while parsing the command line arguments.
Definition exceptions.hpp:40
The Sharg command line parser.
Definition parser.hpp:154
Option struct that is passed to the sharg::parser::add_option() function.
Definition config.hpp:43
std::string description
The description to be shown on any (exported) help page.
Definition config.hpp:68
char short_id
The short identifier for the option (e.g. 'a', making the option callable via -a).
Definition config.hpp:53
T what(T... args)

Now you can call your application via the command line:

MaxMuster% ./grade_avg_app -n Peter --bonus 1.0 2.0 1.7
Peter has an average grade of 1.425

You can also display the help page automatically:

MaxMuster% ./grade_avg_app --help
Grade-Average
=============
POSITIONAL ARGUMENTS
ARGUMENT-1 List of DOUBLE's
Please specify your grades.
OPTIONS
-n, --name STRING
Please specify your name.
-b, --bonus
Please specify if you got the bonus.
VERSION
Last update:
Grade-Average version:
Sharg version: 0.1.0

The POSIX conventions

The sharg::parser follows the POSIX conventions. Note that this means among others:

  1. Options without arguments can use one hyphen, for example -a -b is equivalent to -ab.
  2. Whitespaces between a short option and its argument are optional. For example, -c foo is equivalent to -cfoo.
  3. -- terminates the options and signals that only positional options follow. This enables the user to use a positional option beginning with - without it being misinterpreted as an option identifier.
Attention
Currently, the sharg::parser is in disagreement with one of the POSIX conventions. It does not interpret a single hyphen character as an ordinary non-option argument that may be used for in-/output from standard streams.

Errors that are caught by the parser

There are two different kinds of errors: Developer errors and user errors.

Developer errors are those that violate the sharg::parser design (e.g. calling the sharg::parser::parse function twice or specifying two different options with the same identifier.) In this case, a sharg::design_error is thrown.

The second kind are user errors, due to invalid command line calls. In this case a sharg::parser_error is thrown.

For example:

MaxMuster% ./grade_avg_app -n Peter 2.0 abc 1.7
[PARSER ERROR] Value cast failed for positional option 2: Argument abc could not be casted to type DOUBLE.

See the sharg::parser::parse documentation for a detailed list of which exceptions are caught.

Update Notifications

SeqAn applications that are using the sharg::parser can check SeqAn servers for version updates. The functionality helps getting new versions out to users faster. It is also used to inform application developers of new versions of the SeqAn library which means that applications ship with less bugs. For privacy implications, please see: https://docs.seqan.de/sharg/main_user/about_update_notifications.html.

Developers that wish to disable this feature permanently can pass an extra constructor argument:

// SPDX-FileCopyrightText: 2006-2024 Knut Reinert & Freie Universität Berlin
// SPDX-FileCopyrightText: 2016-2024 Knut Reinert & MPI für molekulare Genetik
// SPDX-License-Identifier: CC0-1.0
#include <sharg/all.hpp>
int main(int argc, char ** argv)
{
sharg::parser myparser{"Game-of-Parsing", argc, argv, sharg::update_notifications::off};
// disable update notifications permanently ----------------------------^
}
@ off
Automatic update notifications should be disabled.

Users of applications that have this feature activated can opt-out, by either:

  • disabling it for a specific application simply by setting the option --version-check false/0 or
  • disabling it for all applications by setting the SHARG_NO_VERSION_CHECK environment variable.

Note that in case there is no --version-check option (display available options with -h/--help), then the developer already disabled the version check functionality.

This entity is stable. Since version 1.0.

Constructor & Destructor Documentation

◆ parser()

sharg::parser::parser ( std::string const & app_name,
std::vector< std::string > const & arguments,
update_notifications version_updates = update_notifications::on,
std::vector< std::string > subcommands = {} )
inline

Initializes an sharg::parser object from the command line arguments.

Parameters
[in]app_nameThe name of the app that is displayed on the help page.
[in]argumentsThe command line arguments to parse.
[in]version_updatesNotify users about version updates (default sharg::update_notifications::on).
[in]subcommandsA list of subcommands (see subcommand parsing ).

The application name must only contain alpha-numeric characters, _ or - , i.e. the following regex must evaluate to true: "^[a-zA-Z0-9_-]+$" .

See the parser tutorial for more information about the version check functionality.

This entity is stable. Since version 1.0.

Member Function Documentation

◆ add_flag()

template<typename validator_type >
requires std::invocable<validator_type, bool>
void sharg::parser::add_flag ( bool & value,
config< validator_type > const & config )
inline

Adds a flag to the sharg::parser.

Parameters
[in,out]valueThe variable which shows if the flag is turned off (default) or on.
[in]configA configuration object to customise the sharg::parser behaviour. See sharg::config.
Exceptions
sharg::design_errorif sharg::parser::parse was already called.
sharg::design_errorif value is true.
sharg::design_errorif the option identifier was already used.
sharg::design_errorif the option identifier is not a valid identifier.

This entity is stable. Since version 1.0.

◆ add_line()

void sharg::parser::add_line ( std::string const & text,
bool is_paragraph = false,
bool const advanced_only = false )
inline

Adds an help page text line to the sharg::parser.

Parameters
[in]textThe text to print.
[in]is_paragraphWhether to insert as paragraph or just a line (Default: false).
[in]advanced_onlyIf set to true, the section only shows when the user requested the advanced help page.
Exceptions
sharg::design_errorif sharg::parser::parse was already called.

If the line is not a paragraph (false), only one line break is appended, otherwise two line breaks are appended. This only affects the help page and other output formats.

This entity is stable. Since version 1.0.

◆ add_list_item()

void sharg::parser::add_list_item ( std::string const & key,
std::string const & desc,
bool const advanced_only = false )
inline

Adds an help page list item (key-value) to the sharg::parser.

Parameters
[in]keyThe key of the key-value pair of the list item.
[in]descThe value of the key-value pair of the list item.
[in]advanced_onlyIf set to true, the section only shows when the user requested the advanced help page.
Exceptions
sharg::design_errorif sharg::parser::parse was already called.

Note: This only affects the help page and other output formats.

A list item is composed of a key (key) and value (desc) and usually used for option identifier-description-pairs. E.g.:

-a, --age LONG
Super important integer for age.

This entity is stable. Since version 1.0.

◆ add_option()

template<typename option_type , typename validator_type >
requires (parsable<option_type> || parsable<std::ranges::range_value_t<option_type>>) && std::invocable<validator_type, option_type>
void sharg::parser::add_option ( option_type & value,
config< validator_type > const & config )
inline

Adds an option to the sharg::parser.

Template Parameters
option_typeMust have a formatted input function (stream >> value). If option_type is a container, its value type must have the formatted input function (exception: std::string is not regarded as a container). See FormattedInputFunction .
validator_typeThe type of validator to be applied to the option value. Must model sharg::validator.
Parameters
[in,out]valueThe variable in which to store the given command line argument.
[in]configA configuration object to customise the sharg::parser behaviour. See sharg::config.

The config.validator must be applicable to the given output variable (value).

Exceptions
sharg::design_errorif sharg::parser::parse was already called.
sharg::design_errorif the option is required and has a default_message.
sharg::design_errorif the option identifier was already used.
sharg::design_errorif the option identifier is not a valid identifier.

This entity is stable. Since version 1.0.

◆ add_positional_option()

template<typename option_type , typename validator_type >
requires (parsable<option_type> || parsable<std::ranges::range_value_t<option_type>>) && std::invocable<validator_type, option_type>
void sharg::parser::add_positional_option ( option_type & value,
config< validator_type > const & config )
inline

Adds a positional option to the sharg::parser.

Template Parameters
option_typeMust have a formatted input function (stream >> value). If option_type is a container, its value type must have the formatted input function (exception: std::string is not regarded as a container). See FormattedInputFunction .
validator_typeThe type of validator to be applied to the option value. Must model sharg::validator.
Parameters
[in,out]valueThe variable in which to store the given command line argument.
[in]configCustomise the sharg::parser behaviour. See sharg::positional_config.
Exceptions
sharg::design_errorif sharg::parser::parse was already called.
sharg::design_errorif the option has a short or long identifier.
sharg::design_errorif the option is advanced or hidden.
sharg::design_errorif the option has a default_message.
sharg::design_errorif there already is a positional list option.
sharg::design_errorif there are subcommands.

The config.validator must be applicable to the given output variable (value).

This entity is stable. Since version 1.0.

◆ add_section()

void sharg::parser::add_section ( std::string const & title,
bool const advanced_only = false )
inline

Adds an help page section to the sharg::parser.

Parameters
[in]titleThe title of the section.
[in]advanced_onlyIf set to true, the section only shows when the user requested the advanced help page.
Exceptions
sharg::design_errorif sharg::parser::parse was already called.

This only affects the help page and other output formats.

This entity is stable. Since version 1.0.

◆ add_subcommands()

void sharg::parser::add_subcommands ( std::vector< std::string > const & subcommands)
inline

Adds subcommands to the parser.

Parameters
[in]subcommandsA list of subcommands.

Adds subcommands to the current parser. The list of subcommands is sorted and duplicates are removed.

Example

// SPDX-FileCopyrightText: 2006-2024 Knut Reinert & Freie Universität Berlin
// SPDX-FileCopyrightText: 2016-2024 Knut Reinert & MPI für molekulare Genetik
// SPDX-License-Identifier: CC0-1.0
#include <sharg/all.hpp>
void run(std::vector<std::string> const & arguments)
{
sharg::parser git_parser{"git", arguments, sharg::update_notifications::off, {"pull", "push"}};
git_parser.add_subcommands({"remote"});
git_parser.parse();
sharg::parser & sub_parser = git_parser.get_sub_parser();
if (sub_parser.info.app_name == std::string_view{"git-pull"})
{
auto & pull_parser = sub_parser;
std::string repository{};
pull_parser.add_positional_option(repository, sharg::config{});
pull_parser.parse();
}
else if (sub_parser.info.app_name == std::string_view{"git-push"})
{
auto & push_parser = sub_parser;
std::string repository{};
push_parser.add_positional_option(repository, sharg::config{});
push_parser.parse();
}
else if (sub_parser.info.app_name == std::string_view{"git-remote"})
{
auto & remote_parser = sub_parser;
remote_parser.add_subcommands({"set-url", "show"});
remote_parser.parse();
sharg::parser & recursive_sub_parser = remote_parser.get_sub_parser();
if (recursive_sub_parser.info.app_name == std::string_view{"git-remote-set-url"})
{
auto & set_url_parser = recursive_sub_parser;
std::string repository{};
set_url_parser.add_positional_option(repository, sharg::config{});
set_url_parser.parse();
}
else if (recursive_sub_parser.info.app_name == std::string_view{"git-remote-show"})
{
auto & show_parser = recursive_sub_parser;
show_parser.parse();
}
}
}
int main(int argc, char ** argv)
{
try
{
run({argv, argv + argc});
}
catch (sharg::parser_error const & ext)
{
std::cerr << "[Error] " << ext.what() << '\n';
std::exit(-1);
}
return 0;
}
void add_subcommands(std::vector< std::string > const &subcommands)
Adds subcommands to the parser.
Definition parser.hpp:652
parser_meta_data info
Aggregates all parser related meta data (see sharg::parser_meta_data struct).
Definition parser.hpp:713
void parse()
Initiates the actual command line parsing.
Definition parser.hpp:414
parser & get_sub_parser()
Returns a reference to the sub-parser instance if subcommand parsing was enabled.
Definition parser.hpp:448
T exit(T... args)
std::string app_name
The application name that will be displayed on the help page.
Definition auxiliary.hpp:51

This entity is experimental and subject to change in the future. Experimental since version 1.1.2

◆ add_subsection()

void sharg::parser::add_subsection ( std::string const & title,
bool const advanced_only = false )
inline

Adds an help page subsection to the sharg::parser.

Parameters
[in]titleThe title of the subsection.
[in]advanced_onlyIf set to true, the section only shows when the user requested the advanced help page.
Exceptions
sharg::design_errorif sharg::parser::parse was already called.

This only affects the help page and other output formats.

This entity is stable. Since version 1.0.

◆ check_parse_not_called()

void sharg::parser::check_parse_not_called ( std::string_view const function_name) const
inlineprivate

Throws a sharg::design_error if parse() was already called.

Parameters
[in]function_nameThe name of the function that was called after parse().
Exceptions
sharg::design_errorif parse() was already called

This function is used when calling functions which have no effect (add_line, add_option, ...) or unexpected behavior (add_subcommands) after parse() was called. Has no effect when parse() encounters a special format (help, version, ...), since those will terminate the program.

◆ determine_format_and_subcommand()

void sharg::parser::determine_format_and_subcommand ( )
inlineprivate

Handles format and subcommand detection.

Exceptions
sharg::too_few_argumentsif option –export-help was specified without a value
sharg::too_few_argumentsif option –version-check was specified without a value
sharg::validation_errorif the value passed to option –export-help was invalid.
sharg::validation_errorif the value passed to option –version-check was invalid.
sharg::user_input_errorif the subcommand is unknown.

This function adds all command line parameters to the format_arguments member variable to take advantage of the vector functionality later on. Additionally, the format member variable is set, depending on which parameters are given by the user:

If --export-help is specified with a value other than html, man, cwl or ctd, an sharg::parser_error is thrown.

◆ get_sub_parser()

parser & sharg::parser::get_sub_parser ( )
inline

Returns a reference to the sub-parser instance if subcommand parsing was enabled.

This entity is stable. Since version 1.0.

◆ id_exists()

template<typename id_type >
bool sharg::parser::id_exists ( id_type const & id)
inlineprivate

Checks whether the long identifier has already been used before.

Parameters
[in]idThe long identifier of the command line option/flag.
Returns
true if an option or flag with the long identifier exists or false otherwise.

◆ is_option_set()

template<typename id_type >
requires std::same_as<id_type, char> || std::constructible_from<std::string, id_type>
bool sharg::parser::is_option_set ( id_type const & id) const
inline

Checks whether the option identifier (id) was set on the command line by the user.

Template Parameters
id_typeEither type char or a type that a std::string is constructible from.
Parameters
[in]idThe short (char) or long (std::string) option identifier to search for.
Returns
true if option identifier id was set on the command line by the user.
Exceptions
sharg::design_errorif the function is used incorrectly (see details below).

You can only ask for option identifiers that were added to the parser beforehand via sharg::parser::add_option. As in the sharg::parser::add_option call, pass short identifiers as a char and long identifiers as a std::string or a type that a std::string is constructible from (e.g. a const char *).

Example

// SPDX-FileCopyrightText: 2006-2024 Knut Reinert & Freie Universität Berlin
// SPDX-FileCopyrightText: 2016-2024 Knut Reinert & MPI für molekulare Genetik
// SPDX-License-Identifier: CC0-1.0
#include <sharg/all.hpp>
int main(int argc, char ** argv)
{
sharg::parser myparser{"awesome-app", argc, argv}; // initialize
int a{3};
myparser.add_option(a, sharg::config{.short_id = 'a', .long_id = "aint", .description = "Specify an integer."});
try
{
myparser.parse();
}
catch (sharg::parser_error const & ext) // the user did something wrong
{
std::cerr << "[PARSER ERROR] " << ext.what() << '\n'; // customize your error message
return -1;
}
if (myparser.is_option_set('a'))
std::cerr << "The user set option -a on the command line.\n";
if (myparser.is_option_set("awesome-parameter"))
std::cerr << "The user set option --awesome-parameter on the command line.\n";
// Asking for an option identifier that was not used before throws an error:
// myparser.is_option_set("foo"); // throws sharg::design_error
return 0;
}
void add_option(option_type &value, config< validator_type > const &config)
Adds an option to the sharg::parser.
Definition parser.hpp:241

Exceptions

This function throws a sharg::design_error if

  • sharg::parser::parse() was not called before.
  • a long identifier was passed (e.g. a std::string) that only consists of a single character. If you mean to pass a short identifier, please pass it as a char not a std::string.
  • the option identifier cannot be found in the list of valid option identifiers that were added to the parser via sharg::parser::add_option() calls beforehand.

This entity is stable. Since version 1.0.

◆ parse()

void sharg::parser::parse ( )
inline

Initiates the actual command line parsing.

Attention
The function must be called at the very end of all parser related code and should be enclosed in a try catch block as the parser may throw.
Exceptions
sharg::design_errorif this function was already called before.
sharg::design_errorif the application name or subcommands contain illegal characters.
sharg::option_declared_multiple_timesif an option that is not a list was declared multiple times.
sharg::user_input_errorif an incorrect argument is given as (positional) option value.
sharg::required_option_missingif the user did not provide a required option.
sharg::too_many_argumentsif the command line call contained more arguments than expected.
sharg::too_few_argumentsif the command line call contained less arguments than expected.
sharg::validation_errorif the argument was not excepted by the provided validator.

When no specific key words are supplied, the sharg::parser starts to process the command line for specified options, flags and positional options.

If the given command line input (argv) contains the following keywords (in order of checking), the parser will exit (std::exit) with error code 0 after doing the following:

  • -h/--help Prints the help page.
  • -hh/--advanced-help Prints the help page including advanced options.
  • --version Prints the version information.
  • --export-help [format] Prints the application description in the given format (html/man/ctd).
  • --version-check false/0/true/1 Disable/enable update notifications.

Example:

// SPDX-FileCopyrightText: 2006-2024 Knut Reinert & Freie Universität Berlin
// SPDX-FileCopyrightText: 2016-2024 Knut Reinert & MPI für molekulare Genetik
// SPDX-License-Identifier: CC0-1.0
#include <sharg/all.hpp>
int main(int argc, char ** argv)
{
sharg::parser myparser{"The-Age-App", argc, argv}; // initialize
int age{30}; // define default values directly in the variable
myparser.add_option(age, sharg::config{.short_id = 'a', .long_id = "user-age", .description = "Your age please."});
try
{
myparser.parse();
}
catch (sharg::parser_error const & ext) // the user did something wrong
{
std::cerr << "The-Age-App - [PARSER ERROR] " << ext.what() << '\n'; // customize your error message
return -1;
}
std::cerr << "integer given by user: " << age << '\n';
return 0;
}

The code above gives the following output when calling --help:

MaxMuster$ ./age_app --help
The-Age-App
===========
OPTIONS
-a, --user-age (signed 32 bit integer)
Please specify your age.
VERSION
Last update:
The-Age-App version:
Sharg version: 0.1.0
Thanks for using The-Age-App!

If the user does something wrong, it looks like this:

MaxMuster$ ./age_app --foo
The Age App - [PARSER ERROR] Unknown option --foo. Please see -h/--help for more information.
MaxMuster$ ./age_app -a abc
The Age App - [PARSER ERROR] Value cast failed for option -a: Argument abc
could not be casted to type (signed 32 bit integer).

This entity is stable. Since version 1.0.

◆ parse_format()

void sharg::parser::parse_format ( )
inlineprivate

Parses the command line arguments according to the format.

Exceptions
sharg::option_declared_multiple_timesif an option that is not a list was declared multiple times.
sharg::user_input_errorif an incorrect argument is given as (positional) option value.
sharg::required_option_missingif the user did not provide a required option.
sharg::too_many_argumentsif the command line call contained more arguments than expected.
sharg::too_few_argumentsif the command line call contained less arguments than expected.
sharg::validation_errorif the argument was not excepted by the provided validator.

This function calls the parse function of the format member variable.

◆ run_version_check()

void sharg::parser::run_version_check ( )
inlineprivate

Runs the version check if the user has not disabled it.

If the user has not disabled the version check, the function will start a detached thread that will call the sharg::detail::version_checker and print a message if a new version is available.

◆ verify_app_and_subcommand_names()

void sharg::parser::verify_app_and_subcommand_names ( ) const
inlineprivate

Verifies that the app and subcommand names are correctly formatted.

Exceptions
sharg::design_errorif the app name is not correctly formatted.
sharg::design_errorif the subcommand names are not correctly formatted.

The app name must only contain alphanumeric characters, '_', or '-'. The subcommand names must only contain alphanumeric characters, '_', or '-'.

◆ verify_identifiers()

void sharg::parser::verify_identifiers ( char const short_id,
std::string const & long_id )
inlineprivate

Verifies that the short and the long identifiers are correctly formatted.

Parameters
[in]short_idThe short identifier of the command line option/flag.
[in]long_idThe long identifier of the command line option/flag.
Exceptions
sharg::design_error

Specifically, checks that identifiers haven't been used before, the length of long IDs is either empty or longer than one char, the characters used in the identifiers are all valid, and at least one of short_id or long_id is given.

Member Data Documentation

◆ format

The format of the parser that decides the behavior when calling the sharg::parser::parse function.

The format is set in the function parser::init.

◆ info

parser_meta_data sharg::parser::info

Aggregates all parser related meta data (see sharg::parser_meta_data struct).

Attention
You should supply as much information as possible to help users of the application.

The meta information is assembled in a struct to provide a central access point that can be easily extended.

You can access the members directly: (see sharg::parser_meta_data for a list of the info members)

// SPDX-FileCopyrightText: 2006-2024 Knut Reinert & Freie Universität Berlin
// SPDX-FileCopyrightText: 2016-2024 Knut Reinert & MPI für molekulare Genetik
// SPDX-License-Identifier: CC0-1.0
#include <sharg/all.hpp>
int main(int argc, char ** argv)
{
sharg::parser myparser{"Penguin_Parade", argc, argv}; // initialize
myparser.info.version = "2.0.0";
myparser.info.date = "12.01.2017";
myparser.info.short_description = "Organize your penguin parade";
myparser.info.description.push_back("First Paragraph.");
myparser.info.description.push_back("Second Paragraph.");
myparser.info.examples.push_back("./penguin_parade Skipper Kowalski Rico Private -d 10 -m 02 -y 2017");
int d{01}; // day
int m{01}; // month
int y{2050}; // year
myparser.add_option(d, sharg::config{.short_id = 'd', .long_id = "day", .description = "Your preferred day."});
myparser.add_option(m, sharg::config{.short_id = 'm', .long_id = "month", .description = "Your preferred month."});
myparser.add_option(y, sharg::config{.short_id = 'y', .long_id = "year", .description = "Your preferred year."});
std::vector<std::string> penguin_names;
myparser.add_positional_option(penguin_names, sharg::config{.description = "Specify the names of the penguins."});
try
{
myparser.parse();
}
catch (sharg::parser_error const & ext) // the user did something wrong
{
std::cerr << ext.what() << "\n";
return -1;
}
// organize ...
return 0;
}
T push_back(T... args)
std::string version
The version information MAJOR.MINOR.PATH (e.g. 3.1.3)
Definition auxiliary.hpp:54

This will produce a nice help page when the user calls -h or --help:

MaxMuster% ./penguin_app --help
Penguin_Parade - Organize your penguin parade
=============================================
DESCRIPTION
First Paragraph.
Second Paragraph.
POSITIONAL ARGUMENTS
ARGUMENT-1 List of STRING's
Specify the names of the penguins.
OPTIONS
-d, --day (signed 32 bit integer)
Please specify your preferred day.
-m, --month (signed 32 bit integer)
Please specify your preferred month.
-y, --year (signed 32 bit integer)
Please specify your preferred year.
EXAMPLES
./penguin_parade Skipper Kowalski Rico Private -d 10 -m 02 -y 2017
VERSION
Last update: 12.01.2017
Penguin_Parade version: 2.0.0
Sharg version: 0.1.0

This entity is stable. Since version 1.0.


The documentation for this class was generated from the following file:
Hide me