Command-Line Options

Introduction

Option

Option describes one command line value. The names you pass to addOption() decide whether the definition is a regular option or a positional argument.

Regular Options and Aliases

An option is a regular option as soon as at least one of its names starts with - or --. Regular options are read from the command line by their dashed names and may appear in any order. Any additional dashless names are value aliases. They are not accepted as command line arguments; they only provide stable and readable lookup names after parsing.

options->addOption({"--demo"_el, "demo"_el});

const auto values = manager.parseOrThrow(arguments);
if (values->getFlag("demo"_el)) {
    runDemo();
}

Because this definition has the dashed name --demo, it is a regular option. Because no explicit type is set, it keeps the regular-option default type OptionType::Flag. The command line accepts --demo. The name demo is only an alias for lookup through OptionValues.

Aliases are especially useful when an option has several command line spellings but your code should use one clear internal name.

options->addOption({"-n"_el, "--name"_el, "name"_el})
    .setType(el::OptionType::Text);

const auto name = values->getText("name"_el);

Here, -n and --name are accepted on the command line. The alias name is only used in user code.

Flags, Boolean Values, and Optional Values

OptionType::Flag is a valueless occurrence marker. It may repeat, and getFlagCount() reports the number of occurrences. A flag never accepts a command-line value and cannot have a configured default.

OptionType::Boolean is a typed value. It accepts the ASCII-case-insensitive true values true, on, yes, and enabled, and the false values false, off, no, and disabled. Boolean values use the same scalar and list behavior as integers and text and are read with getBoolean() or getBooleanList().

Set OptionFlag::AcceptAsFlag on a named scalar value option when it may also occur without a value:

options->addOption({"--color"_el, "color"_el})
    .setType(el::OptionType::Choice)
    .addChoice("auto"_el)
    .addChoice("always"_el)
    .setFlag(el::OptionFlag::AcceptAsFlag);

A bare occurrence stores an internal flag marker: getFlag() returns true and the declared typed getter returns its fallback. A valued occurrence stores only the declared type. Definitions using AcceptAsFlag must be named, non-positional, and accept exactly one value. The flag has no additional effect on OptionType::Flag and no option-set behavior.

Built-in Requests

The parser provides -h and --help[=<name>] for help output and the pure flag --version for version output by default. Bare help displays the ordinary document. The attached long form --help=<name> displays detailed help for a long, short, or internal option name. Detailed help searches global and module scopes in a deterministic order and provides See Also commands when the same name exists in other scopes. Set OptionParserFlag::NoHelpDetails to make help a pure flag and reject an attached target. Use OptionParserFlag::DisableHelp or OptionParserFlag::DisableVersion when an application protocol needs to use one of these names as an ordinary option. Disabling a built-in request also removes it from generated help and releases its names for application definitions.

options->setParserFlag(el::OptionParserFlag::DisableVersion);
options->addOption({"--version"_el, "language-version"_el})
    .setType(el::OptionType::Text);

Value Tokens Beginning With a Dash

A separate value token beginning with - is always rejected. Use attached syntax such as --count=-22 or --name=-draft. Shell quoting is processed before argv reaches the application, so the parser cannot determine whether a separate argument was quoted and does not make quoting an exception to this rule.

Positional Arguments

An option is positional only when none of its names starts with - or --. Positional arguments are assigned from non-option command line values in definition order. Their default type is OptionType::Text.

options->addOption({"path"_el});

const auto values = manager.parseOrThrow(arguments);
const auto path = values->getText("path"_el);

This definition has no dashed name, so path receives the next positional command line value. The command line does not accept --path unless you define a separate regular option with that dashed name.

If an active positional argument is required, invoking the command with no arguments produces the normal help output. This lets a user see the expected input before encountering a missing-value error. Set OptionParserFlag::ErrorOnEmptyRequiredPositionals to retain an error result for an empty command. The behavior applies only to required positional arguments; required regular options continue to report a missing-value error.

Choices and Explicit Types

Calling setChoices() or addChoice() promotes the option type to OptionType::Choice. This works for regular options and positional arguments.

options->addOption({"--mode"_el, "mode"_el})
    .setChoices(el::OptionChoices::create({"fast"_el, "safe"_el}));

const auto mode = values->getText("mode"_el);

The command line accepts values through --mode fast or --mode=safe. The dashless name mode remains a lookup alias because the definition has --mode.

If you explicitly set an inconsistent type after adding choices, parsing fails with a definition error that points back to the affected option. For example, choices require OptionType::Choice, and a choice option must have at least one configured choice.

Sensitive Text

Use OptionType::SensitiveText for a password, token, or other command-line value that should enter protected text storage:

options->addOption({"-s"_el, "--secret"_el, "secret"_el})
    .setType(el::OptionType::SensitiveText);

auto arguments = el::OptionManager::convertCommandLineArguments(argc, argv);
const auto result = manager.parse(arguments);
const auto secret = result.values()->getText("secret"_el);

Sensitive text accepts exactly one value. Definitions with a default value or a maximum other than one are rejected, and repeating the option is an error. The parsed value is stored as a marked String and is available through OptionValues::getText() or OptionValue::getText().

The converted argument list passed to parse() or parseOrThrow() must be a mutable lvalue. Before either method returns, each sensitive suffix is replaced with exactly five stars. Thus --secret=value becomes --secret=*****, while a separate or positional value becomes *****. The previous copy-on-write allocation is securely erased when it is writable shared storage; literal-backed strings are never modified. Error contexts built by the parser contain the masked argument list.

OptionResult::sensitiveTextLocations() exposes the read-only list of OptionSensitiveTextLocation values for every result status. Each location contains the argument index and UTF-8 byte index at which the sensitive suffix began. Attached long and short values start after =, while separate and positional values start at byte zero.

Command-line masking reduces later accidental exposure but cannot retract values already visible to the shell, process listings, operating-system facilities, logs, or earlier application code.

Custom Value Names

Help output normally derives value placeholders from the option type. Text options display <value>, integer options display <integer>, and choice options display <choice>. Use setValueName() when a domain-specific name is clearer. Pass the bare name; generated help adds the angle brackets.

options->addOption({"--config"_el, "config"_el})
    .setType(el::OptionType::Text)
    .setValueName("path"_el);

options->addOption("input"_el)
    .setValueName("source"_el)
    .setRequired();

These definitions are displayed as --config <path> and <source> in usage and option-list help. An empty value name clears the override and restores the type-derived or positional default.

Help, Version and Error Documents

OptionManager builds neutral TextDocument trees for help, version and option-error output. Applications can render these documents through PlainTextRenderer or TerminalDocumentRenderer. DisplayTextMap configures wording only; terminal colors and layout belong to TerminalDocumentStyle.

OptionErrorContext keeps the structured objects needed to build a complete diagnostic. The options root, selected module, option set and option are retained with shared pointers, while the command-line arguments and argument index preserve the source snapshot. Usage, contextual help and the full-help command are derived when the diagnostic is rendered instead of being copied into the context as plain text. The built-in parser escapes command-line values before inserting them into explanatory messages. Command-line snippets escape every displayed argument and calculate marker ranges from that escaped representation, so a visible sequence such as \\033 is covered by the marker in full. The executable name derived from argv[0] is escaped in usage and full-help commands as well.

Unknown long options, modules, detailed-help names, and visible choice values receive up to three ranked suggestions. Suggestions use decoded Unicode code points, adjacent-transposition-aware Damerau-Levenshtein distance, and conservative length-dependent thresholds. They are retained in OptionErrorContext::suggestions() and rendered in a localized Did You Mean section before usage and contextual help.

Use OptionErrorContext::setTitle() for the short error heading and OptionErrorContext::setDescription() for the explanatory paragraph. If a callback omits the title, the parser supplies a title based on OptionErrorReason.

Interface

class Option

A single command line option definition.

An option with at least one dashed name is a regular option. Dashless names on regular options are value aliases. An option without dashed names is a positional argument.

