ALib C++ Framework
by
Library Version: 2605 R0
Documentation generated by doxygen
Loading...
Searching...
No Matches
alib::app::CommandLine Class Reference

Description:

This class provides a foundation for software executables that processes command-line parameters.

See also
"Utility" methods which could have been implemented as an interface of this class have instead been located as static methods in friend class CLIUtil which receive a pointer to an instance of this type.

Friends

class CLIUtil

Exceptions
Exceptionapp::CLIExceptions

Definition at line 28 of file cli.hpp.

#include <cli.hpp>

Collaboration diagram for alib::app::CommandLine:
[legend]

Public Field Index:

String AppInfo
StdVectorMA< integerArgsLeft
StdVectorMA< StringArgStrings
ListMA< CommandDecl * > CommandDecls
 Commands defined.
ListMA< Command * > CommandsParsed
 A list of commands actually parsed. Filled with method ReadNextCommands.
HashMap< MonoAllocator, Enum, ExitCodeDecl * > ExitCodeDecls
 Possible Errors.
integer MaxNameLength [3] ={ 0, 0, 0 }
ListMA< Command * >::iterator NextCommandIt
 The next command in CommandsParsed to be processed. Used with method NextCommand.
ListMA< String, Recycling::Shared > OptionArgsIgnored
ListMA< OptionDecl * > OptionDecls
 Possible Options.
ListMA< Option * > Options
 The options parsed in the order of their appearance.
ListMA< ParameterDecl * > ParameterDecls
 Possible Parameters.
NCString ResourceCategory
 The resource category to fetch CLI resources within field Resources.
resources::ResourcePoolResources =nullptr

Public Method Index:

 CommandLine ()
 Constructor.
virtual ~CommandLine ()
 Virtual empty destructor.
virtual int ArgCount ()
template<typename TEnum>
void DefineCommands ()
template<typename TEnum>
void DefineExitCodes ()
template<typename TEnum>
void DefineOptions ()
template<typename TEnum>
void DefineParameters ()
MonoAllocatorGetAllocator () noexcept
virtual String GetArg (integer idx)
OptionGetOption (Enum element)
const StringGetResource (const NString &name)
void Init (camp::Camp *resModule)
virtual void Init (resources::ResourcePool *resourcePool, NCString resCategory)
virtual CommandNextCommand ()
virtual String PeekArg ()
virtual String PopArg ()
virtual void ReadNextCommands ()
virtual void ReadOptions ()
bool RemoveArg (integer argNo)
const StringTryResource (const NString &name)
void UndefineCommand (Enum command)
void UndefineExitCode (Enum exitCode)
void UndefineOption (Enum option)
void UndefineParameter (Enum parameter)

Protected Field Index:

MonoAllocator allocator
ListMA< Parameter *, Recycling::Shared >::SharedRecyclerType paramListRecycler
ListMA< String, Recycling::Shared >::SharedRecyclerType stringListRecycler
 The element recycler shared between lists of strings.

Field Details:

◆ allocator

MonoAllocator alib::app::CommandLine::allocator
protected

Monotonic allocator used for all resourced static definitions as well as the data used during parsing.

Definition at line 52 of file cli.hpp.

◆ AppInfo

String alib::app::CommandLine::AppInfo

Application information text. Used as a sort of "header" output by class CLIUtil .

Definition at line 67 of file cli.hpp.

◆ ArgsLeft

StdVectorMA<integer> alib::app::CommandLine::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 80 of file cli.hpp.

◆ ArgStrings

StdVectorMA<String> alib::app::CommandLine::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 75 of file cli.hpp.

◆ CommandDecls

ListMA<CommandDecl*> alib::app::CommandLine::CommandDecls

Commands defined.

Definition at line 84 of file cli.hpp.

◆ CommandsParsed

ListMA<Command*> alib::app::CommandLine::CommandsParsed

A list of commands actually parsed. Filled with method ReadNextCommands.

Definition at line 107 of file cli.hpp.

◆ ExitCodeDecls

HashMap<MonoAllocator, Enum, ExitCodeDecl*> alib::app::CommandLine::ExitCodeDecls

Possible Errors.

Definition at line 93 of file cli.hpp.

◆ MaxNameLength

integer alib::app::CommandLine::MaxNameLength[3] ={ 0, 0, 0 }

The maximum length of token names:

  • 0: Commands
  • 1: Options

Note: Used for formatted help/dump output. (0= command, 1= option, 2= param)

Definition at line 117 of file cli.hpp.

◆ NextCommandIt

ListMA<Command*>::iterator alib::app::CommandLine::NextCommandIt

The next command in CommandsParsed to be processed. Used with method NextCommand.

Definition at line 110 of file cli.hpp.

◆ OptionArgsIgnored

ListMA<String, Recycling::Shared> alib::app::CommandLine::OptionArgsIgnored

List of arguments that start with a hyphen and are ignored by this class due to the fact that they were not recognized.

See also
Method ReadOptions for details on this.

Definition at line 104 of file cli.hpp.

