advgetopt 2.0.47
Parse complex command line arguments and configuration files in C++.
Public Types | Public Member Functions | Static Public Member Functions | Private Member Functions | Static Private Member Functions | Private Attributes | List of all members
advgetopt::getopt Class Reference

Class used to parse command line options. More...

#include <advgetopt.h>

Collaboration diagram for advgetopt::getopt:
Collaboration graph
[legend]

Public Types

typedef std::shared_ptr< getoptpointer_t
 

Public Member Functions

 getopt (options_environment const &opts)
 Initialize the getopt object.
 
 getopt (options_environment const &opts, int argc, char *argv[])
 Initialize the getopt object.
 
void add_option (option_info::pointer_t opt, bool ignore_duplicates=false)
 Add one option to the advgetopt object.
 
void add_option_from_string (option_info::pointer_t opt, std::string const &value, std::string const &filename, string_list_t const &option_keys, option_source_t source=option_source_t::SOURCE_DIRECT)
 Add an option with a value defined in a string.
 
void define_environment_variable_data ()
 Retrieve the environment variable string.
 
group_description constfind_group (flag_t group) const
 Search for group in the list of group names.
 
void finish_parsing (int argc, char *argv[])
 Actually parse everything.
 
std::string get_configuration_filename (int idx) const
 
size_t get_configuration_filename_size () const
 
string_list_t get_configuration_filenames (bool exists, bool writable, int argc=0, char *argv[]=nullptr) const
 Generate a list of configuration filenames.
 
std::string get_default (std::string const &name) const
 Get the default value for this option.
 
double get_double (std::string const &name, int idx=0, double min=std::numeric_limits< double >::min(), double max=std::numeric_limits< double >::max()) const
 This function retrieves an argument as a double value.
 
std::string get_environment_variable () const
 
std::string get_environment_variable_name () const
 
std::string get_group_name () const
 Retrieve the group name if one is defined.
 
std::string get_group_or_project_name () const
 Retrieve the group or project name.
 
long get_long (std::string const &name, int idx=0, long min=std::numeric_limits< long >::min(), long max=std::numeric_limits< long >::max()) const
 This function retrieves an argument as a long value.
 
option_info::pointer_t get_option (short_name_t name, bool exact_option=false) const
 Get an option using its short name.
 
option_info::pointer_t get_option (std::string const &name, bool exact_option=false) const
 Retrieve an option by name.
 
option_info::map_by_name_t constget_options () const
 Retrieve the complete list of options.
 
options_environment constget_options_environment () const
 Return a reference to the options environment.
 
std::string get_options_filename () const
 Get the path and filename to options.
 
std::string get_output_filename () const
 Determine the best suited file for updates.
 
std::string get_program_fullname () const
 Get the full name of the program.
 
std::string get_program_name () const
 Get the basename of the program.
 
std::string get_project_name () const
 Retrieve the project name if one is defined.
 
std::string get_string (std::string const &name, int idx=0, bool raw=false) const
 Get the content of an option as a string.
 
variables::pointer_t get_variables () const
 Retrieve a pointer to the variables defined in the getopt object.
 
bool has_default (std::string const &name) const
 Check whether an option has a default value.
 
bool has_flag (flag_t flag) const
 Check whether an environment flag is set or not.
 
bool is_defined (std::string const &name) const
 Check whether a parameter is defined.
 
void link_aliases ()
 Link options marked as a GETOPT_FLAG_ALIAS.
 
option_info_ref operator[] (std::string const &name)
 Access a parameter in read and write mode.
 
std::string operator[] (std::string const &name) const
 Retrieve the value of an argument.
 
std::string options_to_string (bool include_progname=false, bool keep_defaults=false) const
 Transform all the defined options back in a string.
 
void parse_arguments (int argc, char *argv[], option_source_t source=option_source_t::SOURCE_DIRECT, bool only_environment_variable=false)
 Parse an array of arguments.
 
void parse_configuration_files (int argc=0, char *argv[]=nullptr)
 This function checks for arguments in configuration files.
 
void parse_environment_variable ()
 Check for an environment variable.
 
void parse_options_from_file (std::string const &filename, int min_sections, int max_sections, bool ignore_duplicates=false)
 Check for a file with option definitions.
 
void parse_options_info (option const *opts, bool ignore_duplicates=false)
 Parse the options to option_info objects.
 
void parse_program_name (char *argv[])
 Transform the argv[0] parameter in the program name.
 
void parse_string (std::string const &str, option_source_t source=option_source_t::SOURCE_DIRECT, bool only_environment_variable=false)
 Parse a string similar to a command line argument.
 
void process_configuration_file (std::string const &filename)
 Parse one specific configuration file and process the results.
 
std::string process_help_string (char const *help) const
 Change the % flags in help strings.
 
flag_t process_system_options (std::basic_ostream< char > &out)
 Process the system options.
 
void reset ()
 Reset all the options.
 
void set_short_name (std::string const &name, short_name_t short_name)
 Assign a short name to an option.
 
std::size_t size (std::string const &name) const
 Retrieve the number of arguments.
 
std::string usage (flag_t show=GETOPT_FLAG_SHOW_MOST) const
 Create a string of the command line arguments.
 

Static Public Member Functions

static string_list_t split_environment (std::string const &environment)
 Transform a string in an array of arguments.
 

Private Member Functions

void add_options (option_info::pointer_t opt, int &i, int argc, char **argv, string_list_t const &option_keys, option_source_t source=option_source_t::SOURCE_DIRECT)
 Read parameters of the current option.
 
option_info::pointer_t get_alias_destination (option_info::pointer_t opt) const
 Return the alias if there is one.
 
void get_direct_configuration_filenames (string_list_t &names, bool writable) const
 Define the list of direct configuration filenames.
 
void get_managed_configuration_filenames (string_list_t &names, bool writable, int argc, char *argv[]) const
 Generate the list of managed configuration filenames.
 
void initialize_parser (options_environment const &opt_env)
 Initialize the parser.
 
void is_parsed () const
 Verify that the parser is done.
 
void parse_options_from_file ()
 Check for a file with option definitions.
 
void parse_options_from_group_names ()
 Transform group names in –<name>-help commands.
 
void show_option_sources (std::basic_ostream< char > &out)
 Output the source of each option.
 

Static Private Member Functions

static void add_configuration_filename (string_list_t &names, std::string const &add)
 Add one configuration filename to our list.
 
static string_list_t find_config_dir (int argc, char *argv[])
 Search for the "--config-dir" option in a set of arguments.
 
static string_list_t parse_option_map (std::string const &raw_key)
 Parse a map following an option name.
 

Private Attributes

option_info::pointer_t f_default_option = option_info::pointer_t()
 
std::string f_environment_variable = std::string()
 
option_info::map_by_name_t f_options_by_name = option_info::map_by_name_t()
 
option_info::map_by_short_name_t f_options_by_short_name = option_info::map_by_short_name_t()
 
options_environment f_options_environment = options_environment()
 
bool f_parsed = false
 
std::string f_program_fullname = std::string()
 
std::string f_program_name = std::string()
 
variables::pointer_t f_variables = variables::pointer_t()
 

Detailed Description

This class is the one used by all the wpkg tools to parse the command line options. It is very advanced and is capable to read many different types of options with a letter (-h) and a word (–verbose) with no parameters, one parameter, any number of parameters, and a set of "filenames" (lose options that are not specific to an option.)

Definition at line 76 of file advgetopt.h.

Member Typedef Documentation

◆ pointer_t

Definition at line 79 of file advgetopt.h.

Constructor & Destructor Documentation

◆ getopt() [1/2]

advgetopt::getopt::getopt ( options_environment const opt_env)

Introduction

This constructor initializes a getopt object. It also reads and parses the corresponding option configuration file if it exists (based on the project name defined in the environment parameter.)

Program Name

Once constructed, if you want to have access to the program name, make sure to call this function with your argv variable:

opt.parse_program_name(argv);
constexpr flag_t option_flags_merge()
Definition flags.h:87

Remember that the program name is often used in error messages so having it defined early is generally a good idea.

Dynamic Options

This constructor is most often used when you want to dynamically add options to your executable with the parse_options_info() function. For example, the list of options may vary slightly depending on what your command is named when launched.

For example:

if(time(nullptr) & 1)
{
opt.parse_options_info(odd_options);
}
else
{
opt.parse_options_info(even_options);
}

Linking Aliases

After you added all your dynamic options, you want to make sure that aliases are linked to the final option. You should always call that function because you can't be sure whether someone will add such an alias in the .ini option file.

opt.link_aliases();

You can call this function any number of times. So if you add yet more dynamic options at a later time, just make sure to call it again in case aliases were added.