See: Command-Line Options

Public Functions

Option() = default

Create an empty option.

Option(std::initializer_list<text::String> names)

Create an option with names.

void addName(text::String name)

Add a command-line name or lookup alias for this option.

Parameters:

name – The name to append. Dashed names are accepted on the command line, dashless names are lookup aliases or positional argument names.

inline const std::vector<text::String> &names() const noexcept

Get all names for this option.

void setNames(std::initializer_list<text::String> names)

Replace all names for this option.

bool isDisabled() const noexcept

Test if this option is disabled.

bool hasLongName(const text::String &name) const

Test if this option has the given long name.

bool hasShortName(text::Char shortName) const

Test if this option has the given short name.

bool hasOptionName() const

Test if this option has any dashed regular option name.

inline bool isRegularOption() const

Test if this option is a regular option.

inline bool isPositionalArgument() const

Test if this option is a positional argument.

bool hasPositionalName() const

Test if this option has any dashless name.

bool hasPositionalName(const text::String &name) const

Test if this option has the given dashless name.

bool hasValidOptionNames() const noexcept

Test if all names in this option are valid.

bool hasConflictingOptionName(const Option &other) const

Test if this option has a name that conflicts with another option.

std::optional<text::String> matchingChoiceText(const text::String &text) const

Find a configured choice text matching text case-insensitively.

inline const OptionHelp &help() const noexcept

Get the help metadata for this option.

inline void setHelp(OptionHelp help)

Set the complete help metadata for this option.

Parameters:

help – The replacement help metadata.

inline void setHelpTitle(text::String title)

Set the help title for this option.

Parameters:

title – Short title used when no description is available.

inline void setHelpDescription(text::String description)

Set the help description for this option.

Parameters:

description – User-facing description shown next to this option in help output.

inline void setHelpEpilog(text::String epilog)

Set the help epilog for this option.

Parameters:

epilog – Optional trailing text for renderers that support option-level epilogs.

inline void setHelpExample(text::String example)

Set the detailed-help example for this option.

Parameters:

example – Short usage example for detailed help.

inline void setHelpVisibility(const OptionHelpVisibility visibility) noexcept

Set the help visibility for this option.

Parameters:

visibility – Controls where this option appears in generated help output.

inline const text::String &valueName() const noexcept

Get the custom value name shown in help output.

inline void setValueName(text::String valueName)

Set the custom value name shown in help output.

Parameters:

valueName – Bare value name without angle brackets. Empty restores the type-derived default.

inline OptionType type() const noexcept

Get the option type.

inline void setType(const OptionType type) noexcept

Set the option type.

inline OptionFlags flags() const noexcept

Get the option flags.

inline void setFlags(const OptionFlags flags) noexcept

Set the option flags.

inline const OptionChoicesPtr &choices() const noexcept

Get the accepted choices.

inline void setChoices(OptionChoicesPtr choices)

Set the accepted choices.

inline unit::ArgumentCount maximum() const noexcept

Get the maximum number of values for this option.

inline void setMaximum(const unit::ArgumentCount maximum) noexcept

Set the maximum number of values for this option.

inline bool hasDefaultValue() const noexcept

Test if a default value is set.

inline const std::optional<OptionValueStorage> &defaultValue() const noexcept

Get the optional default value.

inline void setDefaultValue(std::optional<OptionValueStorage> defaultValue)

Set the optional default value.

inline const OptionValidateFn &validateFn() const noexcept

Get the value validation callback.

inline void setValidateFn(OptionValidateFn fn)

Set the value validation callback.

Parameters:

fn – The new value validation callback (OptionValuePtr valueToValidate, OptionValuesPtr values) -> void

Public Static Functions

static OptionPtr create()

Create a shared empty option.

Returns:

A shared option with no names and the default implicit text type.

static OptionPtr create(std::initializer_list<text::String> names)

Create a shared option with names.

Parameters:

names – The command-line names and lookup aliases for this option.

Returns:

A shared option whose implicit type is derived from the names.

static bool isLongName(const text::String &name) noexcept

Test if a name is a long command line option name.

Parameters:

name – The name to classify.

Returns:

true if the name starts with --.

static bool isShortName(const text::String &name) noexcept

Test if a name is a short command line option name.

Parameters:

name – The name to classify.

Returns:

true if the name starts with one dash and contains exactly one option character.

static bool isOptionName(const text::String &name) noexcept

Test if a name is a command line option name.

static bool isPositionalName(const text::String &name) noexcept

Test if a name is a positional argument name.

static bool isValidLongName(const text::String &name) noexcept

Test if a name is a valid long command line option name.

static bool isValidShortName(const text::String &name) noexcept

Test if a name is a valid short command line option name.

static bool isValidOptionName(const text::String &name) noexcept

Test if a name is a valid command line option name.

static bool isValidPositionalName(const text::String &name) noexcept

Test if a name is a valid positional argument name.

using erbsland::options::OptionValidateFn = std::function<void(OptionValuePtr valueToValidate, OptionValuesPtr values)>

A callback to validate option values.

Option values are validated before any post-parsing callback is called. The first argument of the callback is the value to be validated.

Throws options::OptionError:

if the validation failed. Must provide description in the error context. Missing values are automatically added by the surrounding context.

using erbsland::options::PreOptionSetParsingFn = std::function<void(OptionSetPtr)>

A callback called before an option set is parsed.

Throws options::OptionError:

if parsing should be aborted. Must provide description in the error context. Can optionally provide option to pin-down an option as error-location. Missing values are automatically added by the surrounding context.

using erbsland::options::PreOptionModuleParsingFn = std::function<void(OptionModulePtr)>

A callback called before an option module is parsed.

Throws options::OptionError:

if parsing should be aborted. Must provide description in the error context. Can optionally provide option or optionSet to pin-down an option as error-location. Missing values are automatically added by the surrounding context.

using erbsland::options::PostParsingFn = std::function<void(OptionValuesPtr)>

A callback called after successful parsing.

Throws options::OptionError:

if post-validation failed. Must provide description in the error context. Shall provide option or optionSet to pin-down the error-location. Missing values are automatically added by the surrounding context.

using erbsland::options::ModuleMainFn = std::function<unit::ExitCode(OptionValuesPtr)>

The main function for a selected option module.

Note

For convenience, exceptions derived from err::Exception are automatically handled in core::Application. The exception message is printed to stdOut(), and the program exits with code 1. We recommend that exceptions shall be handled inside the function, and it returns a custom exit code.

Throws err::Exception:

Exceptions derived from err::Exception are displayed, and the application exits with error code 1.

class OptionChoice

A single accepted choice for an option.

Choice matching is case-insensitive, but the stored parsed value uses the configured choice text.

Public Functions

OptionChoice() = default

Create an empty option choice.

explicit OptionChoice(text::String text)

Create a choice with the given text.

Parameters:

text – Choice text accepted on the command line.

OptionChoice(text::String text, OptionHelp help)

Create a choice with the given text and help.

Parameters:
  • text – Choice text accepted on the command line.

  • help – Help metadata for generated details.

inline const OptionHelp &help() const noexcept

Get the help text.

inline void setHelp(OptionHelp help)

Set the help text.

Parameters:

help – Replacement help metadata.

inline void setHelpTitle(text::String title)

Set the help title for this choice.

Parameters:

title – Short title used when no description is available.

inline void setHelpDescription(text::String description)

Set the help description for this choice.

Parameters:

description – User-facing description shown for this choice in help output.

inline void setHelpEpilog(text::String epilog)

Set the help epilog for this choice.

Parameters:

epilog – Optional trailing text for renderers that support choice-level epilogs.

inline void setHelpExample(text::String example)

Set the detailed-help example for this choice.

Parameters:

example – Short usage example for detailed help.

inline void setHelpVisibility(const OptionHelpVisibility visibility) noexcept

