OBT::OptionArgHandler Class Reference

This class handles all the options to parse a command line. More...

#include <OBTOptionArgHandler.h>

Collaboration diagram for OBT::OptionArgHandler:
[legend]

List of all members.

Public Member Functions

virtual ~OptionArgHandler ()
 Destructor.
int parse (int argc, char *argv[], bool showUsageAndExit=true, int firstArg=1)
 Parse the command line.
int parse (const std::vector< std::string > &args, bool showUsageAndExit=true, int firstArg=1)
 Parse the command line.
int parse (const std::string &args, bool showUsageAndExit=true, int firstArg=1)
 Parse the command line.
int parseFile (const char *file, bool showUsageAndExit=true)
 Parse the command line.
void reset ()
 Reset the options.
void showUsage (bool quit=true) const
 Show usage then exits if argument set to true.

Static Public Member Functions

static OptionArgHandlerget ()
 Returns the last created handler.

Protected Member Functions

 OptionArgHandler ()
 Protected constructor for children.
virtual void usage () const
 Outputs the usage.

Protected Attributes

std::vector< std::string > _args
 The arguments of the command line.
std::size_t _argIterator
 Current position to parse.
ListArg _optionList
 The arguments parsers.

Static Protected Attributes

static OptionArgHandler_currentHandler = 0
 The current handler.

Private Member Functions

void addOp (ArgsOp *op)
void addOp (OptionArg &o)

Private Attributes

ArgsOpList _argOpList

Friends

class ArgsOp
class OptionArg
class OtherOptionArg
operator to build rules.



OBT_API OptionArgHandleroperator< (OptionArg &o1, OptionArg &o2)
 The next option cannot be used if the previous one is not present.
OBT_API OptionArgHandleroperator< (OptionArgHandler &h, OptionArg &o)
OBT_API OptionArgHandleroperator^ (OptionArg &o1, OptionArg &o2)
 The two options are exclusives.
OBT_API OptionArgHandleroperator^ (OptionArgHandler &h, OptionArg &o)
OBT_API OptionArgHandleroperator& (OptionArg &o1, OptionArg &o2)
 Both options must be present or not.
OBT_API OptionArgHandleroperator& (OptionArgHandler &h, OptionArg &o)
OBT_API OptionArgHandleroperator| (OptionArg &o1, OptionArg &o2)
 At least one of the options must be present.
OBT_API OptionArgHandleroperator| (OptionArgHandler &h, OptionArg &o)

Detailed Description

This class handles all the options to parse a command line.

Author:
BenoƮt Chanclou
Example of use
To use it first, if you need to improve the usage message, create your own OptionArgHandler class.
class MyOptionArgHandler : public OBT::OptionArgHandler
{
public:
  MyOptionArgHandler() {}
  virtual ~MyOptionArgHandler() {}
protected:
  void usage() const
  {
    std::cerr << std::endl
              << "my application" << std::endl
              << "usage:  ..." << std::endl
              << std::endl ;
    OBT::OptionArgHandler::usage() ;
    std::cerr << "example:" << std::endl
              << _args[ 0 ] << " ..." << std::endl
              << _args[ 0 ] << " -cfg cmdLine.cfg" << std::endl ;
  }
} ;
Create the instance, add options, then parse the command line.
// The handler
MyOptionArgHandler args ;
// The options
OBT::OptionNPrm cfgOpt( "-cfg", "argument are in the file", "<file>", 1 ) ;
OBT::OptionNPrm socketOpt( "-socket", "the socket number", "<socket>", 1 ) ;
OBT::OptionNPrm ipOpt( "-o", "the ip adress", "<ip adress>", 1 ) ;
OBT::OptionNPrm outputOpt( "-o", "the output file", "<outup file>", 1 ) ;
OBT::OptionFlag traceOpt( "-trace", "this option activate the trace mode" ) ;
OBT::OptionNPrm traceFileOpt( "-traceFile", "the trace file", "<outup file>", 1 ) ;
// the rules
cfgOpt ^ OBT::OptionArg::other() ;
socketOpt & ipOpt ;
socketOpt | outputOpt ;
traceOpt < traceFileOpt ;
// Parsing (argc argv come form the main( argc, argv ) )
if( !args.parse( argc, argv ) )
{
  args.showUsage() ;
}
if( cfgOpt.isPresent() )
{
  args.reset() ;
  if( !args.parseFile( cfgOpt.getPrm().c_str() ) )
  {
    args.showUsage() ;
  }
}

