advgetopt: advgetopt::getopt Class Reference

advgetopt  2.0.1
Parse complex command line arguments and configuration files in C++.

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

#include <advgetopt.h>

Collaboration diagram for advgetopt::getopt:
Public Types typedef std::shared_ptr< getoptpointer_t   Public Member Functions  getopt (options_environment const &opts)  Initialize the getopt object. More...
   getopt (options_environment const &opts, int argc, char *argv[])  Initialize the getopt object. More...
  group_description const * find_group (flag_t group) const  Search for group in the list of group names. More...
  void finish_parsing (int argc, char *argv[])  Actually parse everything. More...
  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) const  Generate a list of configuration filenames. More...
  std::string get_default (std::string const &name) const  Get the default value for this option. More...
  std::string get_environment_variable_name () const   long get_long (std::string const &name, int idx=0, long min=std::numeric_limits< long >::min(), long max=std::numeric_limits< long >::max())  This function retrieves an argument as a long value. More...
  option_info::pointer_t get_option (std::string const &name, bool exact_option=false) const  Retrieve an option by name. More...
  option_info::pointer_t get_option (short_name_t name, bool exact_option=false) const  Get an option using its short name. More...
  option_info::map_by_name_t const & get_options () const  Retrieve the complete list of options. More...
  options_environment const & get_options_environment () const  Return a reference to the options environment. More...
  std::string get_program_fullname () const  Get the full name of the program. More...
  std::string get_program_name () const  Get the basename of the program. More...
  std::string get_project_name () const  Retrieve the project name if one is defined. More...
  std::string get_string (std::string const &name, int idx=0) const  Get the content of an option as a string. More...
  bool has_default (std::string const &name) const  Check whether an option has a default value. More...
  bool has_flag (flag_t flag) const  Check whether an environment flag is set or not. More...
  bool is_defined (std::string const &name) const  Check whether a parameter is defined. More...
  void link_aliases ()  Link options marked as a GETOPT_FLAG_ALIAS. More...
  std::string operator[] (std::string const &name) const  Retrieve the value of an argument. More...
  option_info_ref operator[] (std::string const &name)  Access a parameter in read and write mode. More...
  void parse_arguments (int argc, char *argv[], bool only_environment_variable=false)  Parse an array of arguments. More...
  void parse_configuration_files ()  This function checks for arguments in configuration files. More...
  void parse_environment_variable ()  Check for an environment variable. More...
  void parse_options_info (option const *opts, bool ignore_duplicates=false)  Parse the options to option_info objects. More...
  void parse_program_name (char *argv[])  Transform the argv[0] parameter in the program name. More...
  void parse_string (std::string const &str, bool only_environment_variable)  Parse a string similar to a command line argument. More...
  void process_configuration_file (std::string const &filename)  Parse one specific configuration file and process the results. More...
  std::string process_help_string (char const *help) const  Change the % flags in help strings. More...
  flag_t process_system_options (std::basic_ostream< char > &out)  Process the system options. More...
  void reset ()  Reset all the options. More...
  void set_short_name (std::string const &name, short_name_t short_name)  Assign a short name to an option. More...
  size_t size (std::string const &name) const  Retrieve the number of arguments. More...
  std::string usage (flag_t show=GETOPT_FLAG_SHOW_MOST) const  Create a string of the command line arguments. More...
  Static Public Member Functions static std::string breakup_line (std::string line, size_t const option_width, size_t const line_width)  Breakup a string on multiple lines. More...
  static std::string format_usage_string (std::string const &argument, std::string const &help, size_t const option_width, size_t const line_width)  Format a help string to make it fit on a given width. More...
  static size_t get_line_width ()  Retrieve the width of one line in your console. More...
  Private Member Functions void add_option_from_string (option_info::pointer_t opt, std::string const &value, std::string const &filename)  Add an option with a value string. More...
  void add_options (option_info::pointer_t opt, int &i, int argc, char **argv)  Read parameters of the current option. More...
  option_info::pointer_t get_alias_destination (option_info::pointer_t opt) const  Return the alias if there is one. More...
  void initialize_parser (options_environment const &opt_env)  Initialize the parser. More...
  void parse_options_from_file ()  Check for a file with option definitions. More...
  void parse_options_from_group_names ()  Transform group names in –<name>-help commands. More...
  Private Attributes option_info::pointer_t f_default_option = option_info::pointer_t()   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()   std::string f_program_fullname = std::string()   std::string f_program_name = std::string()   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 77 of file advgetopt.h.

Member Typedef Documentation
typedef std::shared_ptr<getopt> advgetopt::getopt::pointer_t

Definition at line 80 of file advgetopt.h.