Set the help visibility for this choice.

Parameters:

visibility – Controls where this choice appears in generated help output.

inline const text::String &text() const noexcept

Get the choice text.

inline void setText(text::String text)

Set the choice text.

Parameters:

text – Replacement choice text.

Public Static Functions

static OptionChoicePtr create(text::String text)

Create a shared choice.

Parameters:

text – Choice text accepted on the command line.

Returns:

A shared choice object.

static OptionChoicePtr create(text::String text, OptionHelp help)

Create a shared choice with help.

Parameters:
  • text – Choice text accepted on the command line.

  • help – Help metadata for generated details.

Returns:

A shared choice object.

class OptionChoiceEditor

A fluent editor for an option choice definition.

Editors are returned by OptionChoices::addChoice() so choice help can be configured in one expression.

Public Functions

OptionChoiceEditor() = default

Create an empty option choice editor.

explicit OptionChoiceEditor(OptionChoicePtr choice) noexcept

Create an editor for an option choice.

bool isValid() const noexcept

Test if this editor has an option choice.

Returns:

true if mutating calls will be applied to an option choice.

inline const OptionChoicePtr &choice() const noexcept

Access the edited option choice.

Returns:

The shared option choice edited by this object, or nullptr for an invalid editor.

OptionChoiceEditor &setHelp(text::String description)

Set the help description.

Parameters:

description – User-facing help description for this choice.

Returns:

This editor for chaining.

OptionChoiceEditor &setHelp(OptionHelp help)

Set the full help definition.

Parameters:

help – Complete help metadata.

Returns:

This editor for chaining.

OptionChoiceEditor &setHelpTitle(text::String title)

Set the help title.

Parameters:

title – Short title used when no description is available.

Returns:

This editor for chaining.

OptionChoiceEditor &setHelpDescription(text::String description)

Set the help description.

Parameters:

description – User-facing help description for this choice.

Returns:

This editor for chaining.

OptionChoiceEditor &setHelpEpilog(text::String epilog)

Set the help epilog.

Parameters:

epilog – Optional trailing text for renderers that support choice-level epilogs.

Returns:

This editor for chaining.

OptionChoiceEditor &setHelpExample(text::String example)

Set the detailed-help example.

Parameters:

example – Short usage example for detailed help.

Returns:

This editor for chaining.

OptionChoiceEditor &setHelpVisibility(OptionHelpVisibility visibility)

Set the help visibility.

Parameters:

visibility – Controls where this choice appears in generated help output.

Returns:

This editor for chaining.

class OptionChoices

A collection of accepted option choices.

Assign a collection to an option with setChoices() or use OptionEditor::addChoice() for simple definitions.

Public Functions

OptionChoices() = default

Create an empty option-choice collection.

OptionChoiceEditor addChoice(OptionChoicePtr choice)

Add a choice.

Parameters:

choice – Choice object to append.

Returns:

An editor for the appended choice.

OptionChoiceEditor addChoice(text::String text)

Add a choice by text.

Parameters:

text – Choice text to append.

Returns:

An editor for the appended choice.

inline const std::vector<OptionChoicePtr> &choices() const noexcept

Get all choices.

inline unit::ArgumentCount choiceCount() const noexcept

Get the number of choices.

Returns:

The number of configured choices.

Public Static Functions

static OptionChoicesPtr create()

Create an empty shared choice collection.

Returns:

A shared choice collection without choices.

static OptionChoicesPtr create(std::initializer_list<text::String> choices)

Create a shared choice collection from text values.

Parameters:

choices – Choice texts to add in declaration order.

Returns:

A shared choice collection containing one choice for each text.

class OptionEditor

A fluent editor for an option definition.

Editors are returned by addOption() and editOption() so option definitions can be configured in one expression.

Public Functions

OptionEditor() = default

Create an empty option editor.

explicit OptionEditor(OptionPtr option) noexcept

Create an editor for an option.

bool isValid() const noexcept

Test if this editor has an option.

Returns:

true if mutating calls will be applied to an option.

inline const OptionPtr &option() const noexcept

Access the edited option.

Returns:

The shared option edited by this object, or nullptr for an invalid editor.

OptionEditor &setHelp(text::String description)

Set the help description.

Parameters:

description – User-facing help description for this option.

Returns:

This editor for chaining.

OptionEditor &setHelp(OptionHelp help)

Set the full help definition.

Parameters:

help – Complete help metadata.

Returns:

This editor for chaining.

OptionEditor &setHelpTitle(text::String title)

Set the help title.

Parameters:

title – Short title used when no description is available.

Returns:

This editor for chaining.

OptionEditor &setHelpDescription(text::String description)

Set the help description.

Parameters:

description – User-facing help description for this option.

Returns:

This editor for chaining.

OptionEditor &setHelpEpilog(text::String epilog)

Set the help epilog.

Parameters:

epilog – Optional trailing text for renderers that support option-level epilogs.

Returns:

This editor for chaining.

OptionEditor &setHelpExample(text::String example)

Set the detailed-help example.

Parameters:

example – Short usage example for detailed help.

Returns:

This editor for chaining.

OptionEditor &setHelpVisibility(OptionHelpVisibility visibility)

Set the help visibility.

Parameters:

visibility – Controls where this option appears in generated help output.

Returns:

This editor for chaining.

OptionEditor &setValueName(text::String valueName)

Set the custom value name shown in help output.

Parameters:

valueName – Bare value name without angle brackets. Empty restores the type-derived default.

Returns:

This editor for chaining.

OptionEditor &setType(OptionType type)

Set the option type.

Parameters:

type – The expected command-line value type.

Returns:

This editor for chaining.

OptionEditor &setType(OptionType::Type type)

Set the option type.

OptionEditor &setFlags(OptionFlags flags)

Set all option flags.

Parameters:

flags – Replacement flags for the option.

Returns:

This editor for chaining.

OptionEditor &setFlag(OptionFlag flag)

Set one option flag.

OptionEditor &clearFlag(OptionFlag flag)

Clear one option flag.

OptionEditor &setChoices(OptionChoicesPtr choices)

Set the choices and promote the option type to OptionType::Choice.

OptionEditor &addChoice(text::String text)

Add a choice by text and promote the option type to OptionType::Choice.

OptionEditor &setMaximum(unit::ArgumentCount maximum)

Set the maximum number of values.

OptionEditor &setDefaultValue(OptionValueStorage defaultValue)

Set the default value.

OptionEditor &clearDefaultValue()

Clear the default value.

OptionEditor &setValidateFn(OptionValidateFn fn)

Set the validation callback.

Parameters:

fn – The new value validation callback (OptionValuePtr valueToValidate, OptionValuesPtr values) -> void The callback must throw an el::OptionError on failure.

template<typename tValueType>
OptionEditor &setValidateTextValue(text::String errorTitle = {})

Setup a value validation for a type that parses text.

The submitted type must have one of these methods:

  • a static fromStringOrThrow(String) method that throws an err::ParseError on failure.

  • a static isValidString(String) method that returns false on failure.

  • a static fromString(String) method that returns std::nullopt on failure. The methods are used in in the order shown above.

Template Parameters:

tValueType – The type to validate.

Parameters:

errorTitle – The error title to use in the error message.

OptionEditor &setRequired()

Set the option as required.

class OptionError : public erbsland::err::RuntimeError

An error raised while processing command line options.

Public Functions

OptionError() noexcept = default

Create an option error.

explicit OptionError(text::String reason, const std::exception_ptr &cause = {}) noexcept

Create an option error with a reason.

OptionError(text::String title, text::String description, const OptionValuePtr &value, const std::exception_ptr &cause = {}) noexcept

Create an option error caused by a failed value validation.

This ctor automatically constructs the missing meta information from the given value.

Parameters:
  • title – The title of the error (What went wrong?)

  • description – The description of the error (Why did it happen?)

  • value – The value that caused the error.

  • cause – The optional cause of the error.

