Evo C++ Library v0.5.1
Classes | Public Types | Public Member Functions | Static Public Attributes | List of all members
CommandLineT< ConsoleT > Class Template Reference

#include <evo/commandline.h>

Detailed Description

template<class ConsoleT = Console>
class evo::CommandLineT< ConsoleT >

Process command-line arguments.

Template Parameters
ConsoleTConsole type to use (used for testing, leave default)
Example

Here's a simple example:

using namespace evo;
const char* HELP = "Test program description for command-line argument parsing. Long lines will wrap automatically as needed.\n\
\nBullet list of things:\n\
- First thing\n\
- Second thing";
const char* EPILOG = "This is the epilog, which gives additional description and is shown last.";
int main(int argc, const char* argv[]) {
Console& c = con();
// Initialize with description and info
CommandLine cmdline(HELP);
cmdline.set_epilog(EPILOG);
cmdline.addver("Program version 1.0");
// Add options/arguments to support
cmdline.addflag("-f, --flag", "Flag option");
cmdline.addopt("-o, --opt", "Option with a value");
cmdline.addarg("file", "File to use").required().multi();
// Parse command-line, store results in args map
StrMapList args;
cmdline.parse(args, argc, argv);
// Show results
c.out << "Results:" << NL;
for (StrMapList::Iter iter(args); iter; ++iter)
c.out << ' ' << iter->key() << '=' << iter->value() << NL;
c.out << NL;
// Check if a flag is set using map contains()
if (args.contains("flag"))
c.out << "Flag is set" << NL;
// Get option value using lookupsub()
SubString value(lookupsub(args, "opt"));
if (!value.null())
c.out << "Opt: " << value << NL;
// Get argument value using lookupsub(), tokenize multiple values on ';'
StrTok tok(lookupsub(args, "file"));
while (tok.next(';'))
c.out << "File: " << tok.value() << NL;
return 0;
}

Output with: ./program -h

Usage: program [options] file...
Test program description for command-line argument parsing. Long lines will wrap automatically as
needed.
Bullet list of things:
- First thing
- Second thing
Options:
-f, --flag Flag option
-o, --opt <value> Option with a value
-h, --help Show this usage help
--help-general Show general argument processing help
--version Show version information
Arguments:
file File to use
This is the epilog, which gives additional description and is shown last.

Output with: ./program -f -o=val file1 file2

Results:
file=file1;file2
flag=1
opt=val
Flag is set
Opt: val
File: file1
File: file2

Classes

struct  Command
 Used to set command options and arguments. More...
 
struct  Option
 Used to set additional option/argument information. More...
 

Public Types

typedef ConsoleT::OutT OutT
 Output stream type. More...
 
typedef CommandLineT< ConsoleT > This
 This type. More...
 

Public Member Functions

 CommandLineT ()
 Default constructor. More...
 
 CommandLineT (const String &description)
 Constructor with help description. More...
 
Optionadd (const String &str)
 Parse input string and add an global option or argument as described. More...
 
Optionaddarg (const String &key, const String &helpname, const String &help)
 Add a positional argument. More...
 
Optionaddarg (const String &key, const String &help)
 Add a positional argument. More...
 
CommandInfo & addcmd (const String &name, const String &help)
 Add a sub-command argument with it's own options and arguments. More...
 
void addflag (const String &names, const String &key, const String &help)
 Add a global option flag. More...
 
void addflag (const String &names, const String &help)
 Add a global option flag. More...
 
Optionaddopt (const String &names, const String &key, const String &helpname, const String &help)
 Add a global option that stores a value. More...
 
Optionaddopt (const String &names, const String &helpname, const String &help)
 Add a global option that stores a value. More...
 
Optionaddopt (const String &names, const String &help)
 Add a global option that stores a value. More...
 
void addsep ()
 Add a global options separator in usage help. More...
 
Thisaddver (const String &version_info)
 Add version info and enable option flags to show it. More...
 
bool error () const
 Check whether an error occurred while parsing arguments. More...
 
ConsoleT & get_con ()
 Get reference to console object used. More...
 
const NewlineValueget_newline () const
 Get current newline value used for output. More...
 
template<class TMap >
bool parse (TMap &map, int argc, const char *argv[], int offset=0)
 Parse and process command-line using current option and argument info. More...
 