Parse the Arguments

Finally, you want to call the following functions in that order to parse the data from configuration files, the environment variable, and the list of command line arguments:

opt.parse_configuration_files();
opt.parse_environment_variable();

The order is important because the last command line option found is the one kept. So if the same argument is found in the configuration file, the environment variable and the command line, the one on the command line is kept. In most cases it makes no difference for standalone flags, but arguments that expect a parameter will be changed to the last specified value.

If you want to determine the configuration filenames, you may use the process_configuration_file() function directly instead of the parse_configuration_files() function. This also gives you the ability to test whether a configuration file was indeed read.

Note that the parse_arguments() last parameter (only_environment_variable) is expected to be left along when you call it with argc and argv.

If you just have a string instead of an argv variable, call the parse_string() function instead. It will transform your string in an array of arguments and then call the parse_arguments() for you.

Attention
Note that the program name does not get defined until you call the parse_program_name() function since that information comes from the first arguments of your command line which we do not get on construction in this case.
Since the arguments are not known to the getopt system yet, the GETOPT_ENVIRONMENT_FLAG_PROCESS_SYSTEM_PARAMETERS is not used in this case.
Parameters
[in]opt_envThe list of options that your program supports.
See also
link_aliases()
parse_arguments()
parse_configuration_files()
parse_environment_variable()
parse_string()
process_configuration_file()
initialize_parser()
finish_parsing()

Definition at line 546 of file advgetopt.cpp.

References initialize_parser().

◆ getopt() [2/2]

advgetopt::getopt::getopt ( options_environment const opt_env,
int  argc,
char argv[] 
)

The constructor initializes a getopt object and parse the specified argv array. If defined, it also parses a configuration file and an environment variable.

The order in which parameters are parsed is important since only the last value is kept:

  • Each existing configuration file in the order defined in the vector;
  • The environment variable;
  • the argv array.

The constructor calls the reset() function to start the parsing. It is possible to call the reset() function at any time to parse a new set of parameters.

The argv array cannot be nullptr and the array cannot be empty. It must have at least one entry representing the program name (argv[0]).

The configuration_files vector can be empty in which case no configuration files are read.

The environment_variable_name can be nullptr or the empty string in which case it is ignored.

Note
All the data gets copied while parsed. If the argv array is deleted on return, the getopt object remains valid.
Exceptions
getopt_exitThis function calls finish_parsing() which may throw this exception. See that function for details.
Parameters
[in]opt_envThe list of options that your program supports.
[in]argcThe number of arguments in argv.
[in]argvAn array of strings representing arguments.
See also
initialize_parser()
finish_parsing()

Definition at line 593 of file advgetopt.cpp.

References finish_parsing(), and initialize_parser().

Member Function Documentation

◆ add_configuration_filename()

void advgetopt::getopt::add_configuration_filename ( string_list_t names,
std::string const add 
)
staticprivate

This function adds the specified add name to the names list unless already present in the list.