OptionError(text::String description, const OptionValuePtr &value, const std::exception_ptr &cause = {}) noexcept

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

explicit OptionError(OptionErrorContext context) noexcept

Create an option error with reason details.

Parameters:

context – The error context.

explicit OptionError(OptionErrorContext context, const std::exception_ptr &cause) noexcept

Create an option error with reason details and a cause.

Parameters:
  • context – The error context.

  • cause – The cause of the error.

virtual err::DiagnosticConstPtr diagnostic() const override

Create a diagnostic document for this error.

inline const OptionErrorContext &context() const noexcept

Get the error context.

class OptionErrorContext

A detailed error context to pin the source and reason for an error.

Public Functions

inline OptionErrorContext(text::String title, text::String description = {}) noexcept

Create a new option error context with a given title and description.

Parameters:
  • title – The title of the error.

  • description – The description of the error.

inline text::String title() const

Get the short user-facing error title.

inline OptionErrorContext &setTitle(text::String title)

Set the short user-facing error title.

Parameters:

title – The title text.

Returns:

A reference to this context.

inline text::String description() const

Get the detailed user-facing error description.

inline OptionErrorContext &setDescription(text::String description)

Set the detailed user-facing error description.

Parameters:

description – The description text.

Returns:

A reference to this context.

inline OptionErrorReason reason() const

Get the machine-readable error reason.

inline OptionErrorContext &setReason(OptionErrorReason reason)

Set the machine-readable error reason.

Parameters:

reason – The reason value.

Returns:

A reference to this context.

inline unit::ArgumentIndex argumentIndex() const

Get the command-line argument index related to the error.

inline OptionErrorContext &setArgumentIndex(unit::ArgumentIndex index)

Set the command-line argument index related to the error.

Parameters:

index – The argument index.

Returns:

A reference to this context.

inline const OptionsPtr &options() const noexcept

Get the options root related to the error.

inline OptionErrorContext &setOptions(OptionsPtr options)

Set the options root related to the error.

Parameters:

options – The options root.

Returns:

A reference to this context.

inline const OptionModulePtr &module() const noexcept

Get the selected module related to the error.

inline OptionErrorContext &setModule(OptionModulePtr module)

Set the selected module related to the error.

Parameters:

module – The selected module.

Returns:

A reference to this context.

inline const OptionPtr &option() const noexcept

Get the option related to the error.

inline OptionErrorContext &setOption(const OptionPtr &option)

Set the option related to the error.

Parameters:

option – The option pointer.

Returns:

A reference to this context.

inline const OptionSetPtr &optionSet() const noexcept

Get the option set related to the error.

inline OptionErrorContext &setOptionSet(const OptionSetPtr &optionSet)

Set the option set related to the error.

Parameters:

optionSet – The option-set pointer.

Returns:

A reference to this context.

inline const text::StringList &arguments() const noexcept

Get all command-line arguments related to the error.

inline OptionErrorContext &setArguments(text::StringList arguments)

Set all command-line arguments related to the error.

Parameters:

arguments – The command-line arguments.

Returns:

A reference to this context.

inline const text::StringList &suggestions() const noexcept

Get suggested replacements for an unknown or invalid name.

inline OptionErrorContext &setSuggestions(text::StringList suggestions)

Set suggested replacements in display order.

inline const i18n::DisplayTextMapConstPtr &displayText() const noexcept

Get the display wording captured for this error.

inline OptionErrorContext &setDisplayText(i18n::DisplayTextMapConstPtr displayText)

Set the display wording captured for this error.

Parameters:

displayText – The wording configuration.

Returns:

A reference to this context.

enum class erbsland::options::OptionErrorReason : uint8_t

The structured reason for an option error.

Values:

enumerator None

No reason given.

enumerator SyntaxError

The command line syntax is invalid.

enumerator UnknownName

An option name is not known.

enumerator UnexpectedValueType

A parsed value does not match the expected option type.

enumerator ValidationError

A callback or validator rejected the parsed options.

enumerator NotImplemented

The requested operation is not implemented yet.

enum class erbsland::options::OptionFlag : uint8_t

Flags for an option or option set.

Flags modify parser behavior. Use help visibility to hide enabled options from generated help without disabling parsing.

Values:

enumerator None

No flag.

enumerator Disabled

Do not accept or show the option.

enumerator Required

Require the option to be present.

enumerator Greedy

Allow a positional list option to consume values greedily.

enumerator AcceptAsFlag

Allow a named value option to be used without a value.

using erbsland::options::OptionFlags = util::EnumFlags<OptionFlag>

A set of option flags.

class OptionHelp

Help visibility and text for options, sets, modules, choices, and the root options object.

This object stores display metadata only; parser behavior is controlled by option names, types, flags, and callbacks.

Public Functions

OptionHelp() = default

Create empty option help metadata.

explicit OptionHelp(text::String description)

Create help text from a description.

Parameters:

description – User-facing description text for generated help output.

inline OptionHelpVisibility visibility() const noexcept

Get the visibility of this help text.

inline void setVisibility(const OptionHelpVisibility visibility) noexcept

Set the visibility of this help text.

Parameters:

visibility – Controls where this item appears in generated help output.

inline const text::String &title() const noexcept

Get the title.

inline void setTitle(text::String title)

Set the title.

Parameters:

title – Short title, used for option-set groups and as fallback text when no description is available.

inline const text::String &description() const noexcept

Get the main description.

inline void setDescription(text::String description)

Set the main description.

Parameters:

description – Main user-facing help text.

inline const text::String &epilog() const noexcept

Get the epilog text.

inline void setEpilog(text::String epilog)

Set the epilog text.

Parameters:

epilog – Optional trailing help text rendered after root or module help output.

inline const text::String &example() const noexcept

Get the optional example text.

inline void setExample(text::String example)

Set the optional example text.

Parameters:

example – Short usage example for detailed help.

enum class erbsland::options::OptionHelpVisibility : uint8_t

The help visibility of an option, option set, module, choice, or options root.

Visibility only affects generated help documents. It does not disable parsing; use OptionFlag::Disabled to remove an option or option set from parsing.

Values:

enumerator Inherit

Inherit visibility from the owning option set, or use Normal if no owner defines visibility.

enumerator Hidden

Accept the option while hiding it from generated help output.

enumerator Normal

Show in help for the active root or module. This is the default effective visibility.

enumerator Overview

Also show in root overview help when modules exist.

enumerator Usage

Show like Overview and render the option explicitly in the usage line.

using erbsland::options::OptionInteger = int64_t

The integer type used by the options system.

class OptionManager

The option manager orchestrates parsing and validation of command line options.

Command line parsing follows the most common standards that are safe and user-friendly: cmd -a -b -c # short options, case-sensitive cmd -abc # grouped short options cmd long # long options, case-insensitive. Must start with a letter [a-zA-Z]. cmd module -a long # module names are case-insensitive. Same rules as long options.

Option names: ASCII letters [a-zA-Z] and numbers [0-9]

Long options: Can also contain [-_].

Limits: Maximum name length is 100 characters. A maximum 5’000 arguments are supported.

cmd -a -b other # terminates command line option parsing early.

Flags

cmd -a long # Flag definitions are valueless and count occurrences.

Values

cmd -a [value] long [value] # Any text that follows an option without or is considered a value. cmd -a=[value] long=[value] # The alternative syntax is using a , that also allows values starting with .

Boolean definitions accept true/on/yes/enabled and false/off/no/disabled.

Value definitions with OptionFlag::AcceptAsFlag may also occur bare.

Positional arguments

cmd [arg1] [arg2] ... # Any text that does not start with or is considered a positional argument.

Positional arguments, flags, and values can be mixed in any order.

The argument index(es) is stored for every value, allowing advanced apps to reconstruct the order if required.

Modules (“actions”):

- If the option definition contains one or more modules, the command line must start with the module name.