Definition at line 84 of file OBTOptionArgHandler.h.


Constructor & Destructor Documentation

OptionArgHandler::OptionArgHandler (  )  [protected]

Protected constructor for children.

Definition at line 175 of file OBTOptionArgHandler.cpp.

References _currentHandler.

00176 : _args(),
00177   _argIterator( 0 ),
00178   _optionList()
00179 {
00180   _currentHandler = this ;
00181 }

OptionArgHandler::~OptionArgHandler (  )  [virtual]

Destructor.

Definition at line 183 of file OBTOptionArgHandler.cpp.

References _currentHandler, and _optionList.

00184 {
00185   _currentHandler = 0 ;
00186   for( ListArg::iterator i = _optionList.begin() ; i != _optionList.end() ; ++i )
00187   {
00188     (*i)->_handler = 0 ;
00189   }
00190 }


Member Function Documentation

void OptionArgHandler::addOp ( OptionArg o  )  [private]

Definition at line 162 of file OBTOptionArgHandler.cpp.

References _argOpList.

00163 {
00164   _argOpList.back()->_optionsList.push_back( &o ) ;
00165 }

void OptionArgHandler::addOp ( ArgsOp op  )  [private]

Definition at line 158 of file OBTOptionArgHandler.cpp.

References _argOpList.

00159 {
00160   _argOpList.push_back( op ) ;
00161 }

OptionArgHandler & OptionArgHandler::get (  )  [static]

Returns the last created handler.

The handler is not a real singleton, this static method is given for convenience.

Definition at line 169 of file OBTOptionArgHandler.cpp.

References _currentHandler, and OBT_ASSERT.

Referenced by OBT::OtherOptionArg::nbPresent().

00170 { 
00171   OBT_ASSERT( 0 != _currentHandler && "not initialised" ) ; 
00172   return *_currentHandler ; 
00173 }

int OptionArgHandler::parse ( const std::string &  args,
bool  showUsageAndExit = true,
int  firstArg = 1 
)

Parse the command line.

Parameters:
[in] args the arguments in a string, space is the separator, no other characters is allowed. This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 263 of file OBTOptionArgHandler.cpp.

References parse().

00264 {
00265   std::vector< std::string > args ;
00266   std::size_t length = argss.length() ;
00267   for( std::size_t posB = 0 ; posB < length ; )
00268   {
00269     bool quotedArg = ( argss[ posB ] == '"' ) ;
00270     posB += quotedArg ? 1 : 0 ; // the arg starts after the quote
00271     // try to locate the end of the arg
00272     std::size_t posE = argss.find( quotedArg ? '"' : ' ', posB ) ;
00273     if( std::string::npos == posE )
00274     { // End of arg not found => last arg
00275       args.push_back( argss.substr( posB ) ) ;
00276       break ;
00277     }
00278     std::string arg( argss.substr( posB, posE - posB ) ) ; // the arg
00279     if( !arg.empty() || quotedArg ) args.push_back( arg ) ; // no adding of empty arg except ""
00280     posB = ( quotedArg ? 1 : 0 ) + posE + 1 ; // one step forward due to the " and go to the begining of the next arg
00281   }
00282   return parse( args, showUsageAndExit, firstArg ) ;
00283 }

int OptionArgHandler::parse ( const std::vector< std::string > &  args,
bool  showUsageAndExit = true,
int  firstArg = 1 
)

Parse the command line.

Parameters:
[in] args the arguments in a vector This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 285 of file OBTOptionArgHandler.cpp.

References _argIterator, _argOpList, _args, _optionList, showUsage(), and OBT::ArgException::what().

00286 {
00287   _args = args ;
00288   int nbOptions = 0 ;
00289   try
00290   {
00291     for( _argIterator = firstArg ; _argIterator < _args.size() ; )
00292     {
00293       bool flagFound = false ;
00294       for( ListArg::iterator option = _optionList.begin() ;
00295            option != _optionList.end() && !flagFound ;
00296            option++ )
00297       {
00298         flagFound = ( *option )->tryArg() ;
00299       }
00300       if( flagFound )
00301       {
00302         nbOptions++ ;
00303       }
00304       else
00305       {
00306         std::stringstream error ;
00307         error << std::endl << "Unable to parse argument #" << _argIterator 
00308           << ":  unknow option \"" << _args[ _argIterator ] << "\"" << std::endl ;
00309         throw ArgException( error.str() ) ;
00310       }
00311     }
00312 
00313     for( ArgsOpList::const_iterator op = _argOpList.begin() ;
00314          op != _argOpList.end() ;
00315          op++ )
00316     {
00317       ( *op )->testValidity() ;
00318     }
00319   }
00320   catch( ArgException& error )
00321   { // Wrong arguments => usage => exit
00322     if( showUsageAndExit ) 
00323     { 
00324       std::cerr << error.what() ;
00325       showUsage() ;
00326     }
00327   }
00328   return nbOptions ;
00329 }

