ProgramOptions Class Reference

Class ProgramOptions represents the command line options and environment passed to a program by the operating system. A ProgramOptions object can be viewed as a map of environment variables as well as a list of non-option command parameters, and finally a map of options and their parameters. More...

#include <options.h>

Collaboration diagram for ProgramOptions:
Collaboration graph
[legend]

List of all members.

Classes

class  Descriptor
 The description of a single option's type -- not its values, for that see ProgramOptions::Option. More...
class  Descriptors
 A collection of Descriptor's of options. This is a thin wrapper around a vector<Descriptor> Its main purpose is to define the add_option method so that the interface to array of descriptors becomes simpler to use. More...
class  EnvVar
 An EnvVar object exists to provide information about environment variables stored in the map of environment variables without having the user know about the implementation. Here is how an EnvVar is used: More...
class  Option
 Interface to a given option. See documentation for it in the ProgramOptions class. More...

Public Types

enum  allowed_parms_ {
  no_values,
  one_value,
  many_values
}
 

Symbolic names for the parms parameters for add_options and Descriptors::Descriptors().

More...
typedef std::map< string, stringEnvironment
 fast access to program env.
typedef std::vector< stringoption_values
 storage type for option values
typedef std::map< string,
Option * > 
Options
typedef std::string string
typedef
option_values::const_iterator 
value_iterator
 iterator for option values

Public Member Functions

Optionadd_option (string const &name)
 Create a new option with no values in it. That is, it pretends that an option was set in the argv passed in at construction time. This kind of option does not need to appear in the option descriptors used at construction time.
bool error () const
 Indicates that an error occurred while processing the options. Unless you construct the options with the exit_on_error parameter set to false, this function will never return anything but false.
string const & error_text () const
 Returns the text of the error message, if any, corresponding to the error that occured when parsing the options. This will never return a non-zero string unless you construct the options with exit_on_error=false.
std::string expand (std::string const &) const
 Return a copy of the input string with environment variable references expanded. An environment variable reference is a substring of the form '$name' where the name can take either of the following forms:
Environment const & get_environment () const
 Get the actual environment so the user can iterate over the variable, not just check them out, one by one. Rarely done, but useful in testing.
Options const & get_options () const
 Get a list of the options that are set so that you can iterate over it in some way -- mainly for testing.
EnvVar getenv (string const &name) const
 Get an environment variable given its name. EnvVar is a wrapper class that lets you tell whether or not the variable is set or not as well as get its values. See ProgramOptions::EnvVar for details of using the return value.
Option const & option (string const &name) const
 Remove an option and its values.
 ProgramOptions ()
 ProgramOptions (std::string option_descriptor_string, int argc, char const *const *argvp, char const *const *environ, bool exit_on_error=true)
 Construct program options and an environment from those passed in by the operating system. See the class comments for details of using this constructor. This constructor.
 ProgramOptions (Descriptors const &desc, int argc, char const *const *argvp, char const *const *environ, bool exit_on_error=true)
void remove_option (string const &name)
void setenv (string const &name, string const &value)
 Set a new value in the evironment or change an old one. Note that this does not update the real program environment. That getenv() won't get you the value you just set.
 ~ProgramOptions ()
 destroys the options map and everything else

Public Attributes

option_values argv
 non-option args are public arg0 is program name as usual

Static Public Attributes

static ProgramOptionsglobal_options_ = 0
 list of options and their values if any. The map key points to the string name_ field in the Option object.

Private Member Functions

void constructor (Descriptors const &desc, int argc, char const *const *argv, char const *const *environ, bool exit_on_error=true)
 constructor() is the 'real' constructor. It is a separate function so that it can be called as a function by the constructor that takes a character string defining the descriptors.
Optionget_option (string const &)
 get a writeable pointer to the named option.

Private Attributes

Environment environ_
 map of environment variables
string errmsg_
 return by error_text (text parsing options error)
bool error_
 error occurred while parsing options
bool exit_on_error_
 flag saying user wants control of error handling
Options options_
 list of options and their values if any. The map key points to the string name_ field in the Option object.

Static Private Attributes

static Option null_option_
 static option which indicates that it isn't set.

Detailed Description

Class ProgramOptions represents the command line options and environment passed to a program by the operating system. A ProgramOptions object can be viewed as a map of environment variables as well as a list of non-option command parameters, and finally a map of options and their parameters.

While it is possible to have more than one ProgramOptions active at any one time, in general the use of this class is to represent _the_ program options. Thus there is a global variable holding this single program options declared by this header. See ProgramOptions::global_options below. If this pointer is null, then no options are set.

For example, if a program is invoked in the following way:

       program -h -I. -I .. -I ../.. -stuff file file2 file3 ...

The ProgramOptions are described like this:

And of course the environment comes in 'behind' the command line, as it were.

Once constructed, a ProgramOptions object provides the following members:

Note that there is no connection between a ProgramOptions object's copy of the program environment and the real program environment -- except that one is copied from the other at the time of construction.