- <strong>no flags and values are allowed before the module name</strong>, except enabled built-in display requests.

(that’s the main difference to common standards, but makes implementation much simpler and safer).

cmd module-name -a long [value] arg1 arg2

Help and Version:

The special <tt>-h</tt>, <tt>–help[=<name>]</tt> and <tt>–version</tt> requests are enabled by default.

Applications can disable the help and version requests individually with <tt>OptionParserFlag</tt> and then reuse their

names for ordinary options.

If one of these flags is encountered, the parsing is stopped and the corresponding action is performed.

Any other, even invalid or unknown options are silently ignored.

No callbacks are made for these flags.

Public Functions

OptionManager()

Create an option manager with an empty options root.

The created root contains built-in help and version options.

explicit OptionManager(OptionsPtr options, const i18n::DisplayTextMapConstPtr &displayText = {})

Create an option manager for an options root.

Parameters:
  • options – The root options definition. If null, parsing behaves as if an empty root was supplied.

  • displayText – The display texts, or the English defaults if null.

inline const OptionsPtr &options() const noexcept

Get the options root.

inline const i18n::DisplayTextMapConstPtr &displayText() const noexcept

Get the display text.

void setDisplayTextMap(i18n::DisplayTextMapConstPtr displayText) noexcept

Change the display text used to build output documents.

Parameters:

displayText – Replacement wording for help, version, and error documents.

OptionResult parse(core::CommandLineArguments &args)

Parse already converted command line arguments.

Calls all registered pre-hooks before parsing. Calls the affected post-hooks after parsing. Returns after successful and erroneous parsing and if --help or --version is encountered. You are responsible to handle displaying help, version, and errors, based on the returned OptionResult. Sensitive option text is replaced in args before this method returns.

Parameters:

args – The mutable command line arguments to parse and mask.

Returns:

The result of the parsing operation.

OptionValuesPtr parseOrThrow(core::CommandLineArguments &args)

Parse already converted command line arguments or throw on error.

Calls all registered pre-hooks before parsing. Calls the affected post-hooks after parsing. Automatically calls displayVersion or displayHelp if the respective option is encountered and returns a null pointer to indicate successful parsing without values. Automatically displays an error document before throwing. Sensitive option text is replaced in args before this method returns.

Parameters:

args – The mutable command line arguments to parse and mask.

Throws:

options::OptionError – If parsing, validation, or a callback fails.

Returns:

The parsed option values or a null pointer if help or version was displayed.

void displayHelp(const text::String &moduleName) const

Display help using the configured renderer.

Help is displayed using the configured renderer. The default renderer writes the output to the terminal or standard output.

Parameters:

moduleName – The name of the module to display help for. Empty for main help.

void displayDetailedHelp(const text::String &moduleName, const text::String &helpName) const

Display detailed help for one option.

Parameters:
  • moduleName – Selected module name, or empty for root search order.

  • helpName – Raw detailed-help target.

void displayModuleOverview() const

Display the reduced module overview.

void displayVersion(const text::String &moduleName) const

Display version information using the configured renderer.

Version is displayed using the configured renderer. The default renderer writes the output to the terminal or standard output.

Parameters:

moduleName – The name of the module to display help for. Empty for main help.

void displayError(const OptionErrorContext &errorContext) const

Display an error message.

The error message is displayed using the configured renderer.

Parameters:

errorContext – Structured parser or validation error details.

text::TextDocument helpDocument(const text::String &moduleName) const

Build the help document.

Parameters:

moduleName – The selected module name, or empty for root help.

Returns:

A neutral document tree that can be rendered as plain text or terminal output.

text::TextDocument detailedHelpDocument(const text::String &moduleName, const text::String &helpName) const

Build detailed help for one option.

Parameters:
  • moduleName – Selected module name, or empty for root search order.

  • helpName – Raw detailed-help target.

Throws:

OptionError – If the target is not a visible option alias.

Returns:

A neutral detailed-help document.

text::TextDocument moduleOverviewDocument() const

Build the reduced module overview.

Returns:

A neutral document with only module usage and visible modules.

text::TextDocument versionDocument(const text::String &moduleName) const

Build the version document.

Parameters:

moduleName – The selected module name, or empty for root version output.

Returns:

A neutral document tree with application version information.

text::TextDocument errorDocument(const OptionErrorContext &errorContext) const

Build an option error document.

Parameters:

errorContext – Structured parser or validation error details.

Returns:

A neutral document tree with the diagnostic message and optional source context.

OptionResult parse(int argc, char *argv[])

Parse UTF-8 encoded command line arguments.

See also

convertCommandLineArguments(int, char**)

Parameters:
  • argc – Argument count from main.

  • argv – UTF-8 encoded argument vector from main.

Returns:

The result of parsing.

OptionResult parse(int argc, wchar_t *argv[])

Parse wide command line arguments.

See also

convertCommandLineArguments(int, wchar_t**)

Parameters:
  • argc – Argument count from wmain.

  • argv – Wide argument vector from wmain.

Returns:

The result of parsing.

OptionValuesPtr parseOrThrow(int argc, char *argv[])

Parse UTF-8 encoded command line arguments or throw on error.

See also

convertCommandLineArguments(int, char**)

Parameters:
  • argc – Argument count from main.

  • argv – UTF-8 encoded argument vector from main.

Throws:

options::OptionError – If parsing, validation, or a callback fails.

Returns:

The parsed option values or null if help/version was displayed.

OptionValuesPtr parseOrThrow(int argc, wchar_t *argv[])

Parse wide command line arguments or throw on error.

See also

convertCommandLineArguments(int, wchar_t**)

Parameters:
  • argc – Argument count from wmain.

  • argv – Wide argument vector from wmain.

Throws:

options::OptionError – If parsing, validation, or a callback fails.

Returns:

The parsed option values or null if help/version was displayed.

Public Static Functions

static core::CommandLineArguments convertCommandLineArguments(int argc, char *argv[])

Convert UTF-8 command line arguments to library strings.

Assumes UTF-8 encoding. Uses tolerant decoding using the replacement character for invalid sequences.

Parameters:
  • argc – Argument count from main.

  • argv – UTF-8 encoded argument vector from main.

Returns:

A converted command-line argument list using Erbsland Core strings.

static core::CommandLineArguments convertCommandLineArguments(int argc, wchar_t *argv[])

Convert wide command line arguments to library strings.

Assumes UTF-16/32 encoding. Uses tolerant decoding using the replacement character for invalid sequences.

Note

This method is designed for Windows processes, that supply wchar_t arguments via main, which is a safer alternative to the more unpredictable char encoding.

Parameters:
  • argc – Argument count from wmain.

  • argv – Wide argument vector from wmain.

Returns:

A converted command-line argument list using Erbsland Core strings.

class OptionModule : public erbsland::options::OptionSetManager

A command line module with its own option sets, callbacks, help metadata, and optional main function.

Modules are selected by the first ordinary command-line argument when an Options root has modules.

Public Functions

OptionModule() = default

Create an empty option module.

explicit OptionModule(const text::String &name)

Create a module with a command line name.

void addSet(OptionSetPtr optionSet)

Add an option set to this module.

Parameters:

optionSet – The set that becomes active when this module is selected.

virtual OptionEditor addOption(std::initializer_list<text::String> names) override

Add an option with one or more names.

virtual OptionEditor editOption(const text::String &name) override

Edit an option selected by one of its names.

inline const text::String &name() const noexcept

Get the command line module name.

void setName(const text::String &name)

Set the command line module name.

Parameters:

name – The selector accepted as the first ordinary argument.

bool hasName(const text::String &name) const

Test if the given name matches this module.

inline const OptionHelp &help() const noexcept

Get the help metadata for this module.

inline void setHelp(OptionHelp help)

Set the complete help metadata for this module.

Parameters:

help – The replacement help metadata. The description is shown in the root module list.

inline void setHelpTitle(text::String title)