◆ OptionDecls

ListMA<OptionDecl*> alib::app::CommandLine::OptionDecls

Possible Options.

Definition at line 87 of file cli.hpp.

◆ Options

ListMA<Option*> alib::app::CommandLine::Options

The options parsed in the order of their appearance.

Definition at line 98 of file cli.hpp.

◆ ParameterDecls

ListMA<ParameterDecl*> alib::app::CommandLine::ParameterDecls

Possible Parameters.

Definition at line 90 of file cli.hpp.

◆ paramListRecycler

ListMA<Parameter*,Recycling::Shared>::SharedRecyclerType alib::app::CommandLine::paramListRecycler
protected

◆ ResourceCategory

NCString alib::app::CommandLine::ResourceCategory

The resource category to fetch CLI resources within field Resources.

Definition at line 128 of file cli.hpp.

◆ Resources

resources::ResourcePool* alib::app::CommandLine::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 125 of file cli.hpp.

◆ stringListRecycler

ListMA<String,Recycling::Shared>::SharedRecyclerType alib::app::CommandLine::stringListRecycler
protected

The element recycler shared between lists of strings.

Definition at line 55 of file cli.hpp.

Constructor(s) / Destructor Details:

◆ CommandLine()

alib::app::CommandLine::CommandLine ( )
inline

Constructor.

Definition at line 135 of file cli.hpp.

◆ ~CommandLine()

virtual alib::app::CommandLine::~CommandLine ( )
inlinevirtual

Virtual empty destructor.

Definition at line 152 of file cli.hpp.

Method Details:

◆ ArgCount()

virtual int alib::app::CommandLine::ArgCount ( )
inlinevirtual

Retrieves the number of arguments.

Returns
The number of arguments given.

Definition at line 448 of file cli.hpp.

◆ DefineCommands()

template<typename TEnum>
void alib::app::CommandLine::DefineCommands ( )
inline

Defines commands given with enumeration TEnum. ALib Enum Records of type ERCommandDecl need to be associated to the given enumeration type TEnum.

Template Parameters
TEnumThe enum type.

Definition at line 252 of file cli.hpp.

Here is the call graph for this function:

◆ DefineExitCodes()

template<typename TEnum>
void alib::app::CommandLine::DefineExitCodes ( )
inline

Defines exit-codes given with enumeration TEnum. ALib Enum Records of type ERExitCodeDecl need to be associated to the given enumeration type TEnum.

Template Parameters
TEnumThe enum type.

Definition at line 313 of file cli.hpp.

Here is the call graph for this function:

◆ DefineOptions()

template<typename TEnum>
void alib::app::CommandLine::DefineOptions ( )
inline

Defines options given with enumeration TEnum. ALib Enum Records of type EROptionDecl need to be associated to the given enumeration type TEnum.

Template Parameters
TEnumThe enum type.

Definition at line 283 of file cli.hpp.

Here is the call graph for this function:

◆ DefineParameters()

template<typename TEnum>
void alib::app::CommandLine::DefineParameters ( )
inline

Defines parameters given with enumeration TEnum. ALib Enum Records of type ERParameterDecl need to be associated to the given enumeration type TEnum.

Template Parameters
TEnumThe enum type.

Definition at line 222 of file cli.hpp.

Here is the call graph for this function:

◆ GetAllocator()

MonoAllocator & alib::app::CommandLine::GetAllocator ( )
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 lifecycle of the instance of this class.

Returns
The internal allocator

Definition at line 163 of file cli.hpp.

◆ GetArg()

virtual String alib::app::CommandLine::GetArg ( integer idx)
inlinevirtual

Retrieves the argument at the given position.
In debug-builds, this method asserts the index is in the available range.

Parameters
idxThe requested argument's index.
Returns
The element idx of vector ArgStrings.

Definition at line 455 of file cli.hpp.

◆ GetOption()

Option * alib::app::CommandLine::GetOption ( Enum element)

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.

Parameters
elementThe option's declaration enum element.
Returns
A pointer to the parsed option, respectively nullptr if not given.

Definition at line 117 of file cli.cpp.

◆ GetResource()

const String & alib::app::CommandLine::GetResource ( const NString & name)
inline

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.

Parameters
nameThe resource name.
Returns
The resource string, respectively a nulled string on failure.

Definition at line 173 of file cli.hpp.

◆ Init() [1/2]

void alib::app::CommandLine::Init ( camp::Camp * resModule)
inline

Simple helper method that invokes Init(resources::ResourcePool*, NCString) providing the resource pool and categery of the given resModule.

Parameters
resModuleThe module used to load resource strings.

Definition at line 193 of file cli.hpp.

Here is the call graph for this function:

◆ Init() [2/2]

void alib::app::CommandLine::Init ( resources::ResourcePool * resourcePool,
NCString resCategory )
virtual

Initializes this class. This function has to be invoked after construction and after ALib was bootstrapped.