Here is an example of constructing and using a ProgramOptions object:

       int main(int argc, char **argv, char **environ)
       {
    
         // Parse the command line options and arguments and environment --
         // AND store the arguments in the default GLOBAL place so that
         // all parts of the program can have access to them.
    
         ProgramOptions::global_options_ = new ProgramOptions("-x,-y,-z",
                                                              argc,
                                                              argv,
                                                              environ);
    
         ProgramOptions &op = *ProgramOptions::global_options_;  
           // a local variable to make the accesses easier to understand
    
         // Use the parsed options and arguments
    
         if( op.option("-x") )  // operator int() tells you if option is set
          {
             string s = op.option("-x").value(); 
              // operator string() converts value to string but some compilers
              // this is buggy, so use .value()
          }
    
         // here is the easy to check for environment variables and to set them
    
         if( op.getenv("PATH") )
         {
             string path = op.getenv("PATH");  // string conversion
         }
         else
         {
             op.setenv("PATH", "stuff");
         }
    
         // Here's how you access non-option arguments
    
         for(int i=0; i < op.argv.size(); ++i)
           cout << op.argv[i] << endl;
    
         // Here's how you iterate over all environment items
    
         ProgramOptions::environment const& env = op.get_environment();
    
         ProgramOptions::environment::const_iterator f = env.begin();
         ProgramOptions::environment::const_iterator l = env.end();
    
         while(f != l)
         {
            cout << f->first << "=" << f->second << endl;
            ++f;
         }
       }

The 'value' of an option is an array of string objects. Even if there is no value, or if there is only 1 allowed value, an option is stored as an array of strings. Thus you can iterate over the values in an option using the same algorithm -- regardless of the kind of option it is. The option member, operator string(), converts all the values into a comma separated string and returns that. You can iterate over the individual values of an option like this:

       ProgramOptions::value_iterator first = op.option("-x").begin();
       ProgramOptions::value_iterator last  = op.option("-x").end();
    
       while(first != last)
       {
         string v = *first++;
       }

Note, if the double lookup of op.option("-x") bothers you, do this

       ProgramOptions::Option const& option = op.option("-x");
       ProgramOptions::value_iterator first = option.begin();
       ProgramOptions::value_iterator last  = option.end();
       ...

Note: if an option does not take values, then it is viewed as a boolean flag. If the user supplies it multiple times on the command line, the value will be toggled with each use.

When one character options take values, these values can be supplied as part of the option -- as occurs with the -I option to compilers, but multiple character option names must be separated from their values:

       -I../../junk.h    // works
       -stuff../file.h   // wrong will not be recognized.

When constructing an options object, you may optionally choose to instruct it not to print an error to stdout and exit if any options are not recognized -- as is the default behaviour. If you choose this mode of operation, use ProgramOptions::error() to determine if an error in processing the options has occurred. It should return false to indicate that no error occurred. If it returns true, use ProgramOptions::error_text() to find out what the error is.

When constructing ProgramsOptions and supplying a description of the options as a string, use the following constructor syntax:

       ProgramOptions op(option_declaration_string,
                         argc, argv, environment,
                         fail_on_error_flag);

Note that the fail_on_error_flag is optional and defaults to true;

When definiting an options object and passing it a string describing the options, rather than array of descriptors, the string must conform to the following:

       The string is a collection of parameter names followed by
       terminator that indicate the number parameters for the option.
       A ":" means 1 parameter, a ";" means multiple parameters, and a ","
       means no parameters.  For example:
    
         "-a,-queue,-bee:-c;-d"
    
       Means:
    
          Accept an option 'a' that takes no arguments
          accept an option 'queue' that takes no arguments
          accept an option, 'bee', that takes 1 argument
          accept an option, 'c', that takes multiple arguments
            (meaning that you can use it multiple times an suply a
             new option on each use)
          accept an option 'd' that takes no arguments.

Here's how to process options which allow multiple values to be set:

      if(options.option("-I"))
      {
        ProgramOptions::value_iterator f, l;
    
        f = options.option("-I").begin();
        l = options.option("-I").end();
    
        while(f !=l)
        {
          useString(*f);
          ++f;
        }
    
    
      }

Definition at line 45 of file options.h.


Member Typedef Documentation

typedef std::map<string,string> Environment

fast access to program env.

Definition at line 263 of file options.h.

typedef std::vector<string> option_values

storage type for option values

Definition at line 261 of file options.h.

typedef std::map<string, Option*> Options

Definition at line 265 of file options.h.

typedef std::string string

Definition at line 257 of file options.h.

iterator for option values

Definition at line 262 of file options.h.


Member Enumeration Documentation

Symbolic names for the parms parameters for add_options and Descriptors::Descriptors().

Enumerator:
no_values 

This is a boolean option.

one_value 

This option takes exactly one value.

many_values 

This option can be used multiple time and each < use requires a value.

Definition at line 275 of file options.h.


Constructor & Destructor Documentation

ProgramOptions ( Descriptors const &  desc,
int  argc,
char const *const *  argvp,
char const *const *  environ,
bool  exit_on_error = true 
)