Set the help title for this module.

Parameters:

title – Short module title used when no description is available.

inline void setHelpDescription(text::String description)

Set the help description for this module.

Parameters:

description – Description shown for this module and as module-help summary.

inline void setHelpEpilog(text::String epilog)

Set the help epilog for this module.

Parameters:

epilog – Text rendered after module-specific help output.

inline void setHelpVisibility(const OptionHelpVisibility visibility) noexcept

Set the help visibility for this module.

Parameters:

visibility – Controls whether this module appears in root help.

inline const std::vector<OptionSetPtr> &optionSets() const noexcept

Get all option sets.

inline const PreOptionModuleParsingFn &preParsingFn() const noexcept

Get the pre-parsing callback.

inline void setPreParsingFn(PreOptionModuleParsingFn fn)

Set the pre-parsing callback.

inline const PostParsingFn &postParsingFn() const noexcept

Get the post-parsing callback.

inline void setPostParsingFn(PostParsingFn fn)

Set the post-parsing callback.

inline const ModuleMainFn &mainFn() const noexcept

Get the module main function.

inline void setMainFn(ModuleMainFn fn)

Set the module main function.

Parameters:

fn – The function called by Application after this module is parsed successfully.

virtual OptionEditor addOption(const text::String &name)

Add an option with one name.

Parameters:

name – The command-line name, lookup alias, or positional argument name.

Returns:

An editor for the newly created option.

virtual OptionEditor addOption(std::initializer_list<text::String> names) = 0

Add an option with one or more names.

Parameters:

names – Command-line names and lookup aliases.

Returns:

An editor for the newly created option.

Public Static Functions

static OptionModulePtr create()

Create an empty shared module.

Returns:

A shared module without a command-line name.

static OptionModulePtr create(const text::String &name)

Create a shared module with a command line name.

Parameters:

name – The module selector accepted on the command line.

Returns:

A shared module with the given selector.

static bool isValidName(const text::String &name) noexcept

Test if a module name is valid.

Parameters:

name – The module selector to validate.

Returns:

true if the name can be used as a module selector.

enum class erbsland::options::OptionParserFlag : uint8_t

Flags that customize the command-line parser.

Values:

enumerator None

No flags.

enumerator DisableHelp

Disable the built-in -h and --help request.

enumerator DisableVersion

Disable the built-in --version request.

enumerator NoHelpDetails

Disable detailed help and treat --help as a pure flag.

enumerator ErrorOnEmptyRequiredPositionals

Report missing required positional arguments on an empty command.

enumerator ErrorOnMissingModule

Report a missing module instead of displaying the module overview.

enumerator All

All flags.

using erbsland::options::OptionParserFlags = util::EnumFlags<OptionParserFlag>

A set of command-line parser flags.

class OptionResult

The result of processing command line arguments.

parse() returns this object for every outcome, including successful parsing, help/version requests, and errors.

Public Functions

OptionResult() = default

Create an empty parse result.

inline const OptionValuesPtr &values() const noexcept

Get the parsed values.

inline void setValues(OptionValuesPtr values) noexcept

Set the parsed values.

Parameters:

values – Parsed values associated with this result.

inline OptionResultStatus status() const noexcept

Get the result status.

inline void setStatus(const OptionResultStatus status) noexcept

Set the result status.

Parameters:

status – New parser status.

inline const text::String &helpName() const noexcept

Get the detailed-help target name, or an empty string for ordinary help.

inline void setHelpName(text::String helpName)

Set the detailed-help target name.

inline const std::optional<OptionErrorContext> &errorContext() const noexcept

Access the error context.

Returns:

Structured error context when status() is OptionResultStatus::Error.

inline void setErrorContext(std::optional<OptionErrorContext> errorContext) noexcept

Set the error context.

Parameters:

errorContext – Error context for a failed parse, or empty for non-error results.

inline const OptionSensitiveTextLocations &sensitiveTextLocations() const noexcept

Get the command-line locations that contained sensitive text.

Locations are available for successful, display-request, and error results.

Returns:

The sensitive suffix locations in parsing order.

enum class erbsland::options::OptionResultStatus

The status of option processing.

Values:

enumerator Success

Parsing succeeded.

enumerator DisplayVersion

The version should be displayed.

enumerator DisplayHelp

Help should be displayed.

enumerator DisplayModuleOverview

The reduced module overview should be displayed.

enumerator Error

Parsing failed.

class Options : public erbsland::options::OptionSetManager

Root configuration object for command line options, global option sets, built-ins, and modules.

Public Functions

Options()

Create an options root with its built-in option sets.

void addSet(OptionSetPtr optionSet)

Add a main option set.

Parameters:

optionSet – The global option set to activate for root parsing and every selected module.

void addModule(OptionModulePtr optionModule)

Add an option module.

Parameters:

optionModule – The module that can be selected as the first ordinary command-line argument.

virtual OptionEditor addOption(std::initializer_list<text::String> names) override

Add an option with one or more names.

virtual OptionEditor editOption(const text::String &name) override

Edit an option selected by one of its names.

inline const OptionHelp &help() const noexcept

Get the help metadata for the options root.

inline void setHelp(OptionHelp help)

Set the complete help metadata for the options root.

Parameters:

help – The replacement help metadata. The description becomes the root help summary.

inline void setHelpTitle(text::String title)

Set the help title for the options root.

Parameters:

title – Root title used by renderers that expose title text.

inline void setHelpDescription(text::String description)

Set the help description for the options root.

Parameters:

description – Summary paragraph shown before generated root help.

inline void setHelpEpilog(text::String epilog)

Set the help epilog for the options root.

Parameters:

epilog – Text rendered after root help output.

inline void setHelpVisibility(const OptionHelpVisibility visibility) noexcept

Set the help visibility for the options root.

Parameters:

visibility – Root help visibility metadata for custom renderers.

inline const text::String &executablePath() const noexcept

Get the unprocessed executable path from the command line.

void setExecutablePath(text::String executablePath)

Set the unprocessed executable path from the command line.

Parameters:

executablePath – The original argv[0] text. The executable name is extracted for usage output.

inline const text::String &executableName() const noexcept

Get the extracted executable name.

inline const core::ApplicationInfo &applicationInfo() const noexcept

Get the application metadata.

inline void setApplicationInfo(core::ApplicationInfo applicationInfo)

Set the application metadata.

inline const std::vector<OptionModulePtr> &optionModules() const noexcept

Get all option modules.

inline const OptionSetPtr &builtInOptionSet() const noexcept

Get the built-in option set.

inline const std::vector<OptionSetPtr> &optionSets() const noexcept

Get all main option sets.

inline OptionParserFlags parserFlags() const noexcept

Get the command-line parser flags.

inline void setParserFlags(OptionParserFlags flags) noexcept

Replace the command-line parser flags.

Parameters:

flags – The new parser flags.

inline void setParserFlag(OptionParserFlag flag) noexcept

Enable one command-line parser flag.

Parameters:

flag – The flag to enable.

inline void clearParserFlag(OptionParserFlag flag) noexcept

Disable one command-line parser flag.

Parameters:

flag – The flag to disable.

virtual OptionEditor addOption(const text::String &name)

Add an option with one name.

Parameters:

name – The command-line name, lookup alias, or positional argument name.

Returns:

An editor for the newly created option.

virtual OptionEditor addOption(std::initializer_list<text::String> names) = 0

Add an option with one or more names.

Parameters:

names – Command-line names and lookup aliases.

Returns:

An editor for the newly created option.

Public Static Functions

static OptionsPtr create()

Create an empty shared options root.

Returns:

A shared options root with the built-in help and version options.

class OptionSensitiveTextLocation

The location of sensitive text in one command-line argument.

Sensitive text extends from startIndex() through the end of the argument.

Public Functions

OptionSensitiveTextLocation() = default

Create an empty location.