int OptionArgHandler::parse ( int  argc,
char *  argv[],
bool  showUsageAndExit = true,
int  firstArg = 1 
)

Parse the command line.

Parameters:
[in] argc the number of arguments
[in] argv the values of arguments
[in] showUsageAndExit this flag indicate how to handle errors, true show the usage then exits, false doesn't show the usage and doesn't exit, by default true.
[in] firstArg the index of the first argument, by default 1, most of the time the argument 0 is the name of the application. If it is not the case, set this value to 0 to start with the argument 0, or set it to N to skip the N first arguments.

Definition at line 253 of file OBTOptionArgHandler.cpp.

Referenced by parse(), and parseFile().

00254 {
00255   std::vector< std::string > args ;
00256   for( int i = 0 ; i < argc ; i++ )
00257   {
00258     args.push_back( std::string( argv[ i ] ) ) ;
00259   }
00260   return parse( args, showUsageAndExit, firstArg ) ;
00261 }

int OptionArgHandler::parseFile ( const char *  file,
bool  showUsageAndExit = true 
)

Parse the command line.

Parameters:
[in] file the file where are the arguments in a single line See parse( int, char*[], bool, int) "parse" method for details.

Definition at line 222 of file OBTOptionArgHandler.cpp.

References parse(), showUsage(), and OBT::ArgException::what().

00223 {
00224   std::string args ;
00225   try
00226   {
00227     std::ifstream cfg( file );
00228     if( !cfg.is_open() )
00229     {
00230       std::stringstream error ;
00231       error << std::endl << "Unable to open the file \"" << file << "\"" << std::endl ;
00232       throw ArgException( error.str() ) ;
00233     }
00234     std::getline( cfg, args ) ;
00235     if( !cfg.good() )
00236     {
00237       std::stringstream error ;
00238       error << std::endl << "Unable to read the file \"" << file << "\"" << std::endl ;
00239       throw ArgException( error.str() ) ;
00240     }
00241   }
00242   catch( ArgException& error )
00243   { // Wrong arguments => usage => exit
00244     if( showUsageAndExit ) 
00245     { 
00246       std::cerr << error.what() ;
00247       showUsage() ;
00248     }
00249   }
00250   return parse( args, showUsageAndExit, 0 ) ;
00251 }

void OptionArgHandler::reset (  ) 

Reset the options.

If you want to re-parse the command line, call this method.

Definition at line 192 of file OBTOptionArgHandler.cpp.

References _argIterator, _args, and _optionList.

00193 {
00194   _args.clear() ;
00195   _argIterator = 0 ;
00196   for( ListArg::iterator i = _optionList.begin() ; i != _optionList.end() ; ++i )
00197   {
00198     (*i)->reset() ;
00199   }
00200 }

void OBT::OptionArgHandler::showUsage ( bool  quit = true  )  const [inline]

Show usage then exits if argument set to true.

Definition at line 120 of file OBTOptionArgHandler.h.

Referenced by parse(), and parseFile().

00120 { usage() ; if( quit ) { exit( 1 ) ; } }

void OptionArgHandler::usage (  )  const [protected, virtual]

Outputs the usage.

If you want to improve the usage message you must overwrite this method in your own options handler.

Definition at line 202 of file OBTOptionArgHandler.cpp.

References _argOpList, and _optionList.

00203 {
00204   std::cerr << "options:" << std::endl ;
00205   for( ListArg::const_iterator option = _optionList.begin() ;
00206        option != _optionList.end() ;
00207        option++ )
00208   {
00209     std::cerr << ( *option )->getHelp() << std::endl ;
00210   }
00211   std::cerr << std::endl ;
00212 
00213   for( ArgsOpList::const_iterator op = _argOpList.begin() ;
00214        op != _argOpList.end() ;
00215        op++ )
00216   {
00217     ( *op )->usage() ;
00218   }
00219   std::cerr << std::endl ;
00220 }


Friends And Related Function Documentation

friend class ArgsOp [friend]

