nl:: ArgParser
Summary
Enumerations |
|
---|---|
OptionArgumentType
|
enum Defines the argument requirements for a command line option. |
Typedefs |
|
---|---|
NonOptionArgHandlerFunct)(const char *progName, int argc, char *argv[])
|
typedefbool(*
A function that can be called to handle any remaining, non-option command line arguments. |
OptionHandlerFunct)(const char *progName, OptionSet *optSet, int id, const char *name, const char *arg)
|
typedefbool(*
A function that can be called to handle a set of command line options. |
Variables |
|
---|---|
PrintArgError = DefaultPrintArgError)(const char *msg,...)
|
void(*
Pointer to function used to print errors that occur during argument parsing.
|
gActiveOptionSets = NULL
|
OptionSet **
The list of OptionSets passed to the currently active ParseArgs() call.
|
Functions |
|
---|---|
CountAllOptions(OptionSet *optSets[])
|
size_t
|
CountAllOptions(OptionSet **optSets)
|
size_t
|
CountOptionSets(OptionSet *optSets[])
|
size_t
|
CountOptionSets(OptionSet **optSets)
|
size_t
|
DefaultPrintArgError(const char *msg, ...)
|
void
Print an error message associated with argument parsing.
|
FindOptionById(OptionSet **optSets, int optId, OptionSet *& optSet, OptionDef *& optDef)
|
void
|
FindOptionByIndex(OptionSet **optSets, int optIndex, OptionSet *& optSet, OptionDef *& optDef)
|
void
|
GetNextArg(char *& parsePoint)
|
bool
|
IsShortOptionChar(int ch)
|
bool
|
MakeLongOptions(OptionSet **optSets)
|
struct option *
|
MakeShortOptions(OptionSet **optSets)
|
char *
|
MakeUniqueHelpGroupNamesList(OptionSet *optSets[])
|
const char **
|
ParseArgs(const char *progName, int argc, char *argv[], OptionSet *optSets[], NonOptionArgHandlerFunct nonOptArgHandler, bool ignoreUnknown)
|
bool
Parse a set of command line-style arguments, calling handling functions to process each option and non-option argument.
|
ParseArgs(const char *progName, int argc, char *argv[], OptionSet *optSets[], NonOptionArgHandlerFunct nonOptArgHandler)
|
bool
|
ParseArgs(const char *progName, int argc, char *argv[], OptionSet *optSets[])
|
bool
|
ParseArgsFromEnvVar(const char *progName, const char *varName, OptionSet *optSets[], NonOptionArgHandlerFunct nonOptArgHandler, bool ignoreUnknown)
|
bool
Parse a set of arguments from a named environment variable.
|
ParseArgsFromEnvVar(const char *progName, const char *varName, OptionSet *optSets[])
|
bool
|
ParseArgsFromEnvVar(const char *progName, const char *varName, OptionSet *optSets[], NonOptionArgHandlerFunct nonOptArgHandler)
|
bool
|
ParseArgsFromString(const char *progName, const char *argStr, OptionSet *optSets[], NonOptionArgHandlerFunct nonOptArgHandler, bool ignoreUnknown)
|
bool
Parse a set of arguments from a given string.
|
ParseArgsFromString(const char *progName, const char *argStr, OptionSet *optSets[], NonOptionArgHandlerFunct nonOptArgHandler)
|
bool
|
ParseArgsFromString(const char *progName, const char *argStr, OptionSet *optSets[])
|
bool
|
ParseBoolean(const char *str, bool & output)
|
bool
Parse a string as a boolean value.
|
ParseFabricId(const char *str, uint64_t & fabricId, bool allowReserved)
|
bool
Parse a Weave fabric id in text form.
|
ParseHexString(const char *hexStr, uint32_t strLen, uint8_t *outBuf, uint32_t outBufSize, uint32_t & outDataLen)
|
bool
Parse a string of bytes given in hex form.
|
ParseIPAddress(const char *str, IPAddress & output)
|
bool
Parse an IP address in text form.
|
ParseInt(const char *str, uint64_t & output, int base)
|
bool
Parse and attempt to convert a string to a 64-bit unsigned integer, applying the appropriate interpretation based on the base parameter.
|
ParseInt(const char *str, uint32_t & output, int base)
|
bool
Parse and attempt to convert a string to a 32-bit unsigned integer, applying the appropriate interpretation based on the base parameter.
|
ParseInt(const char *str, int32_t & output, int base)
|
bool
Parse and attempt to convert a string to a 32-bit signed integer, applying the appropriate interpretation based on the base parameter.
|
ParseInt(const char *str, uint64_t & output)
|
bool
Parse and attempt to convert a string interpreted as a decimal value to a 64-bit unsigned integer, applying the appropriate interpretation based on the base parameter.
|
ParseInt(const char *str, uint32_t & output)
|
bool
Parse and attempt to convert a string interpreted as a decimal value to a 32-bit unsigned integer, applying the appropriate interpretation based on the base parameter.
|
ParseInt(const char *str, int32_t & output)
|
bool
Parse and attempt to convert a string interpreted as a decimal value to a 32-bit signed integer, applying the appropriate interpretation based on the base parameter.
|
ParseInt(const char *str, uint16_t & output)
|
bool
Parse and attempt to convert a string interpreted as a decimal value to a 16-bit unsigned integer, applying the appropriate interpretation based on the base parameter.
|
ParseInt(const char *str, int16_t & output)
|
bool
Parse and attempt to convert a string interpreted as a decimal value to a 16-bit signed integer, applying the appropriate interpretation based on the base parameter.
|
ParseInt(const char *str, uint8_t & output)
|
bool
Parse and attempt to convert a string interpreted as a decimal value to a 8-bit unsigned integer, applying the appropriate interpretation based on the base parameter.
|
ParseNodeId(const char *str, uint64_t & nodeId)
|
bool
Parse a Weave node id in text form.
|
ParseSubnetId(const char *str, uint16_t & subnetId)
|
bool
Parse and attempt to convert a string to a 16-bit unsigned subnet ID, interpretting the string as hexadecimal.
|
PrintOptionHelp(OptionSet *optSets[], FILE *s)
|
void
Print the help text for a specified list of options to a stream.
|
PutStringWithBlankLine(FILE *s, const char *str)
|
void
|
PutStringWithNewLine(FILE *s, const char *str)
|
void
|
SplitArgs(char *argStr, char **& argList, char *initialArg)
|
int32_t
|
Classes |
|
---|---|
nl:: |
Common OptionSet for handling informational options (help, version). |
nl:: |
An OptionSet where the handler is a virtual function. |
Structs |
|
---|---|
nl:: |
Defines a command line option. |
nl:: |
Defines a group of logically-related and reusable command line options. |
Enumerations
OptionArgumentType
OptionArgumentType
Defines the argument requirements for a command line option.
Typedefs
NonOptionArgHandlerFunct
bool(* NonOptionArgHandlerFunct)(const char *progName, int argc, char *argv[])
A function that can be called to handle any remaining, non-option command line arguments.
OptionHandlerFunct
bool(* OptionHandlerFunct)(const char *progName, OptionSet *optSet, int id, const char *name, const char *arg)
A function that can be called to handle a set of command line options.
Variables
PrintArgError
void(* PrintArgError)(const char *msg,...) = DefaultPrintArgError
Pointer to function used to print errors that occur during argument parsing.
Applications should call PrintArgError() to report errors in their option and non-option argument handling functions, rather than printing directly to stdout/stderr.
Defaults to a pointer to the DefaultPrintArgError()
function.
gActiveOptionSets
OptionSet ** gActiveOptionSets = NULL
The list of OptionSets passed to the currently active ParseArgs() call.
This value will be NULL when no call to ParseArgs() is in progress.
Functions
CountAllOptions
size_t CountAllOptions( OptionSet *optSets[] )
CountAllOptions
size_t CountAllOptions( OptionSet **optSets )
CountOptionSets
size_t CountOptionSets( OptionSet *optSets[] )
CountOptionSets
size_t CountOptionSets( OptionSet **optSets )
DefaultPrintArgError
void DefaultPrintArgError( const char *msg, ... )
Print an error message associated with argument parsing.
Default function used to print error messages that arise due to the parsing of arguments.
Details | |||
---|---|---|---|
Parameters |
|
Applications should call through the PrintArgError function pointer, rather than calling this function directly.
FindOptionById
void FindOptionById( OptionSet **optSets, int optId, OptionSet *& optSet, OptionDef *& optDef )
FindOptionByIndex
void FindOptionByIndex( OptionSet **optSets, int optIndex, OptionSet *& optSet, OptionDef *& optDef )
GetNextArg
bool GetNextArg( char *& parsePoint )
IsShortOptionChar
bool IsShortOptionChar( int ch )
MakeLongOptions
struct option * MakeLongOptions( OptionSet **optSets )
MakeShortOptions
char * MakeShortOptions( OptionSet **optSets )
MakeUniqueHelpGroupNamesList
const char ** MakeUniqueHelpGroupNamesList( OptionSet *optSets[] )
ParseArgs
bool ParseArgs( const char *progName, int argc, char *argv[], OptionSet *optSets[], NonOptionArgHandlerFunct nonOptArgHandler, bool ignoreUnknown )
Parse a set of command line-style arguments, calling handling functions to process each option and non-option argument.
ParseArgs() takes a list of arguments (argv
) and parses them according to a set of supplied option definitions. The function supports both long (opt) and short (-o) options and implements the same option syntax as the GNU getopt_long(3) function.
Details | |||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Parameters |
|
||||||||||||
Returns |
true if all options and non-option arguments were parsed successfully; false if an option was unrecognized or if one of the handler functions failed (i.e. returned false). |
Option definitions are passed to ParseArgs() as an array of OptionSet structures (optSets
). Each OptionSet contains an array of option definitions and a handler function. ParseArgs() processes option arguments in the given order, calling the respective handler function for each recognized option. Once all options have been parsed, a separate non-option handler function (nonOptArgHandler
) is called once to process any remaining arguments.
OPTION SETS
An OptionSet contains a set of option definitions along with a pointer to a handler function that will be called when one of the associated options is encountered. Option sets also contain help text describing the syntax and purpose of each option (see OPTION HELP below). Option sets are designed to allow the creation of re-usable collections of related options. This simplifies the effort needed to maintain multiple applications that accept similar options (e.g. test applications).
There are two patterns for defining OptionSetsone can either initialize an instance of the OptionSet struct itself, e.g. as a static global, or subclass OptionSetBase and provide a constructor. The latter uses a pure virtual HandleOption()
function to delegate option handling to the subclass.
Lists of OptionSets are passed to the ParseArgs() function as a NULL-terminated array of pointers. E.g.:
static OptionSet gToolOptions = { HandleOption, // handler function gToolOptionDefs, // array of option definitions "GENERAL OPTIONS", // help group gToolOptionHelp // option help text }; static OptionSet *gOptionSets[] = { &gToolOptions, &gNetworkOptions, &gTestingOptions, &gHelpOptions, NULL }; int main(int argc, char *argv[]) { if (!ParseArgs("test-app", argc, argv, gOptionSets)) { ... } }
OPTION DEFINITIONS
Options are defined using the OptionDef
structure. Option definitions are organized as an array of OptionDef elements, where each element contains: the name of the option, a integer id that is used to identify the option, and whether the option expects/allows an argument. The end of the option array is signaled by a NULL Name field. E.g.:
enum { kOpt_Listen = 1000, kOpt_Length, kOpt_Count, }; static OptionDef gToolOptionDefs[] = { // NAME REQUIRES/ALLOWS ARG? ID/SHORT OPTION CHAR // ============================================================ { "listen", kNoArgument, kOpt_Listen }, { "length", kArgumentRequired, kOpt_Length }, { "count", kArgumentRequired, kOpt_Count }, { "num", kArgumentRequired, kOpt_Count }, // alias for --count { "debug", kArgumentOptional, 'd' }, { "help", kNoArgument, 'h' }, { NULL } };
OPTION IDS
Option ids identify options to the code that handles them (the OptionHandler function). Option ids are relative to the OptionSet in which they appear, and thus may be reused across different OptionSets (however see SHORT OPTIONS below). Common convention is to start numbering option ids at 1000, however any number > 128 can be used. Alias options can be created by using the same option id with different option names.
SHORT OPTIONS
Unlike getopt_long(3), ParseArgs() does not take a separate string specifying the list of short option characters. Rather, any option whose id value falls in the range of graphical ASCII characters will allow that character to be used as a short option.
ParseArgs() requires that short option characters be unique across all OptionSets. Because of this, the use of short options is discouraged for any OptionSets that are shared across programs due to the significant chance for collisions. Short options characters may be reused within a single OptionSet to allow for the creation of alias long option names.
OPTION HELP
Each OptionSet contains an OptionHelp
string that describes the purpose and syntax of the associated options. These strings are used by the PrintOptionHelp()
function to generate option usage information.
By convention, option help strings consist of a syntax example following by a textual description of the option. If the option has a short version, or an alias name, it is given before primary long name. For consistency, syntax lines are indented with 2 spaces, while description lines are indented with 7 spaces. A single blank line follows each option description, including the last one.
E.g.:
static const char *const gToolOptionHelp = " --listen\n" " Listen and respond to requests sent from another node.\n" "\n" " --length\n" " Send requests with the specified number of bytes in the payload.\n" "\n" " --num, --count \n" " Send the specified number of requests and exit.\n" "\n" " -d, --debug [ ] \n" " Set debug logging to the given level. (Default: 1)\n" "\n" " -h, --help\n" " Print help information.\n" "\n";
OPTION HELP GROUPS
OptionSets contain a HelpGroupName
string which is used to group options together in the help output. The PrintOptionHelp()
function uses the HelpGroupName as a section title in the generated usage output. If multiple OptionSets have the same HelpGroupName, PrintOptionHelp() will print the option help for the different OptionSets together under a common section title.
ParseArgs
bool ParseArgs( const char *progName, int argc, char *argv[], OptionSet *optSets[], NonOptionArgHandlerFunct nonOptArgHandler )
ParseArgs
bool ParseArgs( const char *progName, int argc, char *argv[], OptionSet *optSets[] )
ParseArgsFromEnvVar
bool ParseArgsFromEnvVar( const char *progName, const char *varName, OptionSet *optSets[], NonOptionArgHandlerFunct nonOptArgHandler, bool ignoreUnknown )
Parse a set of arguments from a named environment variable.
ParseArgsFromEnvVar() reads a named environment variable and passes the value to ParseArgsFromString()
for parsing. If the environment variable is not set, the function does nothing.
Details | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
Parameters |
|
||||||||||
Returns |
true if all options and non-option arguments were parsed successfully, or if the specified environment variable is not set; false if an option was unrecognized, if one of the handler functions failed (i.e. returned false) or if an internal error occurred. |
ParseArgsFromEnvVar
bool ParseArgsFromEnvVar( const char *progName, const char *varName, OptionSet *optSets[] )
ParseArgsFromEnvVar
bool ParseArgsFromEnvVar( const char *progName, const char *varName, OptionSet *optSets[], NonOptionArgHandlerFunct nonOptArgHandler )
ParseArgsFromString
bool ParseArgsFromString( const char *progName, const char *argStr, OptionSet *optSets[], NonOptionArgHandlerFunct nonOptArgHandler, bool ignoreUnknown )
Parse a set of arguments from a given string.
ParseArgsFromString() splits a given string (argStr
) into a set of arguments and parses the arguments using the ParseArgs() function.
Details | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
Parameters |
|
||||||||||
Returns |
true if all options and non-option arguments were parsed successfully; false if an option was unrecognized, if one of the handler functions failed (i.e. returned false) or if an internal error occurred. |
The syntax of the input strings is similar to unix shell command syntax, but with a simplified quoting scheme. Specifically:
- Arguments are delimited by whitespace, unless the whitespace is quoted or escaped.
- A backslash escapes the following character, causing it to be treated as a normal character. The backslash itself is stripped.
- Single or double quotes begin/end quoted substrings. Within a substring, the only special characters are backslash, which escapes the next character, and the corresponding end quote. The begin/end quote characters are stripped.
E.g.:
--listen --count 10 --sw-version '1.0 (DEVELOPMENT)' "--hostname=nest.com"
ParseArgsFromString
bool ParseArgsFromString( const char *progName, const char *argStr, OptionSet *optSets[], NonOptionArgHandlerFunct nonOptArgHandler )
ParseArgsFromString
bool ParseArgsFromString( const char *progName, const char *argStr, OptionSet *optSets[] )
ParseBoolean
bool ParseBoolean( const char *str, bool & output )
Parse a string as a boolean value.
This function accepts the following input values (case-insensitive): "true", "yes", "t", "y", "1", "false", "no", "f", "n", "0".
Details | |||||
---|---|---|---|---|---|
Parameters |
|
||||
Returns |
true on success; otherwise, false on failure.
|
ParseFabricId
bool ParseFabricId( const char *str, uint64_t & fabricId, bool allowReserved )
Parse a Weave fabric id in text form.
The ParseFabricId() function accepts a 64-bit fabric id given in hex format, with or without a leading '0x'.
Details | |||||||
---|---|---|---|---|---|---|---|
Parameters |
|
||||||
Returns |
true if the value was successfully parsed; false if not.
|
ParseHexString
bool ParseHexString( const char *hexStr, uint32_t strLen, uint8_t *outBuf, uint32_t outBufSize, uint32_t & outDataLen )
Parse a string of bytes given in hex form.
ParseHexString() expects the input to be in the form of pairs of hex digits (upper or lower case). Hex pairs can optionally be separated by any of the following characters: colon, semicolon, comma, period or dash. Additionally, whitespace characters anywhere in the input string are ignored.
Details | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
Parameters |
|
||||||||||
Returns |
true if the value was successfully parsed; false if the input data is malformed, or if
outBuf is too small. |
ParseIPAddress
bool ParseIPAddress( const char *str, IPAddress & output )
Parse an IP address in text form.
Details | |||||
---|---|---|---|---|---|
Parameters |
|
||||
Returns |
true if the value was successfully parsed; false if not.
|
ParseInt
bool ParseInt( const char *str, uint64_t & output, int base )
Parse and attempt to convert a string to a 64-bit unsigned integer, applying the appropriate interpretation based on the base parameter.
Details | |||||||
---|---|---|---|---|---|---|---|
Parameters |
|
||||||
Returns |
true on success; otherwise, false on failure.
|
ParseInt
bool ParseInt( const char *str, uint32_t & output, int base )
Parse and attempt to convert a string to a 32-bit unsigned integer, applying the appropriate interpretation based on the base parameter.
Details | |||||||
---|---|---|---|---|---|---|---|
Parameters |
|
||||||
Returns |
true on success; otherwise, false on failure.
|
ParseInt
bool ParseInt( const char *str, int32_t & output, int base )
Parse and attempt to convert a string to a 32-bit signed integer, applying the appropriate interpretation based on the base parameter.
Details | |||||||
---|---|---|---|---|---|---|---|
Parameters |
|
||||||
Returns |
true on success; otherwise, false on failure.
|
ParseInt
bool ParseInt( const char *str, uint64_t & output )
Parse and attempt to convert a string interpreted as a decimal value to a 64-bit unsigned integer, applying the appropriate interpretation based on the base parameter.
Details | |||||
---|---|---|---|---|---|
Parameters |
|
||||
Returns |
true on success; otherwise, false on failure.
|
ParseInt
bool ParseInt( const char *str, uint32_t & output )
Parse and attempt to convert a string interpreted as a decimal value to a 32-bit unsigned integer, applying the appropriate interpretation based on the base parameter.
Details | |||||
---|---|---|---|---|---|
Parameters |
|
||||
Returns |
true on success; otherwise, false on failure.
|
ParseInt
bool ParseInt( const char *str, int32_t & output )
Parse and attempt to convert a string interpreted as a decimal value to a 32-bit signed integer, applying the appropriate interpretation based on the base parameter.
Details | |||||
---|---|---|---|---|---|
Parameters |
|
||||
Returns |
true on success; otherwise, false on failure.
|
ParseInt
bool ParseInt( const char *str, uint16_t & output )
Parse and attempt to convert a string interpreted as a decimal value to a 16-bit unsigned integer, applying the appropriate interpretation based on the base parameter.
Details | |||||
---|---|---|---|---|---|
Parameters |
|
||||
Returns |
true on success; otherwise, false on failure.
|
ParseInt
bool ParseInt( const char *str, int16_t & output )
Parse and attempt to convert a string interpreted as a decimal value to a 16-bit signed integer, applying the appropriate interpretation based on the base parameter.
Details | |||||
---|---|---|---|---|---|
Parameters |
|
||||
Returns |
true on success; otherwise, false on failure.
|
ParseInt
bool ParseInt( const char *str, uint8_t & output )
Parse and attempt to convert a string interpreted as a decimal value to a 8-bit unsigned integer, applying the appropriate interpretation based on the base parameter.
Details | |||||
---|---|---|---|---|---|
Parameters |
|
||||
Returns |
true on success; otherwise, false on failure.
|
ParseNodeId
bool ParseNodeId( const char *str, uint64_t & nodeId )
Parse a Weave node id in text form.
The ParseNodeId() function accepts either a 64-bit node id given in hex format (with or without a leading '0x'), or the words 'any' or 'all' which are interpreted as meaning the Any node id (0xFFFFFFFFFFFFFFFF).
Details | |||||
---|---|---|---|---|---|
Parameters |
|
||||
Returns |
true if the value was successfully parsed; false if not.
|
ParseSubnetId
bool ParseSubnetId( const char *str, uint16_t & subnetId )
Parse and attempt to convert a string to a 16-bit unsigned subnet ID, interpretting the string as hexadecimal.
Details | |||||
---|---|---|---|---|---|
Parameters |
|
||||
Returns |
true on success; otherwise, false on failure.
|
PrintOptionHelp
void PrintOptionHelp( OptionSet *optSets[], FILE *s )
Print the help text for a specified list of options to a stream.
Details | |||||
---|---|---|---|---|---|
Parameters |
|
PutStringWithBlankLine
void PutStringWithBlankLine( FILE *s, const char *str )
PutStringWithNewLine
void PutStringWithNewLine( FILE *s, const char *str )
SplitArgs
int32_t SplitArgs( char *argStr, char **& argList, char *initialArg )