Constructor & Destructor Documentation
advgetopt::getopt::getopt ( options_environment const &  opt_env)

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:


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)
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.


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_arguments(argc, argv);

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.

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.
[in]opt_envThe list of options that your program supports.
See also

Definition at line 465 of file advgetopt.cpp.

References initialize_parser().

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.

All the data gets copied while parsed. If the argv array is deleted on return, the getopt object remains valid.
getopt_exception_exitThis function calls finish_parsing() which may throw this exception. See that function for details.
[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

Definition at line 512 of file advgetopt.cpp.

References finish_parsing(), and initialize_parser().

Member Function Documentation
void advgetopt::getopt::add_option_from_string ( option_info::pointer_t  opt, std::string const &  value, std::string const &  filename  ) private

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 value if possible.

[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.

Definition at line 1291 of file advgetopt.cpp.

References advgetopt::end(), advgetopt::error, advgetopt::GETOPT_FLAG_MULTIPLE, advgetopt::GETOPT_FLAG_REQUIRED, and advgetopt::log.

Referenced by parse_arguments(), and process_configuration_file().

void advgetopt::getopt::add_options ( option_info::pointer_t  opt, int &  i, int  argc, char **  argv  ) 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.

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.
[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.

Definition at line 1232 of file advgetopt.cpp.

References advgetopt::end(), advgetopt::error, advgetopt::GETOPT_FLAG_FLAG, advgetopt::GETOPT_FLAG_MULTIPLE, advgetopt::GETOPT_FLAG_REQUIRED, advgetopt::anonymous_namespace{advgetopt.cpp}::is_arg(), and advgetopt::log.

Referenced by parse_arguments().

std::string advgetopt::getopt::breakup_line ( std::string  line, size_t const  option_width, size_t const  line_width  ) static

This function breaks up the specified line of text in one or more strings to fit your output.

The line_width represents the maximum number of characters that get printed in a row.

The option_width parameter is the number of characters in the left margin. When dealing with a very long argument, this width is 3 characters. When dealing with the help itself, it is expected to be around 30.

This function always makes sure that the resulting string ends with a newline character unless the input line string is empty.
[in]lineThe line to breakup. [in]option_widthThe number of characters in the left margin. [in]line_widthThe total number of characters in the output.
The broken up line as required.

Definition at line 815 of file advgetopt_usage.cpp.

Referenced by format_usage_string(), and usage().

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.

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

Definition at line 141 of file advgetopt_usage.cpp.

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

Referenced by usage().

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.

getopt_exception_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.
[in]argcThe number of arguments in argv. [in]argvAn array of strings representing arguments.

Definition at line 570 of file advgetopt.cpp.

References f_options_by_name, 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(), and advgetopt::SYSTEM_OPTION_COMMANDS_MASK.

Referenced by getopt().

std::string advgetopt::getopt::format_usage_string ( std::string const &  argument, std::string const &  help, size_t const  option_width, size_t const  line_width  ) static

This function properly wraps a set of help strings so they fit in your console. The width has to be given by you at the moment.

The function takes two strings, the argument with it's options and the actual help string for that argument. If the argument is short enough, it will appear on the first line with the first line of help. If not, then one whole line is reserved just for the argument and the help starts on the next line.

[in]argumentThe option name with – and arguments. [in]helpThe help string for this argument. [in]option_widthNumber of characters reserved for the option. [in]line_widthThe maximum number of characters to display in width.
A help string formatted for display.

Definition at line 746 of file advgetopt_usage.cpp.

References breakup_line().

Referenced by usage().

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.

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

Definition at line 1089 of file advgetopt.cpp.

References advgetopt::GETOPT_FLAG_ALIAS.

Referenced by get_option().

std::string advgetopt::getopt::get_configuration_filename ( int  idx) const
size_t advgetopt::getopt::get_configuration_filename_size ( ) const
string_list_t advgetopt::getopt::get_configuration_filenames ( bool  exists, bool  writable  ) 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.

[in]existsRemove files that do not exist from the list. [in]writableOnly return files we consider writable.
The list of configuration filenames.

Definition at line 78 of file advgetopt_config.cpp.

References advgetopt::options_environment::f_configuration_directories, advgetopt::options_environment::f_configuration_filename, advgetopt::options_environment::f_configuration_files, f_options_environment, advgetopt::options_environment::f_project_name, get_string(), advgetopt::GETOPT_ENVIRONMENT_FLAG_SYSTEM_PARAMETERS, advgetopt::handle_user_directory(), has_flag(), advgetopt::insert_project_name(), is_defined(), and size().

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

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.

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.
getopt_exception_undefinedThe getopt_exception_undefined exception is raised if this function is called with an empty name.
[in]nameThe name of the parameter of which you want to retrieve the default value.
The default value or an empty string if no value is defined.

Definition at line 189 of file advgetopt_data.cpp.

References get_option().

std::string advgetopt::getopt::get_environment_variable_name ( ) const
size_t advgetopt::getopt::get_line_width ( ) static

This function retrieves the width of the console in number of characters.

If the process is not connected to a TTY, then the function returns 80.

If the width is less than 40, the function returns 40.

The width of the console screen.

Definition at line 911 of file advgetopt_usage.cpp.

Referenced by usage().

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()  )

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
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.)

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.
[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).
The argument as a long.

Definition at line 249 of file advgetopt_data.cpp.

References advgetopt::end(), advgetopt::error, get_option(), and advgetopt::log.

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, whever 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, though.

[in]nameThe name of the option to retrieve. [in]exact_optionReturn the exact option, not its alias.
The pointer to the named option or nullptr if not found.

Definition at line 1142 of file advgetopt.cpp.

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

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

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.

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

Definition at line 1200 of file advgetopt.cpp.

References f_options_by_short_name, and get_alias_destination().

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.

The map of options indexed by name.
See also

Definition at line 1115 of file advgetopt.cpp.

References f_options_by_name.

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.

This getopt options environment.

Definition at line 608 of file advgetopt.cpp.

References f_options_environment.

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;
// the following probably require some const_cast<>(), but that's the idea
my_opts.reset(args.size(), &args[0], ...);
The contents of the argv[0] parameter as defined on construction.
See also

Definition at line 129 of file advgetopt_access.cpp.

References f_program_fullname.

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.

The basename of the program.
See also

Definition at line 147 of file advgetopt_access.cpp.

References f_program_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:

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

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


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:
# Second we read this file (assuming the same project name
# of "snapwebsites"):

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.

The name of the project, maybe empty if undefined.

Definition at line 197 of file advgetopt_access.cpp.

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

std::string advgetopt::getopt::get_string ( std::string const &  name, int  idx = 0  ) 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.

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.
[in]nameThe name of the option to read. [in]idxThe zero based index of a multi-argument command line option.
The option argument as a string.

Definition at line 332 of file advgetopt_data.cpp.

References get_option().

Referenced by get_configuration_filenames().

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.

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

Definition at line 149 of file advgetopt_data.cpp.

References get_option().

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.

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

Definition at line 626 of file advgetopt.cpp.

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

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

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.

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

Definition at line 533 of file advgetopt.cpp.

References advgetopt::options_environment::f_configuration_filename, advgetopt::options_environment::f_options, f_options_environment, advgetopt::anonymous_namespace{advgetopt.cpp}::g_if_configuration_filename_system_options, advgetopt::anonymous_namespace{advgetopt.cpp}::g_system_options, 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().

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")) ...

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")) ...
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.
[in]nameThe long name or short name of the option to check.
true if the option was defined in a configuration file, the environment variable, or the command line.

Definition at line 93 of file advgetopt_data.cpp.

References get_option().

Referenced by get_configuration_filenames(), and process_system_options().

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.

getopt_exception_invalidAll aliases must exist or this exception is raised.

Definition at line 365 of file advgetopt_options.cpp.

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

Referenced by finish_parsing().

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.

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

Definition at line 373 of file advgetopt_data.cpp.

References get_option().

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.

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().
If the option is an alias and the destination is not defined you can still get an exception raised.
[in]nameThe name of the option to access.
A reference to this option with support for many std::string like operators.

Definition at line 449 of file advgetopt_data.cpp.

References f_options_by_name, and get_option().

void advgetopt::getopt::parse_arguments ( int  argc, char *  argv[], 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.

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.
[in]argcThe number of arguments in argv. [in]argvThe argument strings terminated by a nullptr. [in]only_environment_variableAccept command line arguments (false) or environment variable arguments (true).

Definition at line 827 of file advgetopt.cpp.

References add_option_from_string(), add_options(), advgetopt::end(), advgetopt::error, f_default_option, get_option(), advgetopt::GETOPT_FLAG_COMMAND_LINE, advgetopt::GETOPT_FLAG_ENVIRONMENT_VARIABLE, advgetopt::log, and advgetopt::short_name_to_string().

Referenced by finish_parsing(), and parse_string().

void advgetopt::getopt::parse_configuration_files ( )

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.

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.
See also

Definition at line 226 of file advgetopt_config.cpp.

References get_configuration_filenames(), and process_configuration_file().

Referenced by finish_parsing().

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.

Definition at line 651 of file advgetopt.cpp.

References advgetopt::options_environment::f_environment_variable_name, f_options_environment, and parse_string().

Referenced by finish_parsing().

void advgetopt::getopt::parse_options_from_file ( ) private

This function tries to read a file of 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>.


default=<default value>
help=<help sentence>
validator=<validator name>[(<param>)]|/<regex>/<flags>
alias=<name of aliased option>

Definition at line 205 of file advgetopt_options.cpp.

References advgetopt::ASSIGNMENT_OPERATOR_EQUAL, advgetopt::COMMENT_INI, advgetopt::COMMENT_SHELL, f_options_by_name, f_options_by_short_name, f_options_environment, advgetopt::options_environment::f_options_files_directory, advgetopt::options_environment::f_project_name, advgetopt::conf_file::get_conf_file(), advgetopt::GETOPT_FLAG_ALIAS, advgetopt::GETOPT_FLAG_COMMAND_LINE, advgetopt::GETOPT_FLAG_CONFIGURATION_FILE, advgetopt::GETOPT_FLAG_ENVIRONMENT_VARIABLE, advgetopt::GETOPT_FLAG_FLAG, 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::split_string(), and advgetopt::unquote().

Referenced by initialize_parser().

void advgetopt::getopt::parse_options_from_group_names ( ) private
void advgetopt::getopt::parse_options_info ( option const *  opts, bool  ignore_duplicates = false  )
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.

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.
getopt_exception_logicIf you call this function with a null pointer, then it raises this exception.
[in]argvThe arguments vector.
See also

Definition at line 75 of file advgetopt_access.cpp.

References f_program_fullname, and f_program_name.

Referenced by finish_parsing().

void advgetopt::getopt::parse_string ( std::string const &  str, bool  only_environment_variable  )

This function parses a line of command line argument 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.)

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

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

Definition at line 694 of file advgetopt.cpp.

References f_program_fullname, and parse_arguments().

Referenced by parse_environment_variable().

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.

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.
Extend the support by having the various flags that the conf_file class supports appear in the list of configuration filenames.
[in]filenameThe name of the configuration file to check out.
See also

Definition at line 259 of file advgetopt_config.cpp.

References add_option_from_string(), advgetopt::CONFIGURATION_SECTIONS, advgetopt::end(), advgetopt::error, f_options_by_name, 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::conf_file_setup::is_valid(), and advgetopt::log.

Referenced by parse_configuration_files().

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.
  • "%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.

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

Definition at line 458 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_name, advgetopt::options_environment::f_license, f_options_environment, advgetopt::options_environment::f_options_files_directory, f_program_fullname, f_program_name, advgetopt::options_environment::f_project_name, advgetopt::options_environment::f_version, and get_configuration_filenames().

Referenced by usage().

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:

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.)

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

