Quick Links: |
Provide command line parsing, validation, and access. More...
Namespaces | |
namespace | balcl |
balcl::OptionInfo
Specifications
balcl::CommandLine | value-semantic command-line arguments |
balcl::CommandLineOptionsHandle | references to parsed options |
balcl::CommandLine
, used to represent the command-line arguments passed to a process. Also provided is balcl::CommandLineOptionsHandle
, a class that provides access to the options (and associative values, if any) found in a balcl::CommandLine
object in a "parsed" state. balcl::CommandLine
takes a specification describing the command-line arguments. Once created, printUsage
can be invoked to print the usage syntax. The parse
method takes command-line arguments and validates them against the specification supplied at construction, printing suitable messages on an optionally-specified stream in case of a parsing error. Once parsed, options and values can be accessed using various access methods. The class provides a set of theType access methods (for example, theString
, theInt
) that return the value of the specified option name. It is also possible to link a variable with an option in the specification; doing so will cause the variable to be loaded with the option value once parse
has been invoked and was successful. The options
method returns a balcl::CommandLineOptionsHandle
containing option names and their values. bsl::optional
objects for each of the scalar option types except bool
. $ mybuildcommand -e -c CC64 myproject
mybuildcommand
. There is one option, described by -c CC64
: c
is the tag name, and CC64
is the option value. There is also one boolean option (flag): -e
is a flag, e
is the flag name. The last parameter, myproject
, is a non-option argument. -
is allowed (but not as the leading character). When a short tag is used on a command line, it must be preceded by -
, and when a long tag is used it must be preceded by --
. Flags have no corresponding values; they are either present or absent. Option tags must be followed by a corresponding option value. An option can have multiple values (such options are called multi-valued options). When multiple values are provided for an option, the tag must appear with each value (see the section Multi-Valued Options and How to Specify Them). Arguments that are not the command name, options, or flags are called "non-option" arguments and can be either single-valued or multi-valued. They do not have any tag associated with them. usage: mysort [-r|reverse] [-o|outputfile <outfile>] files...
'-r|reverse' is a flag: 'r' is the short tag, 'reverse' is the long tag. '-o|outputfile' is an option: 'o' is the short tag, 'outputfile' is the long tag. The value is parsed from the string 'outfile'. 'files...' describes the multi-valued non-option argument.
$ mysort -r -o myoutfile file1 file2 file3
$ mysort --reverse --outputfile myoutfile file1 file2 file3
-
and long tags with --
. To specify a non-option argument beginning with -
, use a single --
separator (not followed by a long tag). usage: myserver [-p|port <portNumber>]
$ myserver -p 13 $ myserver -p=13 # option value is '13' and *not* '=13' $ myserver -p13 $ myserver --port 13 $ myserver --port=13
=13
is desired as an option value, then whitespace must be used as in: $ myserver -p =13 # option value *is* '=13'
$ myserver -port13 $ myserver --p 13 $ myserver -port 13
-ctv
instead of -c -t -v
). While grouping flags, short tags must be used. For example, given the command-line specification described by the following usage string: usage: mysort [-r|reverse] [-i|insensitiveToCase] [-u|uniq]
$ mysort -r -i -u $ cmd -riu $ cmd -uir $ cmd -i -ru
usage: mysort [-r|reverse] [-i|insensitiveToCase] [-u|uniq] [-o|outfile <outputfile>]
$ mysort -riu -o myoutfile $ mysort -riuo myoutfile $ mysort -riuomyoutfile $ mysort -riuo=myoutfile
*
denotes a multi-valued option, and +
denotes a multivalued option that must occur at least once. usage: mycompiler [-l|library <libName>]* [-o|out outFile] [<object>]+
$ mycompiler -l lib1 -l lib2 -l lib3 -o main a.o b.o
$ mycompiler -l lib1 -o main -l lib2 -l lib3 a.o b.o
-l
must be repeated before both lib2
and lib3
): $ mycompiler -l lib1 lib2 lib3 -o main a.o b.o
$ mycompiler -l lib1 -o main --library lib2 -l lib3 a.o b.o
usage: mysort [-r|reverse] [-o|outputfile <outfile>] [<file>]+
$ mysort -r -o myoutfile file1 file2 file3 $ mysort file1 file2 file3 -r -o myoutfile $ mysort file1 -o myoutfile file2 -r file3 $ mysort file1 -o=myoutfile file2 -r file3
-
then it must not appear before any option or flag and a --
must be put on the command line to indicate the end of all options and flags. -o
should be followed by myoutfile
): $ mysort -o -r myoutfile file1 file2 file3
-weirdfilename
, which starts with -
, must appear after --
): $ mysort -weirdfilename file2 file3 -r -o myoutfile
$ mysort -r -o myoutfile -- -weirdfilename file2 file3 $ mysort file2 file3 -r -o myoutfile -- -weirdfilename
-weirdfilename file2 file3
file2 file3 -weirdfilename
balcl::OptionInfo
). Each entry (row) of the table describes an option (i.e., an option, flag, or non-option argument). Each entry has several fields, specified in the following order: Field name Main purpose (see below for more details) ============================ =========================================== tag field Specify tags (short and long) for options and flags. A non-option argument is indicated by an empty string. name field Specify the name through which the option value can be accessed. description field Used in printing usage. type-and-constraint field (1) Specify the type of the option value(s). (2) Specify a variable to be linked to the option. (3) Specify other constraints on individual value(s). occurrence information field (1) Specify a default value for an option. (2) Specify whether an option is required on the command line or is optional (by default, an option is optional).
balcl::OptionInfo
is a statically-initializable class but it does not conform to the bslma
allocator protocol, while balcl::Option
is convertible from balcl::OptionInfo
, takes allocators, and is suitable for storing into containers. <s>
is the short tag, and <long>
is the long tag; or <s>
), s
must be a single character (different from -
and |
); for long tags ("<long>"), long
must have 2 or more characters (which may contain -
, except as the first character, but cannot contain |
). Also note that either no tag (empty string), both short and long tags, or only a long tag, may be specified. options
method. =
, if any, is removed from the name before storing in the balcl::OptionInfo
. Thus, if a name having such a suffix is specified in a balcl::OptionInfo
(e.g., "nameOption=someAttribute"), the correct name to use for querying this option by name (e.g., through the options
handle) does not include the suffix (e.g., cmdLine.numSpecified("nameOption=someAttribute")
will always return 0, but cmdLine.numSpecified("nameOption")
will return the appropriate value). balcl::TypeInfo(&variable) balcl::TypeInfo(&variable, constraint) // Link the option with the specified 'variable'. Note that the option // type is inferred from the type of 'variable'. Optionally place the // user-specified 'constraint', of a type defined in // 'balcl::Constraint', on the value. balcl::TypeInfo(type) balcl::TypeInfo(type, constraint) // Specify the type of this option to be of the specified 'type'. // Optionally place the user-specified 'constraint', of a type defined // in 'balcl::Constraint', on the value. Don't link this // option with any variable. 'type' must be one of the static // variables (null pointers) listed in // {'balcl_optiontype'|Enumerators}.
parse
method of balcl::CommandLine
should that method determine a value for an option; otherwise, the linked variable is left unchanged. The value for an option is determined either from the command-line arguments passed to parse
or obtained from a pre-configured default value, if any (see Occurrence Information Field). bsl::optional
objects that wrap any of the non-array option types except for bool
(see Supported Types). Also, a link to a bsl::optional
object is disallowed if the option is "required" or has a default value (see Occurrence Information Field). printUsage
). Usage Meaning ============== ======================================================= "o|outputfile" The option being defined is either an option or a flag. The short tag is "o" and the long tag is "outputfile". Note that "o" alone is invalid since a long tag must be specified. "outputfile" The option being defined is either an option or a flag. There is no short tag and the long tag is "outputfile". "" Specifies a non-option argument.
Usage Meaning =============== ======================================================= "xyz" The option value can be accessed by "xyz".
int portNum; // a variable to be linked to an // option bool isVerbose; // a variable to be linked to a flag bsl::vector<bsl::string> fileNames; // a variable to be linked to a // multi-valued option
Usage Meaning =============== ======================================================= balcl::TypeInfo(&portNum) (1) Link the variable 'portNum' with this option value. That is, after successful parsing, this variable will contain the option value specified on the command line. (2) An integer value must be provided on the command line for this option (the type 'int' is inferred implicitly from the type of 'portNum'). balcl::TypeInfo(balcl::OptionType::k_INT) This option value must be an integer. balcl::TypeInfo(&isVerbose) Load the variable 'isVerbose' with this option value. balcl::TypeInfo(balcl::OptionType::k_BOOL) This option is a flag. balcl::TypeInfo(&fileNames) Load the variable 'fileNames' with the values specified for this multi-valued option (or multi-valued non-option argument). That is, after successful parsing, this variable will contain the sequence of values specified on the command line, in the same order. balcl::TypeInfo(balcl::OptionType::k_STRING_ARRAY) This option value consists of a sequence of string values specified on the command line, in the same order.
Usage Meaning =============== ======================================================== balcl::OccurrenceInfo::e_REQUIRED The value(s) for this option *must* be provided on the command line. For options that are of an array type, at least one value must be provided. Omission manifests as a parse error. balcl::OccurrenceInfo::e_OPTIONAL Value(s) for this option may be omitted on the command line. balcl::OccurrenceInfo::e_HIDDEN Same as 'e_OPTIONAL'; in addition, this option will not be displayed by 'printUsage'. 13 The default value for this option is 13 and the option is not required on the command line. If no value is provided, then 13 is used. If the type described by the type-and-constraint field is not integer, then it is an error.
options
or specifiedOptions
. In addition, if a variable was linked to this option, it will be unmodified after parsing. balcl_optiontype
) supplied as the first argument to: balcl::TypeInfo(type, constraint)
balcl::OptionType
shown below: Type Specifier ----------------------------- ------------------------- bool OptionType::k_BOOL char OptionType::k_CHAR int OptionType::k_INT bsls::Types::Int64 OptionType::k_INT64 double OptionType::k_DOUBLE bsl::string OptionType::k_STRING bdlt::Datetime OptionType::k_DATETIME bdlt::Date OptionType::k_DATE bdlt::Time OptionType::k_TIME bsl::vector<char> OptionType::k_CHAR_ARRAY bsl::vector<int> OptionType::k_INT_ARRAY bsl::vector<bsls::Types::Int64> OptionType::k_INT64_ARRAY bsl::vector<double> OptionType::k_DOUBLE_ARRAY bsl::vector<bsl::string> OptionType::k_STRING_ARRAY bsl::vector<bdlt::Datetime> OptionType::k_DATETIME_ARRAY bsl::vector<bdlt::Date> OptionType::k_DATE_ARRAY bsl::vector<bdlt::Time> OptionType::k_TIME_ARRAY
bdlb_numericparseutil
. bdlt_iso8601util
. bool
. Specifically, the utility struct
balcl::Constraint
defines TYPEConstraint
types (for instance, StringConstraint
, IntConstraint
) that can be used to define a constraint suitable for the balcl::TypeInfo
class. bool
value indicating whether or not the data abides by the constraint (with true
indicating success). A constraint for a given option whose value has the given type must be convertible to one of the TYPEConstraint
types defined in the utility struct
balcl::Constraint
. Note that when passing a function as a constraint, the address of the function must be passed. balcl::CommandLine
class has a complex set of preconditions on the option specification table (array of balcl::OptionInfo
objects) passed to each of its constructors. There are requirements on individual elements, on elements relative to each other, and on the entire set of elements. If these preconditions are not met, the behavior of the constructor is undefined. balcl::CommandLine::isValidOptionSpecification
, is provided to allow programmatic checking without risk of incurring undefined behavior. isTagValid
, isNameValid, and 'isDescriptionValid
methods of balcl::Option
, respectively. The tag field:
bool
type (also known as "flags") are distinguished from the other supported option types in several ways: -x=true
and -xFlag false
are disallowed). The presence or absence of the tag name (either long or short form) on the command line determines the value of the option. The boolean option type has no "array" form (i.e., there is no BoolArray
option type).
-x -x -x
). For other option types, specifying multiple tags for a non-array option is an error. true
; however, one can determine the number of appearances by using the position
accessor. A boolean option type cannot be configured to:
bsl::optional<bool>
variable. theBool
method returns the same value (true
or false
) as the isSpecified
method. In contrast, the the*
accessor methods for the other option types have a precondition such that either isSpecified()
must be true
or the option must have a default value. mysort
that has the following syntax: usage: mysort [-r|reverse] [-i|insensitivetocase] [-u|uniq] [-a|algorithm sortAlgo] -o|outputfile <outputFile> [-t|field-separator] <character> [<file>]* // Sort the specified files (in 'fileList'), // using the specified sorting algorithm and // write the output to the specified output file. option note ============ ==================================================== -a|algorithm (1) Value (provided on command line) of this option must be one among "quickSort", "insertionSort", "shellSort". (2) If not provided, default value will be "quickSort". -o|outfile (1) This option must not be omitted on command line.
bsl::string
so as to accommodate multiple files. INCORRECT USE REASON FOR INACCURACY =========================================== ============================ $ mysort -riu -o myofile -aDUMBSORT f1 f2 Incorrect because 'DUMBSORT' is not among valid values for the -a option. $ mysort -riu f1 f2 Incorrect because no value is provided for the -o option.
bool isValidAlgorithm(const bsl::string *algo, bsl::ostream& stream) // Return 'true' if the specified 'algo' is one among "quickSort", // "insertionSort", and "shellSort"; otherwise, output to the specified // 'stream' an appropriate error message and return 'false'. { if ("quickSort" == *algo || "insertionSort" == *algo || "shellSort" == *algo) { return true; // RETURN } stream << "Error: sorting algorithm must be either " "'quickSort', 'insertionSort', or 'shellSort'.\n"; return false; }
balcl::CommandLine
object to parse command-line options. The proper usage is shown below. First we declare the variables to be linked to the options. If they are needed at global scope, we could declare them as global variables, but we prefer to declare them as local variables inside main
: int main(int argc, const char *argv[]) {
balcl::OccurrenceInfo
), these variables are updated; otherwise, these variables are left unchanged. bool isReverse = false; // Must be initially 'false'. bool isCaseInsensitive = false; // Must be initially 'false'. bool isUniq = false; // Must be initially 'false'. bsl::optional<char> fieldSeparator; bsl::string outFile; bsl::string sortAlgo; bsl::vector<bsl::string> files;
false
; otherwise, these variables would show incorrect values (i.e., true
) if their corresponding tags are absent from the command line. // build constraint for sortAlgo option balcl::Constraint::StringConstraint validAlgoConstraint( &isValidAlgorithm); // option specification table balcl::OptionInfo specTable[] = { { "r|reverse", // tag "isReverse", // name "sort in reverse order", // description balcl::TypeInfo(&isReverse), // link balcl::OccurrenceInfo::e_OPTIONAL // occurrence info }, { "i|insensitivetocase", // tag "isCaseInsensitive", // name "be case insensitive while sorting", // description balcl::TypeInfo(&isCaseInsensitive), // link balcl::OccurrenceInfo::e_OPTIONAL // occurrence info }, { "u|uniq", // tag "isUniq", // name "discard duplicate lines", // description balcl::TypeInfo(&isUniq), // link balcl::OccurrenceInfo::e_OPTIONAL // occurrence info }, { "t|field-separator", // tag "fieldSeparator", // name "field separator character", // description balcl::TypeInfo(&fieldSeparator), // link balcl::OccurrenceInfo::e_OPTIONAL // occurrence info }, { "a|algorithm", // tag "sortAlgo", // name "sorting algorithm", // description balcl::TypeInfo(&sortAlgo, validAlgoConstraint), // link and // constraint balcl::OccurrenceInfo(bsl::string("quickSort")) // default // algorithm }, { "o|outputfile", // tag "outputFile", // name "output file", // description balcl::TypeInfo(&outFile), // link balcl::OccurrenceInfo::e_REQUIRED // occurrence info }, { "", // non-option "fileList", // name "files to be sorted", // description balcl::TypeInfo(&files), // link balcl::OccurrenceInfo::e_OPTIONAL // occurrence info } };
// Create command-line specification. balcl::CommandLine cmdLine(specTable); // Parse command-line options; if failure, print usage. if (cmdLine.parse(argc, argv)) { cmdLine.printUsage(); return -1; // RETURN }
cmdLine
object will acquire a value that conforms to the specified constraints. We can examine these values as follows: // If successful, obtain command-line option values. balcl::CommandLineOptionsHandle options = cmdLine.options(); // Access through linked variable. bsl::cout << "outFile: " << outFile << bsl::endl; bsl::cout << "isUniq: " << isUniq << bsl::endl; if (fieldSeparator.has_value()) { bsl::cout << "fieldSeparator: " << fieldSeparator.value() << bsl::endl; } // Access through *theType* methods. assert(cmdLine.theString("outputFile") == outFile); // Access through 'options'. assert(options.theString("outputFile") == outFile); // Check that required option has been specified once. assert(cmdLine.isSpecified("outputFile")); int count = -1; assert(cmdLine.isSpecified("outputFile", &count)); assert(1 == count); return 0; }
$ mysort -omyofile f1 f2 f3 $ mysort -ainsertionSort f1 f2 f3 -riu -o myofile outputFile $ mysort --algorithm insertionSort --outputfile myofile f1 f2 f3 --uniq
stdout
.