Several of the functions computing configuration filenames can end up attempting to add the same filename multiple times. This function prevents the duplication. This also means the order may be slightly different than expected (i.e. the filenames don't get reordered when a duplicate is found).

Parameters
[in,out]namesThe list of configuration names.
[in]addThe new configuration filename to add.

Definition at line 129 of file advgetopt_config.cpp.

Referenced by get_direct_configuration_filenames(), and get_managed_configuration_filenames().

◆ add_option()

void advgetopt::getopt::add_option ( option_info::pointer_t  opt,
bool  ignore_duplicates = false 
)

This function is used to dynamically add one option to the advgetopt object.

This is often used in a library which wants to dynamically add support for library specific parameters to the command line.

Note
The ignore_duplicates option still gets the option added if only the short-name is a duplicate. In that case, we set the option's short-name to NO_SHORT_NAME before adding the option to the tables.
Parameters
[in]optThe option to be added.
[in]ignore_duplicateIf option is a duplicate, do not add it.

Definition at line 160 of file advgetopt_options.cpp.

References f_default_option, f_options_by_name, f_options_by_short_name, get_option(), advgetopt::GETOPT_FLAG_FLAG, advgetopt::NO_SHORT_NAME, and advgetopt::short_name_to_string().

Referenced by parse_options_from_file(), and parse_options_info().

◆ add_option_from_string()

void advgetopt::getopt::add_option_from_string ( option_info::pointer_t  opt,
std::string const value,
std::string const filename,
string_list_t const option_keys,
option_source_t  source = option_source_t::SOURCE_DIRECT 
)

This function accepts a string as the value. If the option accepts multiple values, then the function makes use of the set_multiple_value() function of the option_info class. This will break the option up in multiple values if possible.

Note
The function doesn't verify that the opt parameter is indeed an option defined in this getopt object. It is your responsibility to not mix options from different getopt.
Parameters
[in]optThe option receiving a value.
[in]valueThe value to assign this option.
[in]filenameThe name of a configuration file if the option was read from such.
[in]option_keysAn array of keys to prepend to each value.
[in]sourceWhere the value comes from.

Definition at line 1692 of file advgetopt.cpp.

References advgetopt::GETOPT_FLAG_FLAG, advgetopt::GETOPT_FLAG_MULTIPLE, advgetopt::GETOPT_FLAG_REQUIRED, advgetopt::is_false(), advgetopt::is_true(), and advgetopt::option_with_underscores().

Referenced by parse_arguments(), parse_environment_variable(), and process_configuration_file().

◆ add_options()

void advgetopt::getopt::add_options ( option_info::pointer_t  opt,
int i,
int  argc,
char **  argv,
string_list_t const option_keys,
option_source_t  source = option_source_t::SOURCE_DIRECT 
)
private

This function saves the option in the list of options found in this list of arguments. If the option is expected to have parameters, then those are taken from the argv array before the function saves the option in the object list. The index, i, is increased accordingly.

Warning
This function cannot be called properly with the '-' option in case it is viewed as a default parameter. This is because the algorithm expects the index (i) to be pointing to the command line option and not the argument to that command.
Parameters
[in]optThe concerned option
[in]iThe current position, starting with the option position
[in]argcThe number of arguments in the argv array.
[in]argvThe list of argument strings.
[in]option_keysAn array of keys to prepend to each value.
[in]sourceWhere the value comes from.

Definition at line 1619 of file advgetopt.cpp.

References advgetopt::GETOPT_FLAG_FLAG, advgetopt::GETOPT_FLAG_MULTIPLE, and advgetopt::GETOPT_FLAG_REQUIRED.

Referenced by parse_arguments().

◆ define_environment_variable_data()

void advgetopt::getopt::define_environment_variable_data ( )

This function retrieves the environment variable string and saves it in the f_environment_variable field. This is used to parse that string and add option values, and also by the configuration file loader to see whether a –config-dir was used in there.

Definition at line 764 of file advgetopt.cpp.

References f_environment_variable, advgetopt::options_environment::f_environment_variable_name, and f_options_environment.

Referenced by initialize_parser().

◆ find_config_dir()

string_list_t advgetopt::getopt::find_config_dir ( int  argc,
char argv[] 
)
staticprivate

This function searches the given list of argv arguments for the "--config-dir".

This is done that way because we prematurely need that information in order to properly search for the configuration file. This is because the "--config-dir" is not yet defined when we attempt to read the user specific configuration file.

Parameters
[in]argcThe number of arguments.
[in]argvThe list of arguments to be searched.

Definition at line 527 of file advgetopt_config.cpp.

Referenced by get_managed_configuration_filenames().

◆ find_group()

group_description const * advgetopt::getopt::find_group ( flag_t  group) const

This function is used to search for the name of a group.

Groups are used by the usage() function to list options by some user selected group.

For example, it is often that a tool has a set of commands such as --delete and a set of options such as --verbose. These can represent to clear groups of commands and options.

Parameters
[in]groupThe group to look for (i.e. GETOPT_FLAG_GROUP_ONE).
Returns
The group structure or nullptr when not found.

Definition at line 165 of file advgetopt_usage.cpp.

References advgetopt::options_environment::f_groups, f_options_environment, advgetopt::GETOPT_FLAG_GROUP_MASK, and advgetopt::GETOPT_FLAG_GROUP_NONE.

Referenced by usage().

◆ finish_parsing()

void advgetopt::getopt::finish_parsing ( int  argc,
char argv[] 
)

This function allows you to run the second half of the initialization process. We've broken this process up in two, so you can initialize a getopt object, add some other options, then finish up the initialization process by calling this function.

The command line arguments, configuration files.

Exceptions
getopt_exitIf the GETOPT_ENVIRONMENT_FLAG_PROCESS_SYSTEM_PARAMETERS is set and a system command was specified on the command, such as –help or –version, then that command is run and the function throws this exception.
Parameters
[in]argcThe number of arguments in argv.
[in]argvAn array of strings representing arguments.

Definition at line 661 of file advgetopt.cpp.

References f_options_by_name, f_parsed, advgetopt::GETOPT_ENVIRONMENT_FLAG_PROCESS_SYSTEM_PARAMETERS, has_flag(), link_aliases(), parse_arguments(), parse_configuration_files(), parse_environment_variable(), parse_program_name(), process_system_options(), advgetopt::SOURCE_COMMAND_LINE, and advgetopt::SYSTEM_OPTION_COMMANDS_MASK.

Referenced by getopt().

◆ get_alias_destination()

option_info::pointer_t advgetopt::getopt::get_alias_destination ( option_info::pointer_t  opt) const
private

This function returns the input opt parameter unless it is an alias in which case the destination alias option is returned instead.

Parameters
[in]optThe option for which an alias is desired.
Returns
opt unless it is an alias in which case opt->get_alias_destination() is returned.
See also
option_info::get_alias()

Definition at line 1459 of file advgetopt.cpp.

References advgetopt::GETOPT_FLAG_ALIAS.

Referenced by get_option(), and get_option().

◆ get_configuration_filename()

std::string advgetopt::getopt::get_configuration_filename ( int  idx) const

◆ get_configuration_filename_size()

size_t advgetopt::getopt::get_configuration_filename_size ( ) const

◆ get_configuration_filenames()

string_list_t advgetopt::getopt::get_configuration_filenames ( bool  exists,
bool  writable,
int  argc = 0,
char argv[] = nullptr 
) const

This function goes through the list of filenames and directories and generates a complete list of all the configuration files that the system will load when you call the parse_configuration_files() function.

Set the flag exists to true if you only want the name of files that currently exists.

The writable file means that we only want files under the <project-name>.d folder and the user configuration folder.

Note
The argc/argv and environment variable parameters are used whenever the function is called early and we can't call is_defined(). These are ignored otherwise.
Parameters
[in]existsRemove files that do not exist from the list.
[in]writableOnly return files we consider writable.
[in]argcThe number of arguments in argv.
[in]argvThe arguments passed to the finish_parsing() function or nullptr.
[in]environment_variableThe environment variable or an empty string.
Returns
The list of configuration filenames.

Definition at line 85 of file advgetopt_config.cpp.

References get_direct_configuration_filenames(), and get_managed_configuration_filenames().

Referenced by parse_configuration_files(), process_help_string(), and process_system_options().

◆ get_default()

std::string advgetopt::getopt::get_default ( std::string const name) const

When an option is not defined, you may use this function to retrieve its default instead. This is actually done automatically when you call the get_string() or get_long() functions.

An option without a default has this function returning nullptr.

Note
Whether an option has a default value should be checked with the has_default() function which returns true when the default value was defined. An option with an empty string as the default is a valid case which cannot be detected otherwise.
Exceptions
getopt_exception_undefinedThe getopt_exception_undefined exception is raised if this function is called with an empty name.
Parameters
[in]nameThe name of the parameter of which you want to retrieve the default value.
Returns
The default value or an empty string if no value is defined.

Definition at line 191 of file advgetopt_data.cpp.

References get_option().

Referenced by process_system_options().

◆ get_direct_configuration_filenames()

void advgetopt::getopt::get_direct_configuration_filenames ( string_list_t names,
bool  writable 
) const
private

We generate two lists of configurations: a managed list and a direct configuration list. The managed list is created with the get_managed_configuration_filenames(). The direct list is created with this function and the list of filenames defined in the f_configuration_files list of paths.

In this case, the paths defined in that list are directly used. No additional directory are added, except for the sub-directory to allow for administrator files to be edited (i.e. \<name>.d/??-filename.conf).

Parameters
[in,out]namesThe list of configuration filenames.
[in]writableWhether only writable filenames get added.

Definition at line 293 of file advgetopt_config.cpp.

References add_configuration_filename(), advgetopt::options_environment::f_configuration_files, advgetopt::options_environment::f_group_name, f_options_environment, advgetopt::options_environment::f_project_name, advgetopt::handle_user_directory(), and advgetopt::insert_group_name().

Referenced by get_configuration_filenames().

◆ get_double()

double advgetopt::getopt::get_double ( std::string const name,
int  idx = 0,
double  min = std::numeric_limits<double>::min(),
double  max = std::numeric_limits<double>::max() 
) const

This function reads the specified argument from the named option and transforms it to a double value. It then checks the result against the specified minimum and maximum range.

The function name represents an argument that needs to be defined. You can test whether it was defined on the command line with the is_defined() function. The index must be between 0 and 'size() - 1' inclusive. If the item was not defined, then size() returns zero and you cannot call this function.

The function does not check the validity of the minimum and maximum parameters. If min > max is true then the function will always fail with a call to usage() as no value can be defined between min and max in that case. The minimum and maximum values are inclusive, so a range of 1 to 9 is defined with exactly 1 and 9 in min and max. For example, the z library compression could be retrieved with:

int level(6); // default to 6
if(opt.is_defined("zlevel"))
{
zlevel = opt.get_double("zlevel", 0, 1.0, 9.0);
}

Note that the function can be used to read unsigned numbers, however at this point getopt does not really support negative numbers (i.e. because -<number> is viewed as an option.)

Todo:
Fix example with a parameter which makes sense (i.e. accepts doubles).
Exceptions
getopt_exception_undefinedThe getopt_exception_undefined exception is raised if name was not found on the command line and it has no default, or if idx is out of bounds.
Parameters
[in]nameThe name of the option to retrieve.
[in]idxThe index of the argument to retrieve.
[in]minThe minimum value that will be returned (inclusive).
[in]maxThe maximum value that will be returned (inclusive).
Returns
The argument as a long.

Definition at line 354 of file advgetopt_data.cpp.

References advgetopt::validator_double::convert_string(), get_option(), and is_parsed().

◆ get_environment_variable()

std::string advgetopt::getopt::get_environment_variable ( ) const

◆ get_environment_variable_name()

std::string advgetopt::getopt::get_environment_variable_name ( ) const

◆ get_group_name()

std::string advgetopt::getopt::get_group_name ( ) const

This function returns the name of the group as defined in the options_environment structure passed to the constructor. This is the main group name (TODO: fix the name).

The group name is used for the sub-folder because at times many projects are going to use the same sub-folder.

Returns
The name of the group, maybe empty if undefined.

Definition at line 214 of file advgetopt_access.cpp.

References advgetopt::options_environment::f_group_name, and f_options_environment.

◆ get_group_or_project_name()

std::string advgetopt::getopt::get_group_or_project_name ( ) const

There are a few places where we want to use the group or project name. This function checks the group first. If not defined, then the project name is returned.

This is used to determine the path to configuration files.

Returns
The name of the group, the project or an empty string.

Definition at line 234 of file advgetopt_access.cpp.

References advgetopt::options_environment::f_group_name, f_options_environment, and advgetopt::options_environment::f_project_name.

Referenced by get_managed_configuration_filenames(), get_options_filename(), get_output_filename(), and parse_options_from_file().

◆ get_long()

long advgetopt::getopt::get_long ( std::string const name,
int  idx = 0,
long  min = std::numeric_limits<long>::min(),
long  max = std::numeric_limits<long>::max() 
) const

This function reads the specified argument from the named option and transforms it to a long value. It then checks the result against the specified minimum and maximum range.

The function name represents an argument that needs to be defined. You can test whether it was defined on the command line with the is_defined() function. The index must be between 0 and 'size() - 1' inclusive. If the item was not defined, then size() returns zero and you cannot call this function.

The function does not check the validity of the minimum and maximum parameters. If min > max is true then the function will always fail with a call to usage() as no value can be defined between min and max in that case. The minimum and maximum values are inclusive, so a range of 1 to 9 is defined with exactly 1 and 9 in min and max. For example, the z library compression could be retrieved with:

int level(6); // default to 6
if(opt.is_defined("zlevel"))
{
zlevel = opt.get_long("zlevel", 0, 1, 9);
}

Note that the function can be used to read unsigned numbers, however at this point getopt does not really support negative numbers (i.e. because -<number> is viewed as an option.)

Exceptions
getopt_exception_undefinedThe getopt_exception_undefined exception is raised if name was not found on the command line and it has no default, or if idx is out of bounds.
Parameters
[in]nameThe name of the option to retrieve.
[in]idxThe index of the argument to retrieve.
[in]minThe minimum value that will be returned (inclusive).
[in]maxThe maximum value that will be returned (inclusive).
Returns
The argument as a long.

Definition at line 246 of file advgetopt_data.cpp.

References advgetopt::validator_integer::convert_string(), get_option(), and is_parsed().

◆ get_managed_configuration_filenames()

void advgetopt::getopt::get_managed_configuration_filenames ( string_list_t names,
bool  writable,
int  argc,
char argv[] 
) const
private

As the programmer, you can define a configuration filename and a set of directory names. This function uses that information to generate a list of full configuration filenames that is then used to load those configurations.

If a filename is defined, but no directories, the this function defines three default paths like so:

  • /usr/share/advgetopt/options/\<name>
  • /usr/share/\<name>/options
  • /etc/\<name>
Parameters
[in,out]namesThe list of names are added to this list.
[in]writableWhether the destination has to be writable.
[in]argcThe number of arguments in argv.
[in]argvThe command line arguments.

Definition at line 157 of file advgetopt_config.cpp.

References add_configuration_filename(), advgetopt::options_environment::f_configuration_directories, advgetopt::options_environment::f_configuration_filename, f_environment_variable, advgetopt::options_environment::f_group_name, f_options_environment, f_parsed, f_program_fullname, advgetopt::options_environment::f_project_name, find_config_dir(), get_group_or_project_name(), get_string(), advgetopt::GETOPT_ENVIRONMENT_FLAG_SYSTEM_PARAMETERS, advgetopt::handle_user_directory(), has_flag(), advgetopt::insert_group_name(), is_defined(), size(), and split_environment().

Referenced by get_configuration_filenames().

◆ get_option() [1/2]

option_info::pointer_t advgetopt::getopt::get_option ( short_name_t  short_name,
bool  exact_option = false 
) const

This function searches for an option given its short name.

By default the function returns the final option. That is, if the named option is an alias, the destination option is returned, not the alias. This way the rest of the code is much simpler. You may get the exact option, even if it is aliased, by setting the exact_option parameter to true. It is really rare that you would need to do so, though.

Parameters
[in]short_nameThe short name of the option to look for.
[in]exact_optionReturn the exact option, not its alias.
Returns
The pointer to the option or nullptr if not found.

Definition at line 1585 of file advgetopt.cpp.

References f_options_by_short_name, and get_alias_destination().

◆ get_option() [2/2]

option_info::pointer_t advgetopt::getopt::get_option ( std::string const name,
bool  exact_option = false 
) const

This function retrieves an option by name. The function handles the special case of the default option. This means "--" can always be used to access the default option, whatever the name given to that option in the declaration of your options.

Of course, if no default is defined, then "--" returns a nullptr.

By default the function returns the final option. That is, if the named option is an alias, the destination option is returned, not the alias. This way the rest of the code is much simpler. You may get the exact option, even if it is aliased, by setting the exact_option parameter to true. It is really rare that you would need to do so.

Note
The name parameter could be an empty string to represent the default value (I think that's what that was for, now you use "--"). I've added the throw in this function to catch that invalid use, which either means you tried to check something with an invalid name or are expected to use the "--".
Parameters
[in]nameThe name of the option to retrieve.
[in]exact_optionReturn the exact option, not its alias.
Returns
The pointer to the named option or nullptr if not found.

Definition at line 1519 of file advgetopt.cpp.

References f_default_option, f_options_by_name, f_options_by_short_name, get_alias_destination(), advgetopt::NO_SHORT_NAME, advgetopt::option_with_dashes(), and advgetopt::string_to_short_name().

Referenced by add_option(), get_default(), get_double(), get_long(), get_string(), has_default(), is_defined(), link_aliases(), operator[](), operator[](), parse_arguments(), process_configuration_file(), and size().

◆ get_options()

option_info::map_by_name_t const & advgetopt::getopt::get_options ( ) const

Applications that let their users enter dynamically options need to have access to the resulting list of options which may not otherwise be known.

Returns
The map of options indexed by name.
See also
parse_options_from_file()

Definition at line 1485 of file advgetopt.cpp.

References f_options_by_name.

◆ get_options_environment()

options_environment const & advgetopt::getopt::get_options_environment ( ) const

This function returns a reference to the options environment that was passed to the constructor. This is useful to functions that do not otherwise have access to that object.

Returns
This getopt options environment.

Definition at line 733 of file advgetopt.cpp.

References f_options_environment.

◆ get_options_filename()

std::string advgetopt::getopt::get_options_filename ( ) const

The programmer can define a path to options that the tool will load. By default, that path is expected to be /usr/share/advgetopt.

In order to allow debugging as a programmer, we also support changing the source through an environment variable named ADVGETOPT_OPTIONS_FILES_DIRECTORY. This variable is checked first and any other path is ignored if it is defined and not just an empty string.

Note
If somehow you did not define a group or a project name, then the function will return an empty string. Otherwise, this path always exists.
Returns
The path or an empty string.

Definition at line 232 of file advgetopt_options.cpp.

References f_options_environment, advgetopt::options_environment::f_options_files_directory, and get_group_or_project_name().

Referenced by parse_options_from_file(), and process_help_string().

◆ get_output_filename()

std::string advgetopt::getopt::get_output_filename ( ) const

This function determines the best suited filename where an administrator is expected to save his changes. For some tools, there may be many choices. This function looks for the last entry since that last entry will allow the administrator to override anything defined prior to this last entry.

The search first uses the direct configuration filenames if these are defined. It uses the last directory which does not start with a tilde (i.e. no user file).

If the direct configuration is not defined in that process, we next test with the managed configuration filenames. We again look for the last path and that along the last configuration filename.

If all of that fails, we build a name from "/etc/" the project name, and use the project name plus ".conf" for the filename:

"/etc/" + project_name + "/" + project_name + ".conf"

then pass that file to the default_group_name() function. The result is what gets returned.

Returns
The file the administrator is expected to edit to make changes to the configuration of the given project.

Definition at line 371 of file advgetopt_config.cpp.

References advgetopt::default_group_name(), advgetopt::options_environment::f_configuration_directories, advgetopt::options_environment::f_configuration_filename, advgetopt::options_environment::f_configuration_files, advgetopt::options_environment::f_group_name, f_options_environment, advgetopt::options_environment::f_project_name, and get_group_or_project_name().

Referenced by process_help_string().

◆ get_program_fullname()

std::string advgetopt::getopt::get_program_fullname ( ) const

This function return the name of the program exactly as it was passed to the program via argv[0].

The reset() function will reset this parameter. If you are creating internal lists of parameters that you want to parse with the same getopt object and your main getopt object, then you may want to consider using this function to define argv[0] of your new list:

std::vector<std::string> args;
args.push_back(my_opts.get_program_fullname());
args.push_back("--test");
[...]
// the following probably require some const_cast<>(), but that's the idea
my_opts.reset(args.size(), &args[0], ...);
Returns
The contents of the argv[0] parameter as defined on construction.
See also
parse_program_name()

Definition at line 123 of file advgetopt_access.cpp.

References f_program_fullname.

Referenced by options_to_string().

◆ get_program_name()

std::string advgetopt::getopt::get_program_name ( ) const

This function retrieves the basename, the name of the program with its path trimmed, from this getopt object.

This is defined from the argv[0] parameter passed to the constructor or the last reset() call.

Returns
The basename of the program.
See also
parse_program_name()

Definition at line 141 of file advgetopt_access.cpp.

References f_program_name.

◆ get_project_name()

std::string advgetopt::getopt::get_project_name ( ) const

This function returns the name of the project as defined in the options_environment structure passed to the constructor.

For example, the snapwebsites project makes use of "snapwebsites" name as its common project name. Many of the configuration files are found under that sub-folder. This ensures that the configuration files are searched for under the indicated folders and again under:

So if you have a configuration file named "snapserver.conf" with a path such as "/etc/snapwebsites", you end up with:

"/etc/snapwebsites/snapserver.conf"
"/etc/snapwebsites/snapwebsites.d/snapserver.conf"

Notice that the loader adds a ".d" at the end of the project name. Also, if the user were to specify a different filename with the –config command line option, it could end up like this:

... --config /home/alexis/.config/iplock/iplock.conf ...
# First we read this file:
"/home/alexis/.config/iplock/iplock.conf"
# Second we read this file (assuming the same project name
# of "snapwebsites"):
"/home/alexis/.config/iplock/snapwebsites.d/iplock.conf"

The order is important as well. We first load the direct path, then the path with the sub-folder. Finally, we move forward to the next configuration file. We ignore errors when a file can't be loaded or is missing.

Returns
The name of the project, maybe empty if undefined.

Definition at line 191 of file advgetopt_access.cpp.

References f_options_environment, and advgetopt::options_environment::f_project_name.

◆ get_string()

std::string advgetopt::getopt::get_string ( std::string const name,
int  idx = 0,
bool  raw = false 
) const

Get the content of the named parameter as a string. Command line options that accept multiple arguments accept the idx parameter to specify which item you are interested in.

Note that the option must have been specified on the command line or have a default value. For options that do not have a default value, you want to call the is_defined() function first.

Note
If the function returns the default value, it gets returned as is. i.e. it won't be passed through the variable processing function.
Exceptions
getopt_exception_undefinedThe getopt_exception_undefined exception is raised if name was not found on the command line and it has no default, or if idx is out of bounds.
Parameters
[in]nameThe name of the option to read.
[in]idxThe zero based index of a multi-argument command line option.
[in]rawWhether to return the value without replacing the variables.
Returns
The option argument as a string.

Definition at line 442 of file advgetopt_data.cpp.

References get_option(), advgetopt::GETOPT_FLAG_REQUIRED, and is_parsed().

Referenced by get_managed_configuration_filenames(), and process_system_options().

◆ get_variables()

variables::pointer_t advgetopt::getopt::get_variables ( ) const

This function retrieves the variables defined in the getopt object. This is useful if you want to support those variables within configuration files that you read later on.

Note
This pointer is never a nullptr.
Returns
A pointer to the getopt variables.

Definition at line 1797 of file advgetopt.cpp.

References f_variables.

◆ has_default()

bool advgetopt::getopt::has_default ( std::string const name) const

Some parameters may be given a default. This function is used to detect whether such a default value is defined.

Note
This function is particularly useful in the event the default value may be an empty string.
Exceptions
getopt_exception_undefinedThe getopt_exception_undefined exception is raised if this function is called with an empty name.
Parameters
[in]nameThe name of the parameter of which you want to know whether it has a default value or not.
Returns
true if the default value was defined (even if an empty string.)

Definition at line 156 of file advgetopt_data.cpp.

References get_option().

Referenced by process_system_options().

◆ has_flag()

bool advgetopt::getopt::has_flag ( flag_t  flag) const

This function checks the environment flags for the specified flag. When the flag is set, the function returns true.

You may test multiple flags at the same time, if any one of them is set, then the function returns true.

Parameters
[in]flagThe flag to check out.
Returns
true if the flag is set.

Definition at line 751 of file advgetopt.cpp.

References advgetopt::options_environment::f_environment_flags, and f_options_environment.

Referenced by finish_parsing(), get_managed_configuration_filenames(), initialize_parser(), and process_configuration_file().

◆ initialize_parser()

void advgetopt::getopt::initialize_parser ( options_environment const opt_env)
private

This function is called from the two constructors. It initializes the basic options from the user definitions, the file when there is one, the group names, and if allowed the system command line options.

This is enough to then parse arguments or configuration files, although in most cases this is used to allow for additional environment options to be inserted before calling the finish_parsing() function.

Parameters
[in]opt_envThe list of options that your program supports.

Definition at line 619 of file advgetopt.cpp.

References define_environment_variable_data(), advgetopt::options_environment::f_configuration_filename, advgetopt::options_environment::f_options, f_options_environment, f_variables, advgetopt::GETOPT_ENVIRONMENT_FLAG_PROCESS_SYSTEM_PARAMETERS, advgetopt::GETOPT_ENVIRONMENT_FLAG_SYSTEM_PARAMETERS, has_flag(), parse_options_from_file(), parse_options_from_group_names(), and parse_options_info().

Referenced by getopt(), and getopt().

◆ is_defined()

bool advgetopt::getopt::is_defined ( std::string const name) const

This function returns true if the specified parameter is found as part of the command line options.

You must specify the long name of the option. So a --verbose option can be checked with:

if(is_defined("verbose")) ...
bool is_defined(std::string const &name) const
Check whether a parameter is defined.

For options that come with a short name, you may also specify the short name. This is done with a string in this case. It can be a UTF-8 character. The short name is used if the string represents exactly one Unicode character. So the following is equivalent to the previous example, assuming your verbose definition has v as the short name:

if(is_defined("v")) ...
Note
This function returns true when the option was found on the command line, the environment variable, or a configuration file. It returns false if the option is defined, but was not specified anywhere by the client using your program. Also, specifying the option in one of those three locations when not allowed at that location will not result in this flag being raised.
Parameters
[in]nameThe long name or short name of the option to check.
Returns
true if the option was defined in a configuration file, the environment variable, or the command line.

Definition at line 96 of file advgetopt_data.cpp.

References get_option(), and is_parsed().

Referenced by get_managed_configuration_filenames(), and process_system_options().

◆ is_parsed()

void advgetopt::getopt::is_parsed ( ) const
private

This function ensures that the parser is done. If the parser is not yet done, then the function raises an exception. This allows me to detect that I am trying to access a parameter before the whole parsing process is done (i.e. I had a call to is_defined("config-dir") happening in the configuration handling way before the environment variables and command line arguments were parsed, that would never work!)

Exceptions
getopt_initializationThis exception is raised if the parser is not done yet.

Definition at line 712 of file advgetopt.cpp.

References advgetopt::options_environment::f_environment_flags, f_options_environment, f_parsed, and advgetopt::GETOPT_ENVIRONMENT_FLAG_AUTO_DONE.

Referenced by get_double(), get_long(), get_string(), is_defined(), operator[](), operator[](), and size().

◆ link_aliases()

void advgetopt::getopt::link_aliases ( )

After we defined all the options, go through the list again to find aliases and link them with their corresponding alias option.

Exceptions
getopt_exception_invalidAll aliases must exist or this exception is raised.

Definition at line 561 of file advgetopt_options.cpp.

References f_options_by_name, get_option(), and advgetopt::GETOPT_FLAG_ALIAS.

Referenced by finish_parsing().

◆ operator[]() [1/2]

option_info_ref advgetopt::getopt::operator[] ( std::string const name)

This function allows you to access an argument which may or may not yet exist.

The return value is a reference to that parameter. You can read and write to the reference.

A non-existant argument is created only if necessary. That is, only if you actually use an assignment operator as follow:

// straight assignment:
opt["my-var"] = "123";
// or concatenation:
opt["my-var"] += "append";

In read mode and unless you defined a default, a non-existant argument is viewed as an empty string or 0 if retrieved as a long:

// if non-existant you get an empty string:
std::string value = opt["non-existant"];
// if non-existant you get zero:
long value = opt["non-existant"].get_long();

The get_long() function may generate an error if the parameter is not a valid integer. Also when a default is defined, it tries to convert the default value to a number and if that fails an error is generated.

Note
This operator only allows you to access the very first value of this option. If the option is marked with GETOPT_FLAG_MULTIPLE, you may want to use the get_option() function and then handle the option multiple values manually with the option_info::get_value() and option_info::set_value().
Warning
If the option is an alias and the destination is not defined you can still get an exception raised.
Parameters
[in]nameThe name of the option to access.
Returns
A reference to this option with support for many std::string like operators.

Definition at line 577 of file advgetopt_data.cpp.

References f_options_by_name, f_variables, get_option(), advgetopt::GETOPT_FLAG_DYNAMIC_CONFIGURATION, and is_parsed().

◆ operator[]() [2/2]

std::string advgetopt::getopt::operator[] ( std::string const name) const

This operator returns the value of an argument just like the get_string() does when the argument is defined. When the argument is not defined and it has no default, it returns an empty string instead of throwing.

The function is only capable of returning the very first value. If this argument has the GETOPT_FLAG_MULTIPLE flag set, you probably want to use the get_string() instead.

Parameters
[in]nameThe name of the option to retrieve.
Returns
The value of that option or an empty string if not defined.

Definition at line 499 of file advgetopt_data.cpp.

References get_option(), and is_parsed().

◆ options_to_string()

std::string advgetopt::getopt::options_to_string ( bool  include_progname = false,
bool  keep_defaults = false 
) const

This function creates a string which system() can use to start the command again with the same options. You may, of course, tweak the options first.

Parameters
[in]include_prognameWhether the program name should be included in the output string. In some cases, you may want to start a different program with similar command line options. This gives you that option.
[in]keep_defaultsIf the value is equal to the default value, it gets ignored unless this parameter is set to true.
Returns
The string representing the command line options.

Definition at line 70 of file advgetopt_string.cpp.

References advgetopt::escape_shell_argument(), f_options_by_name, get_program_fullname(), and advgetopt::GETOPT_FLAG_FLAG.

◆ parse_arguments()

void advgetopt::getopt::parse_arguments ( int  argc,
char argv[],
option_source_t  source = option_source_t::SOURCE_DIRECT,
bool  only_environment_variable = false 
)

This function accepts an array of arguments as received by the main() function. By default, though, you pass the argc/argv parameters to the getopt() constructor which automatically calls this function.

This functin is public so you can call it with additional lists of arguments. If that list of arguments comes as a string, you may want to call the parse_string() function instead. It will transform your string in a list of parameters for you.

When the only_environment_variable parameter is set to true, then it is considered that the input arguments were found in an environment variables and they are only accepted if the corresponding option definition includes the GETOPT_FLAG_ENVIRONMENT_VARIABLE flag.

When the only_environment_variable parameter is set to false, the arguments are viewed as command line arguments and the corresponding options must include the GETOPT_FLAG_COMMAND_LINE flag.

Variables get overridden by the newest values found in the list of arguments.

Note that the command line arguments are the only ones that should include a command (opposed to an option that alters the behavior of your commands.) However, the advgetopt system expects you to properly define what can be used in a configuration file, in an environment variable, or directly on the command line. It is not in charge of that part in itself.

Note
The code may find some errors in the tables passed to the advgetopt environment (i.e. a duplicate definition.) When such errors are detected, an exception is raised. Errors found on the command line generate a log message. If you setup a callback, you can then decide to either call exit(1) or raise your own exception.
The function does NOT check whether the list of arguments (argv) is terminated by nullptr. The argc parameter must be correct.
Parameters
[in]argcThe number of arguments in argv.
[in]argvThe argument strings terminated by a nullptr.
[in]sourceWhere the value comes from.
[in]only_environment_variableAccept command line arguments (false) or environment variable arguments (true).

Definition at line 1037 of file advgetopt.cpp.

References add_option_from_string(), add_options(), f_default_option, f_parsed, get_option(), advgetopt::GETOPT_FLAG_ARRAY, advgetopt::GETOPT_FLAG_COMMAND_LINE, advgetopt::GETOPT_FLAG_ENVIRONMENT_VARIABLE, parse_option_map(), and advgetopt::short_name_to_string().

Referenced by finish_parsing(), and parse_string().

◆ parse_configuration_files()

void advgetopt::getopt::parse_configuration_files ( int  argc = 0,
char argv[] = nullptr 
)

Each configuration file is checked one after another. Each file that is defined is loaded and each line is viewed as an option. If valid, it is added to the resulting getopt list of options.

Note that it is an error to define a command in a configuration file. If that happens, an error occurs and the process stops. Technically this is defined with the GETOPT_FLAG_CONFIGURATION_FILE flag in your opt table.

The list of files is checked from beginning to end. So if a later file changes an option of an earlier file, it is the one effective.

The configuration file loader supports a project name as defined in the get_project_name() function. It allows for a sub-directory to be inserted between the path and the basename of the configuration file. This allows for a file to be search in an extra sub-directory so one can avoid changing the original definitions and only use configuration files in the sub-directory. The path looks like this when a project name is specified:

<path>/<project name>.d/<basename>

Notice that we add a ".d" as usual in other projects under Linux.

Exceptions
getopt_exception_invalidThis function generates the getopt_exception_invalid exception whenever something invalid is found in the list of options passed as the opts parameter.
getopt_exception_defaultThe function detects whether two options are marked as the default option (the one receiving parameters that are not used by another command or match a command.) This exception is raised when such is detected.
Parameters
[in]argcThe number of arguments in argv.
[in]argvThe arguments passed to the finish_parsing() function.
See also
process_configuration_file()
get_configuration_filenames()
finish_parsing()

Definition at line 605 of file advgetopt_config.cpp.

References f_parsed, get_configuration_filenames(), and process_configuration_file().

Referenced by finish_parsing().

◆ parse_environment_variable()

void advgetopt::getopt::parse_environment_variable ( )

If the name of an environment variable is specified in the option environment structure, then it is read as a command line string. This function parses the string in an array of strings and then parses it as an argv array (just like the argv parameter defined in a main() function).

Since the environment variable is checked after the configuration files, the options defined in the variable can change the definitions from the configuration files.

Like in the configuration files, only options can be specified in the environment variable and commands generate an error. The system knows since options that can be included in the environment variable are marked by the GETOPT_FLAG_ENVIRONMENT_VARIABLE flag. In other words, you may allow options to appear on the command line, in configuration files, in environment variables or a mix of all of these locations.

Note
If you change the environment variable between the creation of the getopt object and a call to this function, you want to call the define_environment_variable_data() again to make sure it can be parsed.

Definition at line 813 of file advgetopt.cpp.

References add_option_from_string(), f_environment_variable, advgetopt::options_environment::f_environment_variable_intro, f_options_by_name, f_options_environment, f_parsed, parse_string(), and advgetopt::SOURCE_ENVIRONMENT_VARIABLE.

Referenced by finish_parsing().

◆ parse_option_map()

string_list_t advgetopt::getopt::parse_option_map ( std::string const raw_key)
staticprivate

An option may offer the ARRAY capability. This means the option can be used multiple times with a different key as in:

--name:front 123
--name:back 456

The keys in that case are front and back. The key will be saved along the option value and you can later retrieve the corresponding value using the get_string() with a string representing the key.

name_front = f_opts.get_string("front"); // returns 123
name_back = f_opts.get_string("back"); // returns 456

This function searches for the map key names. The map syntax supports any number of key names either separated by colons or written between square brackets:

--name[front] 123
--name[back] 456

are equivalent to the example above.

The map is not limited to one name. At the moment the keys are not verified outside of the requirement of not being empty.

The following shows how to define more than one key:

--name[front][back] 123
--name:front:back 123
--name[back][front] 123
--name:back:front 123

In which case both keys are given the same value(s). So you still have one "front" and one "back" value, only both are set to 123.

If you want to have keys that include multiple names in themselves, use the period as in:

--name:front.color red
--name:back.color blue

Internally, the period is a character like any other (and will remain that way) so the advgetopt library does not know that "front.color" would represent "color" field in the "front" object.

Parameters
[in]raw_keyThe key as written by the user.
Returns
The canonicalized key or an empty string on error.

Definition at line 1386 of file advgetopt.cpp.

References advgetopt::split_string().

Referenced by parse_arguments().

◆ parse_options_from_file() [1/2]

void advgetopt::getopt::parse_options_from_file ( )
private

This function tries to read the default option file for this process. This filename is generated using the the option environment files directory and the project name.

If the directory is not defined, the function uses this default path: "/usr/share/advgetopt/options/". See the other parse_options_from_file(std::string const & filename, int min_sections, int max_sections) function for additional details.

See also
parse_options_from_file(std::string const & filename, int min_sections, int max_sections)

Definition at line 278 of file advgetopt_options.cpp.

References get_options_filename(), and parse_options_from_file().

Referenced by initialize_parser(), and parse_options_from_file().

◆ parse_options_from_file() [2/2]

void advgetopt::getopt::parse_options_from_file ( std::string const filename,
int  min_sections,
int  max_sections,
bool  ignore_duplicates = false 
)

This function tries to read the specified file for command line options for this application. These are similar to the option structure, only it is defined in a file.

The format of the file is like so:

  • Option names are defined on a line by themselves between square brackets.
  • Parameters of that option are defined below as a name=<value>.

Example:

[<command-name>]
default=<default value>
validator=<validator name>[(<param>[,<param>...])]|/<regex>/<flags>
std::string usage(flag_t show=GETOPT_FLAG_SHOW_MOST) const
Create a string of the command line arguments.
Structure representing an option.
Definition options.h:70

The number of namespaces in <command-name> can be limited using the min_sections and max_sections parameters.

The function can be called multiple times. The first time, it verifies that there are not duplicated settings. On following loads, that test is ignored.

Todo:
Test that options get 100% updated on a reload.
Note
By default, this function is called with one specific filename based on the f_project_name field and the f_options_files_directory as defined in the options environment.
Parameters
[in]filenameThe filename to load.
[in]min_sectionsThe minimum number of namespaces.
[in]max_sectionsThe maximum number of namespaces.
[in]ignore_duplicatesWhether duplicates are okay or not.
See also
parse_options_from_file()

Definition at line 332 of file advgetopt_options.cpp.

References add_option(), advgetopt::ASSIGNMENT_OPERATOR_EQUAL, advgetopt::COMMENT_INI, advgetopt::COMMENT_SHELL, f_variables, advgetopt::conf_file::get_conf_file(), get_group_or_project_name(), advgetopt::GETOPT_FLAG_ALIAS, advgetopt::GETOPT_FLAG_COMMAND_LINE, advgetopt::GETOPT_FLAG_CONFIGURATION_FILE, advgetopt::GETOPT_FLAG_DYNAMIC_CONFIGURATION, advgetopt::GETOPT_FLAG_ENVIRONMENT_VARIABLE, advgetopt::GETOPT_FLAG_FLAG, advgetopt::GETOPT_FLAG_GROUP_COMMANDS, advgetopt::GETOPT_FLAG_GROUP_FIVE, advgetopt::GETOPT_FLAG_GROUP_FOUR, advgetopt::GETOPT_FLAG_GROUP_OPTIONS, advgetopt::GETOPT_FLAG_GROUP_SEVEN, advgetopt::GETOPT_FLAG_GROUP_SIX, advgetopt::GETOPT_FLAG_GROUP_THREE, advgetopt::GETOPT_FLAG_MULTIPLE, advgetopt::GETOPT_FLAG_REQUIRED, advgetopt::GETOPT_FLAG_SHOW_USAGE_ON_ERROR, advgetopt::conf_file_setup::is_valid(), advgetopt::line_continuation_unix, advgetopt::NO_SHORT_NAME, advgetopt::SECTION_OPERATOR_INI_FILE, advgetopt::SECTION_OPERATOR_ONE_SECTION, advgetopt::conf_file_setup::set_section_to_ignore(), advgetopt::split_string(), and advgetopt::unquote().

◆ parse_options_from_group_names()

void advgetopt::getopt::parse_options_from_group_names ( )
private

◆ parse_options_info()

void advgetopt::getopt::parse_options_info ( option const opts,
bool  ignore_duplicates = false 
)

◆ parse_program_name()

void advgetopt::getopt::parse_program_name ( char argv[])

This function is transforms the first command line argument in a program name. It will define two versions, the basename and the fullname which you can access with the get_program_name() and get_program_fullname() functions.

Note
The p and %*p options of the process_help_string() function make use of this parameter. If you never call this function, they both use an empty string as the program name.
Exceptions
getopt_exception_logicIf you call this function with a null pointer, then it raises this exception.
Parameters
[in]argvThe arguments vector.
See also
get_program_name()
get_program_fullname()
process_help_string()

Definition at line 69 of file advgetopt_access.cpp.

References f_program_fullname, and f_program_name.

Referenced by finish_parsing().

◆ parse_string()

void advgetopt::getopt::parse_string ( std::string const str,
option_source_t  source = option_source_t::SOURCE_DIRECT,
bool  only_environment_variable = false 
)

This function parses a line of command line arguments from a string. Especially, it is used to parse the environment variable which is a string of arguments.

This can be used to parse the command line string as received under MS-Windows (i.e. an unparsed one long string of arguments, where you also need to do the glob() calls yourself.)

This function actually transforms the input string in an array of strings and then calls the parse_arguments() function.

Note
The input allows for an empty string in which case pretty much nothing happens.
Parameters
[in]strThe string that is going to be parsed.
[in]sourceWhere the value comes from.
[in]only_environment_variableWhether only options marked with the GETOPT_FLAG_ENVIRONMENT_VARIABLE flag are accepted.

Definition at line 873 of file advgetopt.cpp.

References f_program_fullname, parse_arguments(), and split_environment().

Referenced by parse_environment_variable().

◆ process_configuration_file()

void advgetopt::getopt::process_configuration_file ( std::string const filename)

This function reads one specific configuration file using a conf_file object and then goes through the resulting arguments and add them to the options of this getopt object.

The options found in the configuration file must match an option by its long name. In a configuration file, it is not allowed to have an option which name is only one character.

Note
If the filename points to a file which can't be read or does not exist, then nothing happens and the function returns without an error.
Todo:
Extend the support by having the various flags that the conf_file class supports appear in the list of configuration filenames.
Parameters
[in]filenameThe name of the configuration file to check out.
See also
parse_configuration_files()

Definition at line 641 of file advgetopt_config.cpp.

References add_option_from_string(), advgetopt::ASSIGNMENT_APPEND, advgetopt::ASSIGNMENT_NEW, advgetopt::ASSIGNMENT_NONE, advgetopt::ASSIGNMENT_OPTIONAL, advgetopt::ASSIGNMENT_SET, advgetopt::CONFIGURATION_SECTIONS, advgetopt::options_environment::f_config_setup, f_options_by_name, f_options_environment, f_parsed, advgetopt::options_environment::f_section_variables_name, f_variables, advgetopt::conf_file::get_conf_file(), get_option(), advgetopt::GETOPT_ENVIRONMENT_FLAG_DYNAMIC_PARAMETERS, advgetopt::GETOPT_FLAG_CONFIGURATION_FILE, advgetopt::GETOPT_FLAG_DYNAMIC, advgetopt::GETOPT_FLAG_MULTIPLE, has_flag(), advgetopt::option_with_underscores(), advgetopt::option_info::set_configuration_filename(), and advgetopt::SOURCE_CONFIGURATION.

Referenced by parse_configuration_files().

◆ process_help_string()

std::string advgetopt::getopt::process_help_string ( char const help) const

This function goes through the help string and replaces the %\<flag> with various content available in the getopt object.

This is helpful for various reasons. For example, you may use the same set of options in several different programs, in which case the p is likely useful to print out the name of the program currently in use.

Similarly we offer ways to print out lists of configuration files, the environment variable name & value, etc. The following is the list of supported flags:

  • "%%" – print out a percent
  • "%a" – print out the project name (a.k.a. application name)
  • "%b" – print out the build date
  • "%c" – print out the copyright notice
  • "%d" – print out the first directory with configuration files.
  • "%*d" – print out the complete list of directories with configuration files.
  • "%e" – print out the name of the environment variable.
  • "%*e" – print out the name and value of the environment variable.
  • "%f" – print out the first configuration path and filename.
  • "%*f" – print out all the configuration full paths.
  • "%g" – print out the list of existing configuration files.
  • "%*g" – print out the list of all possible configuration files.
  • "%i" – print out the directory to option files.
  • "%l" – print out the license.
  • "%o" – show the configuration filename where changes get written.
  • "%p" – print out the program basename.
  • "%*p" – print out the full program name.
  • "%s" – print out the group name.
  • "%t" – print out the build time.
  • "%v" – print out the version.
  • "%w" – print out the list of all the writable configuration files.

Here is an example where the p can be used:

"Usage: %p [-opt] filename ..."

The other flags are more often used in places like the copyright notice the footer, the license notice, etc.

Parameters
[in]helpA string that may include % flags.
Returns
The string with any '%<flag>' replaced.
See also
parse_program_name()

Definition at line 592 of file advgetopt_usage.cpp.

References advgetopt::options_environment::f_build_date, advgetopt::options_environment::f_build_time, advgetopt::options_environment::f_configuration_directories, advgetopt::options_environment::f_configuration_files, advgetopt::options_environment::f_copyright, advgetopt::options_environment::f_environment_variable_intro, advgetopt::options_environment::f_environment_variable_name, advgetopt::options_environment::f_group_name, advgetopt::options_environment::f_license, f_options_environment, f_program_fullname, f_program_name, advgetopt::options_environment::f_project_name, advgetopt::options_environment::f_section_variables_name, advgetopt::options_environment::f_version, advgetopt::usage_flag_traits::FORMAT_FLAG_EXTENDED, get_configuration_filenames(), get_options_filename(), and get_output_filename().

Referenced by usage().

◆ process_system_options()

flag_t advgetopt::getopt::process_system_options ( std::basic_ostream< char > &  out)

If you have the GETOPT_ENVIRONMENT_FLAG_SYSTEM_PARAMETERS flag turned on, then several options are automatically added to your list of supported options, such as --version.

This function processes these options if any were used by the client.

If the function finds one or more system flags as being defined, it returns a non-zero set of SYSTEM_OPTION_... flags. This can be useful to decide whether to continue processing or not.

We define a set of flags that can help you decide whether to continue or exit. In most cases, we propose that you exit your program if any one of the options was a command. This is done like so:

{
exit(1);
}
flag_t process_system_options(std::basic_ostream< char > &out)
Process the system options.
std::uint32_t flag_t
Definition flags.h:41
constexpr flag_t SYSTEM_OPTION_COMMANDS_MASK
Definition advgetopt.h:71

You may still want to continue, though, if other flags where set, even if some commands were used. For example, some tools will print their version and move forward with there work (i.e. compilers often do that to help with logging all the information about a build process, including the version of the compiler.)

Parameters
[in]outThe stream where output is sent if required.
Returns
non-zero set of flags if any of the system parameters were processed.

Definition at line 640 of file advgetopt_data.cpp.

References advgetopt::options_environment::f_build_date, advgetopt::options_environment::f_build_time, advgetopt::options_environment::f_copyright, advgetopt::options_environment::f_environment_variable_name, advgetopt::options_environment::f_groups, advgetopt::options_environment::f_license, f_options_environment, advgetopt::options_environment::f_options_files_directory, advgetopt::options_environment::f_project_name, advgetopt::options_environment::f_version, get_configuration_filenames(), get_default(), get_string(), advgetopt::GETOPT_FLAG_GROUP_NONE, advgetopt::GETOPT_FLAG_SHOW_ALL, advgetopt::GETOPT_FLAG_SHOW_SYSTEM, has_default(), is_defined(), advgetopt::less(), LIBADVGETOPT_COMPILER_VERSION, advgetopt::sanitizer_details(), show_option_sources(), advgetopt::SYSTEM_OPTION_BUILD_DATE, advgetopt::SYSTEM_OPTION_CONFIG_DIR, advgetopt::SYSTEM_OPTION_CONFIGURATION_FILENAMES, advgetopt::SYSTEM_OPTION_COPYRIGHT, advgetopt::SYSTEM_OPTION_ENVIRONMENT_VARIABLE_NAME, advgetopt::SYSTEM_OPTION_HELP, advgetopt::SYSTEM_OPTION_LICENSE, advgetopt::SYSTEM_OPTION_NONE, advgetopt::SYSTEM_OPTION_PATH_TO_OPTION_DEFINITIONS, advgetopt::SYSTEM_OPTION_SHOW_OPTION_SOURCES, advgetopt::SYSTEM_OPTION_SHOW_OPTION_VALUE, advgetopt::SYSTEM_OPTION_VERSION, and usage().

Referenced by finish_parsing().

◆ reset()

void advgetopt::getopt::reset ( )

This function goes through the list of options and mark them all as undefined. This is useful if you want to reuse a getopt object.

The effect is that all calls to is_defined() made afterward return false until new arguments get parsed.

Definition at line 82 of file advgetopt_options.cpp.

References f_options_by_name.

◆ set_short_name()

void advgetopt::getopt::set_short_name ( std::string const name,
short_name_t  short_name 
)

This function allows for dynamically assigning a short name to an option. This is useful for cases where a certain number of options may be added dynamically and may share the same short name or similar situation.

On our end we like to add -c as the short name of the --config-dir command line or environment variable option. However, some of our tools use -c for other reason (i.e. our cxpath tool uses -c for its --compile option.) So we do not want to have it as a default in --config-dir. Instead we assign it afterward if possible.

IMPORTANT: It is possible to change the short-name at any time. However, note that you can't have duplicates. It is also possible to remove a short-name by setting it to the advgetopt::NO_SHORT_NAME special value.

Note
This function requires you to make use of the constructor without the argc and argv parameters, add the short name, then run all the parsing.
Exceptions
getopt_exception_logicThe same short name cannot be used more than once. This exception is raised if it is discovered that another option already makes use of this short name. This exception is also raised if name does not reference an existing option.
Parameters
[in]nameThe name of the option which is to receive a short name.
[in]short_nameThe short name to assigned to the name option.

Definition at line 644 of file advgetopt_options.cpp.

References f_options_by_name, f_options_by_short_name, advgetopt::NO_SHORT_NAME, and advgetopt::short_name_to_string().

◆ show_option_sources()

void advgetopt::getopt::show_option_sources ( std::basic_ostream< char > &  out)
private

This function goes through the list of options by name ("alphabetically") and prints out the sources or "(undefined)" if not defined anywhere.

This function gets called when using the --show-option-sources system command line option at the time the process_system_options() function gets called.

Parameters
[in]outThe output streaming where the info is written.

Definition at line 706 of file advgetopt_options.cpp.

References f_options_by_name.

Referenced by process_system_options().

◆ size()

size_t advgetopt::getopt::size ( std::string const name) const

This function returns the number of arguments that were specified after the named option.

The function returns zero if the argument was never specified on the command line. If the option accepts exactly one parameter (i.e. not marked as a multiple arguments option: GETOPT_FLAG_MULTIPLE) then the function returns either zero (not specified) or one (specified at least once.)

Parameters
[in]nameThe name of the option to check.
Returns
The number of arguments specified on the command line or zero.

Definition at line 125 of file advgetopt_data.cpp.

References get_option(), and is_parsed().

Referenced by get_managed_configuration_filenames().

◆ split_environment()

string_list_t advgetopt::getopt::split_environment ( std::string const environment)
static

This function is used to transform a string to an array of arguments that can then be used with the parse_arguments() function.

For example, it is used to parse the environment variable string.

Note
The input string may include quotes. These will be removed. There is currently no support for the backslash character.
Parameters
[in]environmentThe string to be split in arguments.
Returns
An array of strings.

Definition at line 936 of file advgetopt.cpp.

References advgetopt::quote().

Referenced by get_managed_configuration_filenames(), and parse_string().

◆ usage()

std::string advgetopt::getopt::usage ( flag_t  show = GETOPT_FLAG_SHOW_MOST) const

This function assembles the command line arguments in a string and returns that string.

The function has the ability to wrap strings around for better formatting.

The list of arguments to show is defined by the show parameter. When show is 0, then only the regular and error arguments are shown. Otherwise only the argumenst with the specified flags are show. Only the ..._SHOW_... flags are valid here.

When an error occurs, it is customary to set show to GETOPT_FLAG_SHOW_USAGE_ON_ERROR so only a limited set of arguments are shown.

The library offers two groups in case you have a command line tools with a large number of options, those two can be used to only show those specific set of options with using a specific --help argument.

Note
This function does NOT print anything in the output. This is your responsibility. We do it this way because you may be using a logger and not want to print the usage in the wrong destination.
Bug:
The options are written from our map. This means the order will be alphabetical and not the order in which you defined the options. We are not looking into fixing this problem. That's just something you want to keep in mind.
Parameters
[in]showSelection of the options to show.
Returns
The assembled command line arguments.

Definition at line 237 of file advgetopt_usage.cpp.

References advgetopt::breakup_line(), advgetopt::group_description::f_description, advgetopt::options_environment::f_environment_variable_intro, advgetopt::options_environment::f_groups, advgetopt::options_environment::f_help_footer, advgetopt::options_environment::f_help_header, f_options_by_name, f_options_environment, find_group(), advgetopt::format_usage_string(), advgetopt::get_screen_width(), advgetopt::GETOPT_FLAG_ALIAS, advgetopt::GETOPT_FLAG_DYNAMIC_CONFIGURATION, advgetopt::GETOPT_FLAG_FLAG, advgetopt::GETOPT_FLAG_GROUP_MASK, advgetopt::GETOPT_FLAG_GROUP_MAXIMUM, advgetopt::GETOPT_FLAG_GROUP_MINIMUM, advgetopt::GETOPT_FLAG_GROUP_NONE, advgetopt::GETOPT_FLAG_GROUP_SHIFT, advgetopt::GETOPT_FLAG_MULTIPLE, advgetopt::GETOPT_FLAG_REQUIRED, advgetopt::GETOPT_FLAG_SHOW_ALL, advgetopt::GETOPT_FLAG_SHOW_GROUP1, advgetopt::GETOPT_FLAG_SHOW_GROUP2, advgetopt::GETOPT_FLAG_SHOW_SYSTEM, advgetopt::GETOPT_FLAG_SHOW_USAGE_ON_ERROR, advgetopt::NO_SHORT_NAME, process_help_string(), and advgetopt::short_name_to_string().

Referenced by process_system_options().

Member Data Documentation

◆ f_default_option

option_info::pointer_t advgetopt::getopt::f_default_option = option_info::pointer_t()
private

Definition at line 227 of file advgetopt.h.

Referenced by add_option(), get_option(), and parse_arguments().

◆ f_environment_variable

std::string advgetopt::getopt::f_environment_variable = std::string()
private

◆ f_options_by_name

option_info::map_by_name_t advgetopt::getopt::f_options_by_name = option_info::map_by_name_t()
private

◆ f_options_by_short_name

option_info::map_by_short_name_t advgetopt::getopt::f_options_by_short_name = option_info::map_by_short_name_t()
private

◆ f_options_environment

options_environment advgetopt::getopt::f_options_environment = options_environment()
private

◆ f_parsed

bool advgetopt::getopt::f_parsed = false
private

◆ f_program_fullname

std::string advgetopt::getopt::f_program_fullname = std::string()
private

◆ f_program_name

std::string advgetopt::getopt::f_program_name = std::string()
private

Definition at line 222 of file advgetopt.h.

Referenced by get_program_name(), parse_program_name(), and process_help_string().

◆ f_variables

variables::pointer_t advgetopt::getopt::f_variables = variables::pointer_t()
private

The documentation for this class was generated from the following files:

This document is part of the Snap! Websites Project.

Copyright by Made to Order Software Corp.