Sharg 1.1.2-rc.1
The argument parser for bio-c++ tools.
Loading...
Searching...
No Matches
Parser

The Parser Module. More...

Classes

struct  sharg::parser_meta_data
 Stores all parser related meta information of the sharg::parser. More...
 
struct  sharg::config< validator_t >
 Option struct that is passed to the sharg::parser::add_option() function. More...
 
class  sharg::detail::format_base
 The format that contains all helper functions needed in all formats. More...
 
class  sharg::detail::format_help_base< derived_type >
 The format that contains all helper functions needed in all formats for printing the interface description of the application (to std::cout). More...
 
class  sharg::detail::format_help
 The format that prints the help page to std::cout. More...
 
class  sharg::detail::format_short_help
 The format that prints a short help message to std::cout. More...
 
class  sharg::detail::format_version
 The format that prints the version to std::cout. More...
 
class  sharg::detail::format_copyright
 The format that prints the copyright information to std::cout. More...
 
class  sharg::detail::format_html
 The format that prints the help page as html to std::cout. More...
 
class  sharg::detail::format_man
 The format that prints the help page information formatted for a man page to std::cout. More...
 
class  sharg::detail::format_parse
 The format that organizes the actual parsing of command line arguments. More...
 
class  sharg::detail::format_tdl
 A generalized format to create different tool description files. More...
 
class  sharg::detail::version_checker
 A functor whose operator() performs the server http request and version checks. More...
 
class  sharg::parser
 The Sharg command line parser. More...
 

Functions

bool sharg::detail::stdin_is_terminal ()
 Check whether the standard input is interactive.
 
bool sharg::detail::stdout_is_terminal ()
 Check whether the standard output is interactive.
 
bool sharg::detail::stderr_is_terminal ()
 Check whether the standard error output is interactive.
 
unsigned sharg::detail::get_terminal_width ()
 Retrieve size of terminal.
 
void sharg::detail::call_server (std::string const &command, std::promise< bool > prom)
 Writes a timestamp file and performs the server call to get the newest version information.
 

Detailed Description

The Parser Module.

The Parser Class

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:

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:

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.

Parsing Command Line Arguments

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:

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;
}
void add_option(option_type &value, config< validator_type > const &config)
Adds an option to the sharg::parser.
Definition parser.hpp:241

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.

Argument Validation

The Sharg Parser offers a validation mechanism for (positional_)options via callables. You can pass any functor that fulfils the sharg::validator and takes the value passed to the add_(positional_)option function call as a parameter. We provide some commonly used functor that might come in handy:

Function Documentation

◆ call_server()

void sharg::detail::call_server ( std::string const & command,
std::promise< bool > prom )
inline

Writes a timestamp file and performs the server call to get the newest version information.

Parameters
[in]commandThe system command as a string. See sharg::detail::version_checker::command for details.
[in]promA promise object used to track the detached thread which executes this command.

This function performs a https server request by executing a hard coded command (string) as a system call.

◆ get_terminal_width()

unsigned sharg::detail::get_terminal_width ( )
inline

Retrieve size of terminal.

Returns
The width of the current terminal in number of characters.

Note: Only works on Linux/Unix. TIOCGWINSZ is the command (number) to trigger filling the winsize struct. STDOUT_FILENO is the default file descriptor (STDOUT_FILENO == fileno(stdout)).

◆ stderr_is_terminal()

bool sharg::detail::stderr_is_terminal ( )
inline

Check whether the standard error output is interactive.

Returns
True if standard error output is a terminal, false otherwise.

For example "./some_binary --help 2> cerr.out" will return false. "./some_binary --help" will return true.

◆ stdin_is_terminal()

bool sharg::detail::stdin_is_terminal ( )
inline

Check whether the standard input is interactive.

Returns
True if standard input is a terminal, false otherwise.

For example "./some_binary --help | less" will return false. "./some_binary --help" will return true.

◆ stdout_is_terminal()

bool sharg::detail::stdout_is_terminal ( )
inline

Check whether the standard output is interactive.

Returns
True if standard output is a terminal, false otherwise.

For example "./some_binary --help | less" will return false. "./some_binary --help" will return true.

Hide me