Thisset_epilog (const String &text)
 Set epilog text shown in usage help. More...
 
Thisset_maxline (uint maxline)
 Set new max line length for usage help output. More...
 
Thisset_newline (const NewlineValue &nl)
 Set current newline value used for output. More...
 
Thisset_noexit (bool val=true)
 Set no-exit flag to prevent parse() from terminating and instead have it return false. More...
 
Thisset_progname (const String &name)
 Set program name to use with usage help. More...
 
OutTshow_error ()
 This writes the beginning (prefix) of an error message and returns a stream for the caller to write the error message to. More...
 
OutTshow_warning ()
 This writes the beginning (prefix) of a warning message and returns a stream for the caller to write the warning message to. More...
 

Static Public Attributes

static const uint MAXLINE_DEFAULT = 100
 Default maxline value. More...
 

Member Typedef Documentation

◆ OutT

typedef ConsoleT::OutT OutT

Output stream type.

◆ This

typedef CommandLineT<ConsoleT> This

This type.

Constructor & Destructor Documentation

◆ CommandLineT() [1/2]

CommandLineT ( )
inline

Default constructor.

  • Usage help will not include a description

◆ CommandLineT() [2/2]

CommandLineT ( const String description)
inline

Constructor with help description.

  • The description is shown with usage help
Parameters
descriptionDesription to show with usage help

Member Function Documentation

◆ add()

Option& add ( const String str)
inline

Parse input string and add an global option or argument as described.

  • This calls addsep(), addflag(), addopt(), or addarg() depending on input
  • Use empty string to add an option separator
  • Option flag syntax: NAMES HELP
  • Option with value syntax: NAMES VALUE HELP
  • Argument syntax: NAME HELP
  • Where:
    • NAMES is a comma and/or space separated list of short or long option names (usually short first), the last of which is used as the option key (without dash or double dash prefix)
    • HELP is a help string for this option/argument (may contain newlines) – at least two spaces are required before this
    • VALUE is the name of the option value to show in usage help (also called helpname)
    • NAME is the argument name to show in usage help
Parameters
strInput string to parse

◆ addarg() [1/2]

Option& addarg ( const String key,
const String helpname,
const String help 
)
inline

Add a positional argument.

  • Multiple values for an argument are stored with a semicolon separator (i.e. they stack)
Parameters
keyKey to store option flag under when parsing arguments, example: outfile
helpnameName to represent argument value shown with usage help (usually in caps), example: OUTFILE
helpHelp string for this option to show with usage help, example: Output file to use
Returns
Option object for setting additonal information

◆ addarg() [2/2]

Option& addarg ( const String key,
const String help 
)
inline

Add a positional argument.

Parameters
keyKey to store option flag under when parsing arguments, example: outfile
helpHelp string for this option to show with usage help, example: Output file to use
Returns
Option object for setting additonal information

◆ addcmd()

CommandInfo& addcmd ( const String name,
const String help 
)
inline

Add a sub-command argument with it's own options and arguments.

  • Use the returned object to add options and arguments to this sub-command
Parameters
nameCommand name to add
helpShort help for command, shown in main usage help
Returns
Command object for setting additional information

◆ addflag() [1/2]

void addflag ( const String names,
const String key,
const String help 
)
inline

Add a global option flag.

  • When parsing repeated flags, the occurrences are counted and stored as a string value (if more than 1 occurrence)
  • Special option '-' (just a single dash) can be added here, this usually means read from stdin instead of a file
Parameters
namesOption names to look for when parsing arguments (comma separated)
keyKey to store option flag under when parsing arguments
helpHelp string for this option

◆ addflag() [2/2]

void addflag ( const String names,
const String help 
)
inline

Add a global option flag.

Parameters
namesOption names to look for when parsing arguments (comma separated)
helpHelp string for this option

◆ addopt() [1/3]

Option& addopt ( const String names,
const String key,
const String helpname,
const String help 
)
inline

Add a global option that stores a value.

  • Multiple values allowed for the same option are stored with a semicolon separator
  • When parsing repeated options, previous values for that option are overwritten by default