inline OptionSensitiveTextLocation(unit::ArgumentIndex argumentIndex, unit::ByteIndex startIndex) noexcept

Create a sensitive-text location.

Parameters:
  • argumentIndex – The command-line argument containing the sensitive suffix.

  • startIndex – The UTF-8 byte index where the sensitive suffix starts.

bool operator==(const OptionSensitiveTextLocation&) const noexcept = default

Compare two locations.

inline unit::ArgumentIndex argumentIndex() const noexcept

Get the command-line argument index.

Returns:

The argument index, or ArgumentIndex::noIndex() for an empty location.

inline unit::ByteIndex startIndex() const noexcept

Get the UTF-8 byte index where sensitive text starts.

Returns:

The start byte index, or ByteIndex::noIndex() for an empty location.

using erbsland::options::OptionSensitiveTextLocations = std::vector<OptionSensitiveTextLocation>

A list of sensitive command-line text locations.

class OptionSet : public erbsland::options::OptionSetManager

A set of options with its own help grouping, flags, and parsing callbacks.

The parser can combine multiple enabled sets for parsing while still invoking each set’s callbacks separately.

Public Functions

OptionSet() = default

Create an empty option set.

void addOption(OptionPtr option)

Add an existing option to this set.

Parameters:

option – The option to append. Null pointers are stored as-is and ignored by parser/display code.

virtual OptionEditor addOption(std::initializer_list<text::String> names) override

Add an option with one or more names.

virtual OptionEditor editOption(const text::String &name) override

Edit an option selected by one of its names.

inline const OptionHelp &help() const noexcept

Get the help metadata for this set.

inline void setHelp(OptionHelp help)

Set the complete help metadata for this set.

Parameters:

help – The replacement help metadata. A non-empty title becomes the help group title.

inline void setHelpTitle(text::String title)

Set the help title for this set.

Parameters:

title – Group title used in generated help output.

inline void setHelpDescription(text::String description)

Set the help description for this set.

Parameters:

description – Description for renderers that expose set-level help text.

inline void setHelpEpilog(text::String epilog)

Set the help epilog for this set.

Parameters:

epilog – Optional trailing text for renderers that expose set-level epilogs.

inline void setHelpVisibility(const OptionHelpVisibility visibility) noexcept

Set the help visibility for this set.

Parameters:

visibility – Controls whether options in this set are visible in generated help output.

inline const std::vector<OptionPtr> &options() const noexcept

Get all options in this set.

inline OptionFlags flags() const noexcept

Get the set flags.

inline void setFlags(OptionFlags flags) noexcept

Set the set flags.

Parameters:

flags – The replacement flags. OptionFlag::Disabled removes the whole set from parsing and help.

inline const PreOptionSetParsingFn &preParsingFn() const noexcept

Get the pre-parsing callback.

inline void setPreParsingFn(PreOptionSetParsingFn fn)

Set the pre-parsing callback.

inline const PostParsingFn &postParsingFn() const noexcept

Get the post-parsing callback.

inline void setPostParsingFn(PostParsingFn fn)

Set the post-parsing callback.

virtual OptionEditor addOption(const text::String &name)

Add an option with one name.

Parameters:

name – The command-line name, lookup alias, or positional argument name.

Returns:

An editor for the newly created option.

virtual OptionEditor addOption(std::initializer_list<text::String> names) = 0

Add an option with one or more names.

Parameters:

names – Command-line names and lookup aliases.

Returns:

An editor for the newly created option.

Public Static Functions

static OptionSetPtr create()

Create an empty shared option set.

Returns:

A shared option set with no options, default help visibility, and no callbacks.

class OptionSetManager

A common interface for objects that can own option definitions.

Options, OptionSet, and OptionModule all implement this interface so option registration can use the same fluent addOption() and editOption() calls.

Subclassed by erbsland::options::OptionModule, erbsland::options::OptionSet, erbsland::options::Options

Public Functions

OptionSetManager() = default

Create an empty option-set manager.

virtual ~OptionSetManager() = default

Destroy the option-set manager polymorphically.

OptionSetManager(const OptionSetManager&) = default

Copy the option-set manager base state.

OptionSetManager &operator=(const OptionSetManager&) = default

Copy-assign the option-set manager base state.

OptionSetManager(OptionSetManager&&) = default

Move the option-set manager base state.

OptionSetManager &operator=(OptionSetManager&&) = default

Move-assign the option-set manager base state.

virtual OptionEditor addOption(const text::String &name)

Add an option with one name.

Parameters:

name – The command-line name, lookup alias, or positional argument name.

Returns:

An editor for the newly created option.

virtual OptionEditor addOption(std::initializer_list<text::String> names) = 0

Add an option with one or more names.

Parameters:

names – Command-line names and lookup aliases.

Returns:

An editor for the newly created option.

virtual OptionEditor editOption(const text::String &name) = 0

Edit an existing option by name.

Parameters:

name – Any configured name or lookup alias of the option to edit.

Returns:

An editor for the option, or an invalid editor if no option was found.

class OptionType

The value type accepted by an option.

The parser stores values according to this type and the option maximum. Flags count occurrences; Boolean, integer, and text options store one value or a list; choice options store the configured choice text that matched the argument.

Public Types

enum Type

The supported option types.

Values:

enumerator Flag

A valueless switch whose occurrences are counted.

enumerator Boolean

A boolean value argument.

enumerator Integer

A signed decimal integer argument.

enumerator Text

An arbitrary text argument.

enumerator SensitiveText

A single sensitive text argument stored in protected memory.

enumerator Choice

A text argument that must match one configured OptionChoice.

Public Functions

constexpr OptionType() noexcept = default

Create a flag option type.

inline constexpr OptionType(const Type type) noexcept

Create an option type from a raw type value.

Parameters:

type – The raw type value to store.

constexpr bool operator==(const OptionType &other) const noexcept = default

Compare two option types.

inline constexpr bool operator==(Type type) const noexcept

Compare this option type with a raw type.

inline constexpr Type type() const noexcept

Get the raw option type.

Returns:

The raw type value.

inline void setType(Type type) noexcept

Set the raw option type.

Parameters:

type – The new type value.

text::String toString() const

Convert the option type to a text representation.

Returns:

A stable lowercase name for diagnostics and generated help.

class OptionValue

A single parsed command line option value.

Values keep the parsed storage, an optional weak reference to the source option, and the original argument indexes that produced the value.

Public Functions

OptionValue() = default

Create an empty option value.

explicit OptionValue(OptionValueStorage storage)

Create an option value.

Parameters:

storage – Parsed value storage.

OptionValue(OptionValueStorage storage, std::vector<unit::ArgumentIndex> argumentIndexes)

Create an option value with source argument indexes.

Parameters:
  • storage – Parsed value storage.

  • argumentIndexes – Source argument indexes that produced this value.

OptionValue(OptionWeakPtr option, OptionValueStorage storage)

Create an option value with its source option.

Parameters:
  • option – Source option definition.

  • storage – Parsed value storage.

OptionValue(OptionWeakPtr option, OptionValueStorage storage, std::vector<unit::ArgumentIndex> argumentIndexes)

Create an option value with its source option and argument indexes.

Parameters:
  • option – Source option definition.

  • storage – Parsed value storage.

  • argumentIndexes – Source argument indexes that produced this value.

inline const OptionWeakPtr &option() const noexcept

Get the source option.

inline void setOption(OptionWeakPtr option) noexcept

Set the source option.

Parameters:

option – Source option definition.

inline const OptionValueStorage &storage() const noexcept

Get the stored value.

inline void setStorage(OptionValueStorage storage)

Set the stored value.

Parameters:

storage – Replacement parsed value storage.

inline const std::vector<unit::ArgumentIndex> &argumentIndexes() const noexcept

Get the source argument indexes.

unit::ArgumentIndex argumentIndex() const noexcept

Get the first source argument index.

Returns:

The first source argument index, or an empty index if no index is stored.