This method accesses global ALib variables alib::ARG_C, alib::ARG_VN, and alib::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(camp::Camp*) is provided which calls this method by forwarding the pool and category name from that module.

Parameters
resourcePoolThe resource pool used to load resource strings.
resCategoryThe resource category used to load resource strings.

Definition at line 7 of file cli.cpp.

Here is the call graph for this function:

◆ NextCommand()

Command * alib::app::CommandLine::NextCommand ( )
virtual

Returns the next item in vector NextCommand. If needed, ReadNextCommands is invoked.

Returns
The next command parsed from CLI argument list. nullptr, if no more commands are found.

Definition at line 152 of file cli.cpp.

Here is the call graph for this function:

◆ PeekArg()

virtual String alib::app::CommandLine::PeekArg ( )
inlinevirtual

Retrieves the next argument from the list without removing it.

See also
Method PopArg, RemoveArg and ReadNextCommands.
Returns
The first argument of (respectively remaining in) the list. If no argument is available, a nulled string is returned.

Definition at line 468 of file cli.hpp.

◆ PopArg()

String alib::app::CommandLine::PopArg ( )
virtual

Retrieves the next argument and removes it from list ArgsLeft.

See also
Method PeekArg, RemoveArg and ReadNextCommands.
Returns
The first argument of vector ArgsLeft. If no argument is available, a nulled string is returned.

Definition at line 164 of file cli.cpp.

Here is the call graph for this function:

◆ ReadNextCommands()

void alib::app::CommandLine::ReadNextCommands ( )
virtual

Parses as many commands as possible and stores them in CommandsParsed. Prior to invoking this method, 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:

  • Check if CommandsParsed is empty
  • Invoke this method (ReadNextCommands )
  • If still no command is found, break loop
  • Remove and process first command in CommandsParsed.

A similar parsing approach is supported with the 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 static AString & DumpParseResults(CommandLine&, Paragraphs&)  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 125 of file cli.cpp.

Here is the call graph for this function:

◆ ReadOptions()

void alib::app::CommandLine::ReadOptions ( )
virtual

Finalizes Initialization and has to be called after all invocations of:

  • DefineCommands,
  • DefineOptions,
  • DefineParameters and
  • DefineExitCodes,

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, the inherited field integer Position is quite useful, as well as the 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.

Note
A good sample for this is class CLIVariablesPlugin used with ALib configuration variables. After this method has been invoked, vector OptionArgsIgnored may/should be passed to the plug-in CLIVariablesPlugin of (all) Configuration object(s) used with the application. For this, an invocation, similar to this may be used with all ALib Modules that use an own configuration object:
  XYZModule.GetConfig()->GetPluginTypeSafe<alib::variables::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 57 of file cli.cpp.

Here is the call graph for this function:

◆ RemoveArg()

bool alib::app::CommandLine::RemoveArg ( integer argNo)

Removes the argument at position argNo. If the argument is not in ArgsLeft, an ALib Assertion is raised.

See also
Method PeekArg, PopArg and ReadNextCommands.
Parameters
argNoThe argument number to remove.
Returns
false if the arg was removed before, true if the arg was removed now.

Definition at line 173 of file cli.cpp.

◆ TryResource()

const String & alib::app::CommandLine::TryResource ( const NString & name)
inline

Helper function that uses fields Resources and ResourceCategory to fetch a resourced string.

Note
Usually, it is recommended to use GetResource, which asserts with debug-builds if a resource was not found.
Parameters
nameThe resource name.
Returns
The resource string, respectively a nulled string on failure.

Definition at line 185 of file cli.hpp.

◆ UndefineCommand()

void alib::app::CommandLine::UndefineCommand ( Enum command)
inline

Removes a recognizable command previously defined with DefineCommands.

See also
Chapter 6.4.2 Undefine CLI Elements of the Programmer's Manual.
Parameters
commandThe enumeration element that identifies the command to undefine.

Definition at line 267 of file cli.hpp.

◆ UndefineExitCode()

void alib::app::CommandLine::UndefineExitCode ( Enum exitCode)
inline

Removes a recognizable exit-code previously defined with DefineExitCodes.

See also
Chapter 6.4.2 Undefine CLI Elements of the Programmer's Manual.
Parameters
exitCodeThe enumeration element that identifies the exitCode to undefine.

Definition at line 324 of file cli.hpp.

◆ UndefineOption()

void alib::app::CommandLine::UndefineOption ( Enum option)
inline

Removes a recognizable option previously defined with DefineOptions.

See also
Chapter 6.4.2 Undefine CLI Elements of the Programmer's Manual.
Parameters
optionThe enumeration element that identifies the option to undefine.

Definition at line 297 of file cli.hpp.

◆ UndefineParameter()

void alib::app::CommandLine::UndefineParameter ( Enum parameter)
inline

Removes a recognizable parameter previously defined with DefineParameters.

See also
Chapter 6.4.2 Undefine CLI Elements of the Programmer's Manual.
Parameters
parameterThe enumeration element that identifies the parameter to undefine.

Definition at line 236 of file cli.hpp.


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