ddn.util.docopt

Command-line interface description language parser.

This module provides an idiomatic D implementation of the docopt command-line interface description language parser, based on the Python docopt package (https://github.com/docopt/docopt).

Docopt parses command-line arguments based on a help message that you write for your program. The help message defines the interface, and docopt parses the arguments accordingly.

Example:

import ddn.util.docopt;

enum DOC = "Usage: prog [options] <file>

Options:
 -h --help     Show this help
 -v --verbose  Be verbose
";

void main(string[] args) {
  auto arguments = docopt(DOC, args[1..$]);
  if (arguments["--verbose"].isTrue) {
     writeln("Verbose mode enabled");
  }
}

Types 20

classDocoptLanguageError : Exception

Exception thrown when there is an error in the docopt language definition.

This exception indicates a problem with the documentation string itself, such as missing "usage:" section or malformed patterns.

Constructors
this(string msg, string file = __FILE__, size_t line = __LINE__)Constructs a DocoptLanguageError with the given message.
classDocoptExitHelp : Exception

Exception thrown when the user requests help via --help flag.

This exception is thrown when the parsed arguments contain --help, allowing the application to display help and exit gracefully.

Constructors
this(string msg, string file = __FILE__, size_t line = __LINE__)Constructs a DocoptExitHelp with the help text.
classDocoptArgumentError : Exception

Exception thrown when there is an error in the command-line arguments.

This exception indicates that the user provided invalid arguments that do not match the expected pattern defined in the usage string.

Fields
private string _expected
private string _got
private size_t _position
private string[] _argv
Methods
string expected() const @safe pure nothrow @nogcReturns the expected description stored with this error.
string got() const @safe pure nothrow @nogcReturns the offending token or input stored with this error.
size_t position() const @safe pure nothrow @nogcReturns the position (0-based index) in argv where mismatch occurred. If unknown, this may be 0 or a sentinel depending on the throw site.
const(string[]) argv() const @safe pure nothrow @nogcReturns the snapshot of argv for additional context.
private string formatMessage(string expected, string got, size_t pos, const string[] argv) @safeHelper to format a contextual error message.
Constructors
this(string msg, string file = __FILE__, size_t line = __LINE__)Constructs a DocoptArgumentError with the given message.
this(string expected, string got, size_t position, const string[] argv, string file = __FILE__, size_t line = __LINE__)Constructs a DocoptArgumentError with contextual information.
structArgValue

Represents a value parsed from command-line arguments.

ArgValue can hold different types of values:

  • Boolean (for flags)
  • String (for arguments with values)
  • Long integer (for counting repeated options and numeric values)
  • Double-precision floating point (for numeric values)
  • List of strings (for repeated arguments)
  • Null (for missing optional arguments)
Fields
private Type _type
private bool _bool
private string _string
private long _long
private double _double
private string[] _list
Methods
Type type() const @safe pure nothrow @nogcReturns the type of value stored.
bool isTrue() const @safe pure nothrow @nogcChecks if this value represents a "true" condition.
bool isNull() const @safe pure nothrow @nogcChecks if this value is null/none.
bool asBool() const @safe pure nothrow @nogcReturns the value as a boolean.
string asString() const @safe pure nothrow @nogcReturns the value as a string.
int asInt() const @safe pure nothrow @nogcReturns the value as a 32-bit integer.
long asLong() const @safe pure nothrow @nogcReturns the value as a 64-bit integer.
double asDouble() const @safe pure nothrow @nogcReturns the value as a double-precision floating point number.
float asFloat() const @safe pure nothrow @nogcReturns the value as a single-precision floating point number.
const(string[]) asList() const @safe pure nothrow @nogcReturns the value as a list of strings.
T as(T)() if (is(T == string) || is(T == bool) || is(T == int) || is(T == long) || is(T == double) || is(T == float) || is( T == const(string[]))) const @safe pure nothrow @nogcReturns the value converted to the specified type.
T opCast(T)() if (is(T == string) || is(T == bool) || is(T == int) || is(T == long) || is(T == double) || is(T == float) || is( T == const(string[])) || is(T == ArgValue)) const @safe pure nothrow @nogcExplicitly casts this `ArgValue` to the requested type using `cast(T)`.
bool opEquals(const ArgValue rhs) const @safe pure nothrow @nogcCompares this value to another `ArgValue` for equality.
bool opEquals(string rhs) const @safe pure nothrow @nogcCompares this `ArgValue` with a string for equality.
bool opEquals(bool rhs) const @safe pure nothrow @nogcCompares this `ArgValue` with a boolean for equality.
bool opEquals(int rhs) const @safe pure nothrow @nogcCompares this `ArgValue` with a 32-bit integer for equality.
bool opEquals(long rhs) const @safe pure nothrow @nogcCompares this `ArgValue` with a long integer for equality.
bool opEquals(double rhs) const @safe pure nothrow @nogcCompares this `ArgValue` with a double for equality.
bool opEquals(const(string[]) rhs) const @safe pure nothrow @nogcCompares this `ArgValue` with a list of strings for equality.
size_t toHash() const @safe pure nothrowComputes a hash value for this `ArgValue`.
string toString() const @safeConverts the value to a string representation.
Constructors
this(bool b)Constructs an ArgValue from a boolean.
this(string s)Constructs an ArgValue from a string.
this(long i)Constructs an ArgValue from a 64-bit integer.
this(int i)Constructs an ArgValue from a 32-bit integer.
this(double d)Constructs an ArgValue from a double-precision floating point value.
this(float f)Constructs an ArgValue from a single-precision floating point value.
this(string[] l)Constructs an ArgValue from a list of strings.
Nested Templates
NoneMarker type representing the absence of a value.
TypeThe type of value stored in this ArgValue.
aliasArgMap = ArgValue[string]

Type alias for the argument map returned by docopt.

Maps argument names (like "--verbose", "<file>", "command") to their values.

classPattern

Base class for all pattern types in the docopt pattern tree.

Patterns form a tree structure that represents the command-line interface grammar. Leaf patterns represent actual arguments/options, while branch patterns represent groupings and structure.

Methods
Pattern[] flat(TypeInfo[] types...)Returns a flat array of all leaf patterns of the specified types.
Tuple!(bool, Pattern[], Pattern[]) match(Pattern[] left, Pattern[] collected = null)Attempts to match this pattern against a list of parsed arguments.
Pattern fix()Fixes the pattern tree by unifying identical patterns and setting up repeating argument handling.
void fixIdentities(Pattern[] uniq = null)Makes pattern-tree tips point to the same object if they are equal.
void fixRepeatingArguments()Fixes elements that should accumulate/increment values.
string name() const @safeReturns the name of this pattern element.
bool opEquals(Object other) const @safeCompares patterns for equality based on their string representation.
size_t toHash() const @trusted nothrowComputes hash based on string representation.
string toStringImpl() const @safeInternal string representation method that can be called on const objects.

Leaf/terminal node of a pattern tree.

LeafPattern represents actual command-line elements like arguments, commands, and options. These are the terminal nodes that don't have children.

Fields
string _name
ArgValue _value
size_t _sourceIndexSource index in argv for this leaf, if it originates from argv tokens. Defaults to size_t.max when not applicable (e.g., pattern nodes).
Methods
string name() const @safeReturns the name of this pattern element.
ArgValue value() @safe pure nothrow @nogcGets the value of this pattern element.
ArgValue valueConst() const @safe pure nothrow @nogcGets the value of this pattern element (const version).
size_t sourceIndex() const @safe pure nothrow @nogcReturns the 0-based argv index from which this pattern was parsed. If not set, returns size_t.max.
void setSourceIndex(size_t idx) @safe pure nothrow @nogcSets the 0-based argv index for this leaf pattern.
void setValue(ArgValue v)Sets the value of this pattern element.
Pattern[] flat(TypeInfo[] types...)Returns a flat array containing just this pattern if it matches the types.
Tuple!(int, LeafPattern) singleMatch(Pattern[] left)Finds a single match for this pattern in the left array.
Tuple!(bool, Pattern[], Pattern[]) match(Pattern[] left, Pattern[] collected = null)Attempts to match this pattern against a list of parsed arguments.
string toString() constReturns a string representation of this pattern.
string toStringImpl() constInternal string representation for const access.
Constructors
this(string name, ArgValue value = ArgValue.init)Constructs a LeafPattern with a name and optional value.

Represents a positional argument in the command-line interface.

Arguments are specified in angle brackets like <name> or as UPPER_CASE identifiers in the usage pattern.

Methods
Tuple!(int, LeafPattern) singleMatch(Pattern[] left)Finds a single match for this argument in the left array.
Argument parse(string source)Parses an argument from a source string.
Constructors
this(string name, ArgValue value = ArgValue.init)Constructs an Argument with a name and optional value.

Represents a command word in the command-line interface.

Commands are literal words that must be matched exactly, like "ship", "mine", "set", "remove" in a usage pattern.

Methods
Tuple!(int, LeafPattern) singleMatch(Pattern[] left)Finds a single match for this command in the left array.
Constructors
this(string name, ArgValue value = ArgValue(false))Constructs a Command with a name and optional value.

Represents a command-line option (flag).

Options can have short form (-v), long form (--verbose), or both. They may also accept an argument value.

Fields
private string _short
private string _long
private int _argCount
Methods
string shortName() constReturns the short form of this option.
string longName() constReturns the long form of this option.
int argCount() constReturns the argument count for this option.
string name() constReturns the canonical name of this option.
Tuple!(int, LeafPattern) singleMatch(Pattern[] left)Finds a single match for this option in the left array.
string toString() constReturns a string representation of this option.
string toStringImpl() constInternal string representation for const access.
Option parse(string optionDescription)Parses an option from a description line.
Constructors
this(string short_, string long_, int argCount = 0, ArgValue value = ArgValue.init)Constructs an Option with short/long forms and argument count.
private structResolvedDefault

Result of resolving a default specification that may reference an environment variable.

When parsing [default: ...] specifications, we support the extended syntax $VARNAME or fallback, where the value of environment variable VARNAME is used if set and non-empty; otherwise the literal fallback is used. If only $VARNAME is provided and the variable is not set (or empty), then the default is considered not present.

Fields
bool presentWhether a default value is present after resolution.
string valueThe resolved default value (valid only when `present` is true).

Branch/inner node of a pattern tree.

BranchPattern represents groupings of patterns like Required, Optional, Either, etc. These patterns have children and define how those children should be matched.

Fields
Pattern[] childrenThe child patterns contained in this branch.
Methods
Pattern[] flat(TypeInfo[] types...)Returns a flat array of all leaf patterns of the specified types.
void fixIdentities(Pattern[] uniq = null)Makes pattern-tree tips point to the same object if they are equal.
void fixRepeatingArguments()Fixes elements that should accumulate/increment values.
string toString() constReturns a string representation of this branch pattern.
string toStringImpl() constInternal string representation for const access.
Constructors
this(Pattern[] children...)Constructs a BranchPattern with the given children.

Represents a required sequence of patterns.

All children must match in order for Required to match. This is the implicit grouping for patterns not in brackets.

Methods
Tuple!(bool, Pattern[], Pattern[]) match(Pattern[] left, Pattern[] collected = null)Attempts to match all children in sequence.
Constructors
this(Pattern[] children...)Constructs a Required pattern with the given children.

Represents an optional sequence of patterns.

Children may or may not match. Corresponds to patterns in square brackets.

Methods
Tuple!(bool, Pattern[], Pattern[]) match(Pattern[] left, Pattern[] collected = null)Attempts to match children, but always succeeds.
Constructors
this(Pattern[] children...)Constructs an Optional pattern with the given children.

Marker/placeholder for [options] shortcut in usage patterns.

This is expanded to include all options defined in the Options section that are not explicitly mentioned in the usage pattern.

Constructors
this(Pattern[] children...)Constructs an OptionsShortcut with the given children.

Represents one or more occurrences of a pattern.

Corresponds to patterns followed by "..." in the usage pattern.

Methods
Tuple!(bool, Pattern[], Pattern[]) match(Pattern[] left, Pattern[] collected = null)Attempts to match the child pattern one or more times.
Constructors
this(Pattern[] children...)Constructs a OneOrMore pattern with the given child.

Represents mutually exclusive alternatives.

Corresponds to patterns separated by "|" in the usage pattern.

Methods
Tuple!(bool, Pattern[], Pattern[]) match(Pattern[] left, Pattern[] collected = null)Attempts to match one of the alternative patterns.
Constructors
this(Pattern[] children...)Constructs an Either pattern with the given alternatives.
classTokens

Tokenizer for parsing docopt patterns and arguments.

Tokens splits input strings into individual tokens and provides methods to iterate through them during parsing.

Fields
private string[] _tokens
private bool _isParsingPattern
private string[] _original
private size_t _consumed
Methods
Tokens fromPattern(string source)Creates a Tokens instance for parsing a usage pattern.
string move()Removes and returns the first token.
string current() constReturns the current (first) token without removing it.
string[] getTokens() constReturns the remaining tokens as an array.
string[] originalTokens() constReturns the original snapshot of tokens provided to this tokenizer.
size_t consumedCount() constReturns how many tokens were consumed so far (position index).
size_t length() constReturns the number of remaining tokens.
bool empty() constChecks if there are no more tokens.
bool isParsingPattern() constReturns whether this tokenizer is parsing a pattern.
void error(string message) constThrows an appropriate error based on parsing mode.
Constructors
this(string source, bool isParsingPattern = false)Constructs a Tokens instance from a string or string array.
this(string[] source, bool isParsingPattern = false)ditto

Lightweight compile-time representation of an option specification.

This type is used by the CTFE parsing API to carry extracted option declarations from the Options: section without allocating runtime class instances at compile time. It is later converted to runtime Option objects when invoking docopt with a pre-parsed descriptor.

Fields
string shortNameShort option name (e.g. "-v"), or `null` if not present.
string longNameLong option name (e.g. "--verbose"), or `null` if not present.
int argcountNumber of required arguments (0 or 1).
string defaultValueDefault value string if provided via `[default: ...]`, else empty.
structCtfeDoc

Compile-time parsed descriptor for a docopt document.

Fields are simple POD so they can be produced entirely at CTFE.

See also: parseDocopt template and docopt(CtfeDoc) overload.

Fields
string usageSectionRaw `Usage:` section (single block) as extracted.
string formalFormal usage string derived from the `Usage:` section.
CtfeOptionSpec[] optionsExtracted option specifications from the `Options:` section.

Functions 24

fnT get(T)(const ref ArgMap args, string key, auto ref T defaultValue) if (is(T == string) || is(T == bool) || is(T == int) || is(T == long) || is(T == double) || is(T == float) || is( T == const(string[])))Retrieves a value from the argument map with a default fallback.
private fnResolvedDefault resolveEnvDefault(string spec) @safeResolves a default value specification possibly referencing an environment variable.
fnEither transform(Pattern pattern)Expands a pattern into an (almost) equivalent one with a single Either at top.
private fnstring ctfeFindSection(string name, string source) @safe pureExtracts a section block (e.g. "usage:" or "options:") from a doc string.
private fnstring ctfeFormalFromUsage(string usageSection) @safe pureCreates a very simple formal usage string from a `Usage:` section.
private fnCtfeOptionSpec[] ctfeParseOptions(string optionsSection) @safe pureParses the `Options:` section into a list of `CtfeOptionSpec`.
private fnCtfeDoc ctfeParseDocopt(string doc) @safe pureCompile-time docopt parser that extracts `Usage:` and `Options:`.
private fnOption[] buildOptionsFromCtfe(const CtfeOptionSpec[] specs)Builds runtime `Option` objects from CTFE specs.
fnArgMap docopt(CtfeDoc parsed, string[] argv, bool help = true, string versn = null, bool optionsFirst = false)Overload of `docopt` that accepts a compile-time parsed descriptor.
fnPattern[] parseLong(Tokens tokens, ref Option[] options)Parses a long option from the token stream.
fnPattern[] parseShorts(Tokens tokens, ref Option[] options)Parses short option(s) from the token stream.
fnPattern[] parseExpr(Tokens tokens, ref Option[] options)
fnPattern[] parseSeq(Tokens tokens, ref Option[] options)
fnPattern[] parseAtom(Tokens tokens, ref Option[] options)Parses a single atom from the token stream.
private fnbool isUpperString(string s)Checks if a string is all uppercase letters.
fnPattern[] parseSeq(Tokens tokens, ref Option[] options)Parses a sequence of atoms from the token stream.
fnPattern[] parseExpr(Tokens tokens, ref Option[] options)Parses an expression from the token stream.
fnRequired parsePattern(string source, ref Option[] options)Parses a complete usage pattern.
fnPattern[] parseArgv(Tokens tokens, ref Option[] options, bool optionsFirst = false)Parses command-line argument vector.
fnstring[] parseSection(string name, string source)Parses sections matching a name from the doc string.
fnOption[] parseDefaults(string doc)Parses option defaults from the Options section of the doc string.
fnstring formalUsage(string section)Converts a usage section to a formal pattern string.
fnvoid extras(bool help, string versn, Pattern[] options, string doc)Handles --help and --version options.
fnArgMap docopt(string doc, string[] argv, bool help = true, string versn = null, bool optionsFirst = false)Parses command-line arguments based on a docopt-style documentation string.

Templates 1

tmplparseDocopt(string DOC)

Template that evaluates the parse at compile time for a string literal.

Example:

enum DOC = "Usage: prog <file>\n\nOptions:\n  -v, --verbose  Be verbose";
enum CT = parseDocopt!DOC;