inline void setArgumentIndexes(std::vector<unit::ArgumentIndex> argumentIndexes)

Set the source argument indexes.

Parameters:

argumentIndexes – Replacement source argument indexes.

unit::ArgumentCount flagCount() const noexcept

Get the number of source occurrences for a flag value.

Returns:

The number of stored argument indexes for flag storage.

unit::ArgumentCount valueCount() const noexcept

Get the number of stored values.

Returns:

One for scalar storage, the list length for list storage, or the flag occurrence count for flags.

OptionValueType type() const noexcept

Get the concrete value type.

Returns:

The concrete storage type.

bool getFlag(bool defaultFlag = false) const

Read a flag value.

Parameters:

defaultFlag – Returned when this value is not flag storage.

Returns:

The flag value.

bool getBoolean(bool defaultBoolean = false) const

Read a boolean value.

Parameters:

defaultBoolean – Returned when this value is not boolean storage.

Returns:

The boolean value.

std::vector<bool> getBooleanList(std::vector<bool> defaultBooleanList = {}) const

Read a boolean list value.

Parameters:

defaultBooleanList – Returned when this value is not boolean or boolean-list storage.

Returns:

The boolean values.

OptionInteger getInteger(OptionInteger defaultInteger = 0) const

Read an integer value.

Parameters:

defaultInteger – Returned when this value is not integer storage.

Returns:

The integer value.

text::String getText(const text::String &defaultText = {}) const

Read a text value.

Parameters:

defaultText – Returned when this value is not text storage.

Returns:

The text or choice value.

text::StringList getTextList(text::StringList defaultTextList = {}) const

Read a text list value.

Parameters:

defaultTextList – Returned when this value is not text-list storage.

Returns:

The text values.

std::vector<OptionInteger> getIntegerList(std::vector<OptionInteger> defaultIntegerList = {}) const

Read an integer list value.

Parameters:

defaultIntegerList – Returned when this value is not integer-list storage.

Returns:

The integer values.

Public Static Functions

static OptionValuePtr create(OptionValueStorage storage)

Create a shared option value.

Parameters:

storage – Parsed value storage.

Returns:

A shared parsed value.

static OptionValuePtr create(OptionValueStorage storage, std::vector<unit::ArgumentIndex> argumentIndexes)

Create a shared option value with source argument indexes.

Parameters:
  • storage – Parsed value storage.

  • argumentIndexes – Source argument indexes that produced this value.

Returns:

A shared parsed value.

static OptionValuePtr create(OptionWeakPtr option, OptionValueStorage storage)

Create a shared option value with its source option.

Parameters:
  • option – Source option definition.

  • storage – Parsed value storage.

Returns:

A shared parsed value.

static auto create(OptionWeakPtr option, OptionValueStorage storage, std::vector<unit::ArgumentIndex> argumentIndexes) -> OptionValuePtr

Create a shared option value with its source option and argument indexes.

Parameters:
  • option – Source option definition.

  • storage – Parsed value storage.

  • argumentIndexes – Source argument indexes that produced this value.

Returns:

A shared parsed value.

class OptionValueNameHash

Hash helper for option value lookup names.

Public Functions

inline std::size_t operator()(const text::String &name) const

Hash an option value lookup name.

class OptionValues

A set of parsed command line option values.

Each accepted lookup name maps to the same parsed value instance. For example, an option registered as {"--verbose", "verbose"} can be read through either name.

Public Functions

OptionValues() = default

Create an empty parsed option-value set.

void setValue(const text::String &name, OptionValuePtr value)

Set a value for one lookup name.

Parameters:
  • name – Lookup name to associate with the value.

  • value – Parsed value pointer. Null pointers are stored as-is and behave like absent values in typed getters.

void setValue(std::initializer_list<text::String> names, OptionValuePtr value)

Set a value for multiple lookup names.

Parameters:
  • names – Lookup names that shall all resolve to the same value.

  • value – Parsed value pointer.

inline const text::String &moduleName() const noexcept

Get the selected module name.

inline void setModuleName(text::String moduleName)

Set the selected module name.

Parameters:

moduleName – The module name selected on the command line, or empty for root parsing.

inline const OptionModulePtr &module() const noexcept

Get the selected module.

inline void setModule(OptionModulePtr module) noexcept

Set the selected module.

Parameters:

module – The selected module object, or null for root parsing.

unit::ArgumentCount valueCount(const text::String &name) const

Get the number of values stored for a lookup name.

Parameters:

name – Lookup name to inspect.

Returns:

The number of stored scalar or list values. Flag storage reports one.

OptionValuePtr value(const text::String &name) const

Get the parsed value for a lookup name.

Parameters:

name – Lookup name to inspect.

Returns:

The parsed value, or null if the name was not present and no default was stored.

inline const std::unordered_map<text::String, OptionValuePtr, OptionValueNameHash> &values() const noexcept

Get all mapped values.

bool getFlag(const text::String &name, bool defaultFlag = false) const

Read a flag value.

Parameters:
  • name – Lookup name to read.

  • defaultFlag – Returned when the name is absent or not a flag.

Returns:

True only for flag-marker storage, otherwise the fallback.

unit::ArgumentCount getFlagCount(const text::String &name, unit::ArgumentCount defaultCount = {}) const

Read the number of source occurrences for a flag value.

Parameters:
  • name – Lookup name to read.

  • defaultCount – Returned when the name is absent or not a flag.

Returns:

The number of flag occurrences.

bool getBoolean(const text::String &name, bool defaultBoolean = false) const

Read a boolean value.

Parameters:
  • name – Lookup name to read.

  • defaultBoolean – Returned when the name is absent or not Boolean storage.

Returns:

The stored Boolean scalar or fallback.

std::vector<bool> getBooleanList(const text::String &name, std::vector<bool> defaultBooleanList = {}) const

Read a boolean list value.

Parameters:
  • name – Lookup name to read.

  • defaultBooleanList – Returned when the name is absent or not Boolean scalar/list storage.

Returns:

The stored Boolean list, or a one-element list for scalar storage.

OptionInteger getInteger(const text::String &name, OptionInteger defaultInteger = 0) const

Read an integer value.

Parameters:
  • name – Lookup name to read.

  • defaultInteger – Returned when the name is absent or not an integer.

Returns:

The stored integer value.

text::String getText(const text::String &name, const text::String &defaultText = {}) const

Read a text value.

Parameters:
  • name – Lookup name to read.

  • defaultText – Returned when the name is absent or not text/choice storage.

Returns:

The stored text or choice value.

text::StringList getTextList(const text::String &name, text::StringList defaultTextList = {}) const

Read a text list value.

Parameters:
  • name – Lookup name to read.

  • defaultTextList – Returned when the name is absent or not a text list.

Returns:

The stored text values.

auto getIntegerList(const text::String &name, std::vector<OptionInteger> defaultIntegerList = {}) const -> std::vector<OptionInteger>

Read an integer list value.

Parameters:
  • name – Lookup name to read.

  • defaultIntegerList – Returned when the name is absent or not an integer list.

Returns:

The stored integer values.

Public Static Functions

static OptionValuesPtr create()

Create an empty shared value set.

Returns:

A shared value set without selected module or parsed values.

using erbsland::options::OptionValueStorage = std::variant<std::monostate, bool, std::vector<bool>, OptionInteger, std::vector<OptionInteger>, text::String, text::StringList>

Storage for a parsed option value or default value.

Sensitive text is stored as a marked scalar string and never as a list or default value.

enum class erbsland::options::OptionValueType

The concrete storage type of an option value.

Values:

enumerator Flag

A valueless flag occurrence.

enumerator Boolean

A single boolean value.

enumerator BooleanList

A list of boolean values.

enumerator Integer

A single integer value.

enumerator IntegerList

A list of integer values.

enumerator Text

A single text value.

enumerator TextList

A list of text values.

enumerator SensitiveText

A single protected sensitive text value.