Definition at line 231 of file OBTOptionArgHandler.h.

OBT_API OptionArgHandler& operator& ( OptionArgHandler h,
OptionArg o 
) [friend]

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

OBT_API OptionArgHandler& operator& ( OptionArg o1,
OptionArg o2 
) [friend]

Both options must be present or not.

In the command

 -socket xxx -ip xxx

To retrieve such command arguments

 OptionNPrm socketOpt( "-socket", "the socket number", "<socket>", 1 ) ;
 OptionNPrm ipOpt( "-ip", "the ip adress", "<ip adress>", 1 ) ;
 // the rule: Both options must be present or not
 socketOpt & ipOpt ;

To get the parameters

 if( socketOpt.isPresent() )
 {
   assert( ipOpt.isPresent() ) ;
   DefineCommunication( ipOpt.getPrm(), socketOpt.getPrm() ) ;
   ...
 }
OBT_API OptionArgHandler& operator< ( OptionArgHandler h,
OptionArg o 
) [friend]

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

OBT_API OptionArgHandler& operator< ( OptionArg o1,
OptionArg o2 
) [friend]

The next option cannot be used if the previous one is not present.

In the command line

 -trace -traceFile out.log

To retrieve such command arguments

 OptionFlag traceOpt( "-trace", "this option activate the trace mode" ) ;
 OptionNPrm traceFileOpt( "-traceFile", "the trace file",
                          "<outup file>", 1 ) ;
 // the rule: if -traceFile is in the command line, -trace must be also defined
 traceOpt < traceFileOpt ;

To get the parameters

 if( traceOpt.isPresent() )
 { // -trace is in the command line
   activateTraces( true ) ;
   if( traceFileOpt.isPresent() )
   { // -traceFile is in the command line
     // Get the file name
     std::string fileName( traceFileOpt.getPrm() ) ;
     // Create the file
     ...
   }
 }
OBT_API OptionArgHandler& operator^ ( OptionArgHandler h,
OptionArg o 
) [friend]

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

OBT_API OptionArgHandler& operator^ ( OptionArg o1,
OptionArg o2 
) [friend]

The two options are exclusives.

In the command line these argument will fail

 -trace -optimized

To retrieve such command arguments

 OptionFlag traceOpt( "-trace", "this option activate the trace mode" ) ;
 OptionFlag optimizedOpt( "-optimized", "this option activate the optimized mode" ) ;
 // the rule: if -trace is in the command line, -optimized cannot be defined, and the opposite
 traceOpt ^ optimizedOpt ;

To get the parameters

 activateTraces( traceOpt.isPresent() ) ;
 activateOptimization( optimizedOpt.isPresent() ) ;
OBT_API OptionArgHandler& operator| ( OptionArgHandler h,
OptionArg o 
) [friend]

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

OBT_API OptionArgHandler& operator| ( OptionArg o1,
OptionArg o2 
) [friend]

At least one of the options must be present.

In the command

 -socket xxx -o fileName

To retrieve such command arguments

 OptionNPrm socketOpt( "-socket", "the socket number", "<socket>", 1 ) ;
 OptionNPrm outputOpt( "-o", "the output file", "<outup file>", 1 ) ;
 // the rule: At least one of the options must be present
 socketOpt | outputOpt ;

To get the parameters

 if( socketOpt.isPresent() ) defineSocket( socketOpt.getPrm() ) ;
 if( outputOpt.isPresent() )
 {
   openOutputFile( outputOpt.getPrm() ) ;
   ...
 }
friend class OptionArg [friend]

Definition at line 236 of file OBTOptionArgHandler.h.

friend class OtherOptionArg [friend]

Definition at line 237 of file OBTOptionArgHandler.h.


Member Data Documentation

std::size_t OBT::OptionArgHandler::_argIterator [protected]

Definition at line 234 of file OBTOptionArgHandler.h.

Referenced by addOp(), parse(), and usage().

std::vector< std::string > OBT::OptionArgHandler::_args [protected]

The arguments of the command line.

Definition at line 239 of file OBTOptionArgHandler.h.

Referenced by OBT::OptionArg::atLastArg(), OBT::OptionArg::getArg(), OBT::OptionArg::moveNextArg(), parse(), and reset().

The current handler.

Definition at line 245 of file OBTOptionArgHandler.h.

Referenced by get(), OptionArgHandler(), and ~OptionArgHandler().


Generated on 1 Jan 2010 for OBT by  doxygen 1.6.1