This class provides a foundation for software executables that processes command line parameters.
class CLIUtil
alib::cli::Exceptions |
Definition at line 35 of file commandline.hpp.
#include <commandline.hpp>
Public Method Index: | |
CommandLine () | |
Constructor. | |
virtual | ~CommandLine () |
Virtual empty destructor. | |
virtual integer | ArgCount () |
template<typename TEnum > | |
void | DefineCommands () |
template<typename TEnum > | |
void | DefineExitCodes () |
template<typename TEnum > | |
void | DefineOptions () |
template<typename TEnum > | |
void | DefineParameters () |
MonoAllocator & | GetAllocator () noexcept |
virtual String | GetArg (integer idx) |
ALIB_API Option * | GetOption (Enum element) |
const String & | GetResource (const NString &name) |
void | Init (lang::Camp *resModule) |
virtual ALIB_API void | Init (lang::resources::ResourcePool *resourcePool, NCString resCategory) |
virtual ALIB_API Command * | NextCommand () |
virtual String | PeekArg () |
virtual ALIB_API String | PopArg () |
virtual ALIB_API void | ReadNextCommands () |
virtual ALIB_API void | ReadOptions () |
ALIB_API void | RemoveArg (integer argNo) |
const String & | TryResource (const NString &name) |
Protected Field Index: | |
MonoAllocator | allocator |
List< MonoAllocator, Parameter *, Recycling::Shared >::SharedRecyclerType | paramListRecycler |
List< MonoAllocator, String, Recycling::Shared >::SharedRecyclerType | stringListRecycler |
The element recycler shared between lists of strings. | |
|
protected |
Monotonic allocator used for all resourced static definitions as well as the data used during parsing.
Definition at line 61 of file commandline.hpp.
String AppInfo |
Application information text. Used as a sort of "header" output by class CLIUtil .
Definition at line 76 of file commandline.hpp.
StdVectorMono<integer> ArgsLeft |
A vector of args. If constructor variant accepting wchar strings is used, those unicode strings get converted to 1-byte strings using the current locale.
Values that are 'consumed' by options that get defined, are removed.
Definition at line 89 of file commandline.hpp.
StdVectorMono<String> ArgStrings |
A vector of args. If the type of CLI argument strings provided with the constructor does not match the default ALib string width, the strings get converted.
Values that are 'consumed' by options that get defined, are not removed from this list. Instead, they are removed from index vector ArgsLeft.
Definition at line 84 of file commandline.hpp.
List<MonoAllocator, CommandDecl*> CommandDecls |
Commands defined.
Definition at line 93 of file commandline.hpp.
List<MonoAllocator, Command*> CommandsParsed |
A list of commands actually parsed. Filled with method ReadNextCommands.
Definition at line 116 of file commandline.hpp.
DryRunModes DryRun =DryRunModes::Off |
Specifies if a "dry run" should be performed. For more information, see CLIUtil::GetDryOpt.
Definition at line 141 of file commandline.hpp.
HashMap<MonoAllocator, Enum, ExitCodeDecl*> ExitCodeDecls |
Possible Errors.
Definition at line 102 of file commandline.hpp.
integer MaxNameLength[3] = { 0, 0, 0 } |
The maximum length of token names:
Note: Used for formatted help/dump output. (0= command, 1= option, 2= param)
Definition at line 126 of file commandline.hpp.
List<MonoAllocator,Command*>::Iterator NextCommandIt |
The next command in CommandsParsed to be processed. Used with method NextCommand.
Definition at line 119 of file commandline.hpp.
List<MonoAllocator, String, Recycling::Shared> OptionArgsIgnored |
List of arguments that start with a hyphen and are ignored by this class due to the fact that they were not recognized.
Definition at line 113 of file commandline.hpp.
List<MonoAllocator, OptionDecl*> OptionDecls |
Possible Options.
Definition at line 96 of file commandline.hpp.
List<MonoAllocator, Option*> Options |
The options parsed in the order of their appearance.
Definition at line 107 of file commandline.hpp.
List<MonoAllocator, ParameterDecl*> ParameterDecls |
Possible Parameters.
Definition at line 99 of file commandline.hpp.
|
protected |
The element recycler shared between fields Command::ParametersMandatory and Command::ParametersOptional.
Definition at line 68 of file commandline.hpp.
NCString ResourceCategory |
The resource category to fetch CLI resources within field Resources.
Definition at line 137 of file commandline.hpp.
lang::resources::ResourcePool* Resources = nullptr |
The resource pool used to fetch resources from. Several resources are loaded from this in addition to what is loaded as enum meta-information of the cli declaration objects.
It is recommended to have the main application implement a custom module, as described here.
Definition at line 134 of file commandline.hpp.
|
protected |
The element recycler shared between lists of strings.
Definition at line 64 of file commandline.hpp.
|
inline |
Constructor.
Definition at line 148 of file commandline.hpp.
|
inlinevirtual |
Virtual empty destructor.
Definition at line 166 of file commandline.hpp.
|
inlinevirtual |
Retrieves the number of arguments.
Definition at line 484 of file commandline.hpp.
|
inline |
Defines commands given with enumeration TEnum. ALib Enum Records of type ERCommandDecl need to associated to given enumeration type TEnum.
TEnum | The enum type. |
|
inline |
Defines errors given with enumeration TEnum. ALib Enum Records of type ERExitCodeDecl need to associated to given enumeration type TEnum.
TEnum | The enum type. |
|
inline |
Defines options given with enumeration TEnum. ALib Enum Records of type EROptionDecl need to associated to given enumeration type TEnum.
TEnum | The enum type. |
|
inline |
Defines parameters given with enumeration TEnum. ALib Enum Records of type ERParameterDecl need to associated to given enumeration type TEnum.
TEnum | The enum type. |
|
inlinenoexcept |
Returns the allocator used for all command parsing, resourced enum record creation and so on. This allocator might be used for allocations that align with (or are shorter as) the lifecylce of the instance of this class.
Definition at line 180 of file commandline.hpp.
Retrieves the argument at the given position.
In debug-builds, this method assert the index is in the available range.
idx | The requested argument's index. |
Definition at line 496 of file commandline.hpp.
Searches and returns the last occurrence of the specified option.
This method is to be used with options that overwrite previous values in case that it was given multiple times as a CLI argument. Instead, options that may occur multiple times without overriding a previous occurrence, are to be processed "manually" by examining field Options.
element | The option's declaration enum element. |
nullptr
if not given. Definition at line 157 of file commandline.cpp.
Helper function that uses fields Resources and ResourceCategory to fetch a resourced string.
With debug-builds, this method asserts that a resource was found. If this is not wanted, use TryResource.
name | The resource name. |
Definition at line 193 of file commandline.hpp.
|
inline |
Simple helper method that invokes Init(lang::resources::ResourcePool*, NCString ) providing the resource pool and categery of the given resModule.
resModule | The module used to load resource strings. |
Definition at line 217 of file commandline.hpp.
|
virtual |
Initializes this class. This function has to be invoked after construction and after this object ALib was bootstrapped.
This method accesses global ALib variables ARG_C, ARG_VN, and ARG_VW, and thus those have to be set by the user's main()
-function properly.
A resource pool has to be provided along with a corresponding resource category to use. While it is not necessary to do, it is recommended to create a custom ALib module, which holds such resource pool. For this case, overloaded helper method Init(lang::Camp*) is provided which calls this method by forwarding the pool and category name from that module.
resourcePool | The resource pool used to load resource strings. |
resCategory | The resource category used to load resource strings. |
Definition at line 22 of file commandline.cpp.
|
virtual |
Returns the next item in vector NextCommand. If needed, ReadNextCommands is invoked.
nullptr
, if no more commands are found. Definition at line 200 of file commandline.cpp.
|
inlinevirtual |
Retrieves the next argument from the list without removing it.
Definition at line 512 of file commandline.hpp.
|
virtual |
Retrieves the next argument and removes it from list ArgsLeft.
Definition at line 224 of file commandline.cpp.
|
virtual |
Parses as many commands as possible and stores them in CommandsParsed. Prior to invoking this methods, all CLI declarations have to be made. Furthermore, usually method ReadOptions has to be invoked before this method.
The name of the method indicates that one or more, but maybe not all commands are read. The reason for this behavior lies in the fact that commands may be defined that do their own, specifically coded parsing. As a matter of the fact that the flags and options of structs CommandDecl and ParameterDecl are kept rather simple to match the most usual cases, the parsing of arguments of a command often has to be left to be done by custom code. Mostly just when processing (executing) a command. In contrast to the need of parsing (and processing) all CLI options, given before processing commands, this is not a problem. The usual inner part of a command processing loop then looks like this:
A similar parsing approach is supported with method NextCommand. The only difference is that the parsed commands stay in CommandsParsed and instead field NextCommandIt indicates the position of the next command to read. This way, commands may refer to previous ones, if this is needed.
As a final note it should be mentioned, that implementing a "dry run" option on the level of command parsing, for the reasons explained above, might need some specific custom code to be able to parse all commands (without processing them). If such functionality is wanted, it is best to separate custom command parsing from command execution (the opposite was recommended above). Only the last command in the list has to be 'manually' processed, as the previous ones obviously got parsed well. With this approach, all commands can be parsed without executing them. Static utility method CLIUtil::DumpParseResults is a predefined way to then write information about all options and commands parsed.
A lower level "dry run", that receives information about the concrete actions that the processing of commands would perform, is of course a different, application specific task.
Definition at line 166 of file commandline.cpp.
|
virtual |
Finalizes Initialization and has to be called after all invocations of:
have been performed. All options recognized get collected in list Options The arguments of the options get removed from ArgsLeft.
In case of options that have own parameter arguments, such arguments may not be fully removed. This depends on whether it is possible with the simple flags and values provided in OptionDecl to enable class Option to fully detect them. Therefore, after this method is invoked, for options with more complex syntax, custom code may be needed to pull the "remainders" of option arguments from ArgsLeft. For this, field Option::Position is quite useful, as well as method RemoveArg.
It has to be ensured that before the next step, which is the invocation of ReadNextCommands, all option-related CLI arguments are cleaned away!
For this reason, this method removes all arguments that start with a hyphen '-'
from the ArgsLeft, even if they got not recognized. Those CLI arguments get collected in OptionArgsIgnored. Finding unrecognized options is not considered an error, because other libraries used with the software might read CLI options autonomously.
XYZModule.GetConfig().GetPluginTypeSafe<alib::config::CLIVariablesPlugin>()->SetArgs( &OptionArgsIgnored );
In the case that other libraries have more complex option syntax, e.g., options consisting of multiple arguments or such that do not even start with a hyphen character, then, this method should be called only after a custom code removes such 3rd party options in a reliable way!
If all this was not done, the "remainder" of custom options might confuse parsing of commands and its parameters and most probably would lead to an "unknown" command error when the remainders of non-removed 3rd party option arguments are consumed later.
As a consequence of this approach, a subsequent call to this method has no effect.
Definition at line 86 of file commandline.cpp.
void RemoveArg | ( | integer | argNo | ) |
Removes the argument at position argNo. If the argument is not in ArgsLeft, an ALib assertion is raised.
argNo | The argument number to remove. |
Definition at line 234 of file commandline.cpp.
Helper function that uses fields Resources and ResourceCategory to fetch a resourced string.
name | The resource name. |
Definition at line 207 of file commandline.hpp.