Construct program options and an environment from those passed in by the operating system. See the class comments for details of using this constructor. This constructor requires that you supply a vector of descriptors. The next constructor accepts a character string describing the options.

Definition at line 292 of file options.h.

Here is the call graph for this function:

ProgramOptions ( std::string  option_descriptor_string,
int  argc,
char const *const *  argvp,
char const *const *  environ,
bool  exit_on_error = true 
)

Construct program options and an environment from those passed in by the operating system. See the class comments for details of using this constructor. This constructor.

Definition at line 420 of file options.cxx.

Here is the call graph for this function:

ProgramOptions (  ) 

Default constructor in case you need to make the options from scratch.

Definition at line 324 of file options.h.

~ProgramOptions (  ) 

destroys the options map and everything else

Definition at line 300 of file options.cxx.


Member Function Documentation

ProgramOptions::Option & add_option ( string const &  name  ) 

Create a new option with no values in it. That is, it pretends that an option was set in the argv passed in at construction time. This kind of option does not need to appear in the option descriptors used at construction time.

Definition at line 259 of file options.cxx.

Here is the caller graph for this function:

void constructor ( Descriptors const &  desc,
int  argc,
char const *const *  argv,
char const *const *  environ,
bool  exit_on_error = true 
) [private]

constructor() is the 'real' constructor. It is a separate function so that it can be called as a function by the constructor that takes a character string defining the descriptors.

Definition at line 50 of file options.cxx.

Here is the call graph for this function:

Here is the caller graph for this function:

bool error (  )  const

Indicates that an error occurred while processing the options. Unless you construct the options with the exit_on_error parameter set to false, this function will never return anything but false.

Definition at line 352 of file options.h.

string const& error_text (  )  const

Returns the text of the error message, if any, corresponding to the error that occured when parsing the options. This will never return a non-zero string unless you construct the options with exit_on_error=false.

Definition at line 358 of file options.h.

string expand ( std::string const &  in  )  const

Return a copy of the input string with environment variable references expanded. An environment variable reference is a substring of the form '$name' where the name can take either of the following forms:

        
              $[0-9]                    -- command line parameter expansion
              $[a-zA-Z_][0-9a-zA-Z_]*   -- environment variable expansion

Here is an example expansion:

             static char *args[]= { "zero", "one", "two", 0 };
         
             options.setenv("fred", "freddy boy");
         
             std::string rv = options.expand("$1-$fred-");

After expansion, rv will contain "one-freddy boy-".

Obviously, only the first 9 program parameters can be included in expansions of this form. This restriction is kept in order to be consistent with the behavior of most shell interpreters.

Definition at line 484 of file options.cxx.

Here is the call graph for this function:

Environment const& get_environment (  )  const

Get the actual environment so the user can iterate over the variable, not just check them out, one by one. Rarely done, but useful in testing.

Definition at line 378 of file options.h.

ProgramOptions::Option * get_option ( string const &  name  )  [private]

get a writeable pointer to the named option.

Definition at line 378 of file options.cxx.

Here is the caller graph for this function:

Options const& get_options (  )  const

Get a list of the options that are set so that you can iterate over it in some way -- mainly for testing.

Definition at line 384 of file options.h.

ProgramOptions::EnvVar getenv ( string const &  name  )  const

Get an environment variable given its name. EnvVar is a wrapper class that lets you tell whether or not the variable is set or not as well as get its values. See ProgramOptions::EnvVar for details of using the return value.

Definition at line 286 of file options.cxx.

Here is the caller graph for this function:

ProgramOptions::Option const & option ( string const &  name  )  const

Remove an option and its values.

Find the option or return a reference a static option that will tell you that it doesn't exist.

Definition at line 405 of file options.cxx.

Here is the call graph for this function:

Here is the caller graph for this function:

void remove_option ( string const &  name  ) 

Definition at line 390 of file options.cxx.

Here is the caller graph for this function:

void setenv ( string const &  name,
string const &  value 
)

Set a new value in the evironment or change an old one. Note that this does not update the real program environment. That getenv() won't get you the value you just set.

Definition at line 279 of file options.cxx.

Here is the caller graph for this function:


Member Data Documentation

non-option args are public arg0 is program name as usual

Definition at line 287 of file options.h.

Environment environ_ [private]

map of environment variables

Definition at line 574 of file options.h.

string errmsg_ [private]

return by error_text (text parsing options error)

Definition at line 571 of file options.h.

bool error_ [private]

error occurred while parsing options

Definition at line 572 of file options.h.

bool exit_on_error_ [private]

flag saying user wants control of error handling

Definition at line 570 of file options.h.

list of options and their values if any. The map key points to the string name_ field in the Option object.

_the_ program's options

Definition at line 273 of file options.h.

static option which indicates that it isn't set.

Definition at line 563 of file options.h.

Options options_ [private]

list of options and their values if any. The map key points to the string name_ field in the Option object.

Definition at line 565 of file options.h.


The documentation for this class was generated from the following files:
Generated on Wed Feb 29 22:56:11 2012 for CXXUtilities by  doxygen 1.6.3