Definition at line 507 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::group_description::f_group, 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(), advgetopt::GETOPT_FLAG_GROUP_NONE, advgetopt::GETOPT_FLAG_SHOW_ALL, is_defined(), 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_VERSION, and usage().

Referenced by finish_parsing().

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 77 of file advgetopt_options.cpp.

References f_options_by_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 has a default in that option. Instead we assign it afterward.

IMPORTANT: To make this call useful, make sure to make it before you call the parse functions. Setting the short name after the parsing was done is going to be useless.

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.
The function calls the option_info::set_short_name() function which may raise an exception if the option already has a short name (or if you inadvertendly passed NO_SHORT_NAME.)
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 the name parameter does not reference an existing option.
[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 452 of file advgetopt_options.cpp.

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

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.)

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

Definition at line 120 of file advgetopt_data.cpp.

References get_option().

Referenced by get_configuration_filenames().

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.

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.
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.
[in]showSelection of the options to show.
The assembled command line arguments.

Definition at line 213 of file advgetopt_usage.cpp.

References breakup_line(), advgetopt::group_description::f_description, 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(), format_usage_string(), get_line_width(), advgetopt::GETOPT_FLAG_ALIAS, 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_USAGE_ON_ERROR, advgetopt::NO_SHORT_NAME, process_help_string(), and advgetopt::short_name_to_string().

Referenced by process_system_options().

Member Data Documentation
option_info::pointer_t advgetopt::getopt::f_default_option = option_info::pointer_t() private

Definition at line 180 of file advgetopt.h.

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

option_info::map_by_short_name_t advgetopt::getopt::f_options_by_short_name = option_info::map_by_short_name_t() private
std::string advgetopt::getopt::f_program_fullname = std::string() private
std::string advgetopt::getopt::f_program_name = std::string() private

Definition at line 175 of file advgetopt.h.

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

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.

Syndicate content

Snap! Websites
An Open Source CMS System in C++

Contact Us Directly