Parameters
namesOption names to look for when parsing arguments (comma separated), example: -v,–verbose
keyKey to store option flag under when parsing arguments, example: outfile
helpnameName to represent option value shown with usage help (usually in caps), example: OUTFILE
helpHelp string for this option to show with usage help, example: Output file to use
Returns
Option object for setting additonal information

◆ addopt() [2/3]

Option& addopt ( const String names,
const String helpname,
const String help 
)
inline

Add a global option that stores a value.

Parameters
namesOption names to look for when parsing arguments (comma separated), example: -v,–verbose
helpnameName to represent option value shown with usage help (usually in caps), example: OUTFILE
helpHelp string for this option to show with usage help, example: Output file to use
Returns
Option object for setting additonal information

◆ addopt() [3/3]

Option& addopt ( const String names,
const String help 
)
inline

Add a global option that stores a value.

Parameters
namesOption names to look for when parsing arguments (comma separated), example: -v,–verbose
helpHelp string for this option to show with usage help, example: Output file to use
Returns
Option object for setting additonal information

◆ addsep()

void addsep ( )
inline

Add a global options separator in usage help.

  • This adds a blank line before the next option in usage help
  • This is useful for visually grouping related options in usage help

◆ addver()

This& addver ( const String version_info)
inline

Add version info and enable option flags to show it.

Parameters
version_infoVersion info string to show with version flags (–version or -V), empty to disable these flags
Returns
This

◆ error()

bool error ( ) const
inline

Check whether an error occurred while parsing arguments.

  • This is true when something is wrong with a command-line argument
Returns
Whether an error occurrend

◆ get_con()

ConsoleT& get_con ( )
inline

Get reference to console object used.

Returns
Console reference

◆ get_newline()

const NewlineValue& get_newline ( ) const
inline

Get current newline value used for output.

Returns
Newline value used

◆ parse()

bool parse ( TMap &  map,
int  argc,
const char *  argv[],
int  offset = 0 
)
inline

Parse and process command-line using current option and argument info.

  • This writes error or help info to stderr (using Console)
  • This writes the parsed result values to map
  • If this returns false, call error() to determine whether to terminate with an error
Parameters
mapMap to write parsed options and arguments to
argcArgument count (from main())
argvArgument array (from main())
offsetOffset for starting argument (0 for first, 1 for second, etc)
Returns
Whether to continue, false to terminate due to an error or for showing help info

◆ set_epilog()

This& set_epilog ( const String text)
inline

Set epilog text shown in usage help.

  • This should include things like relevant environment variables and the software homepage
Parameters
textEpilog text
Returns
This

◆ set_maxline()

This& set_maxline ( uint  maxline)
inline

Set new max line length for usage help output.

Parameters
maxlineNew max line length, set to 40 if lower than 40
Returns
This

◆ set_newline()

This& set_newline ( const NewlineValue nl)
inline

Set current newline value used for output.

Parameters
nlNewline value to use
Returns
This

◆ set_noexit()

This& set_noexit ( bool  val = true)
inline

Set no-exit flag to prevent parse() from terminating and instead have it return false.

Parameters
valNo-exit flag to set, false to let parse() terminate
Returns
This

◆ set_progname()

This& set_progname ( const String name)
inline

Set program name to use with usage help.

  • If not set, then this is inferred from the first argument parsed
  • If set, you may need to pass offset=1 to parse to skip argv program name
Parameters
nameProgram name to use, ignored if empty
Returns
This

◆ show_error()

OutT& show_error ( )
inline

This writes the beginning (prefix) of an error message and returns a stream for the caller to write the error message to.

  • This sets up the error using formatting consistent with command-line parsing errors
  • Example:
    CommandLine cmdline;
    cmdline.show_error() << "An error occurred" << NL;
    exit(1);
Returns
Stream to write the desired error message, which should end with a newline (NL)

◆ show_warning()

OutT& show_warning ( )
inline

This writes the beginning (prefix) of a warning message and returns a stream for the caller to write the warning message to.

  • This sets up the warning using formatting consistent with command-line parsing errors
  • Example:
    CommandLine cmdline;
    cmdline.show_warning() << "This is a warning message" << NL;
Returns
Stream to write the desired warning message, which should end with a newline (NL)

Member Data Documentation

◆ MAXLINE_DEFAULT

const uint MAXLINE_DEFAULT = 100
static

Default maxline value.


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