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
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.
this(string msg, string file = __FILE__, size_t line = __LINE__)Constructs a DocoptLanguageError with the given message.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.
this(string msg, string file = __FILE__, size_t line = __LINE__)Constructs a DocoptExitHelp with the help text.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.
private string _expectedprivate string _gotprivate size_t _positionprivate string[] _argvstring 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.string formatMessage(string expected, string got, size_t pos, const string[] argv) @safeHelper to format a contextual error message.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.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)
private Type _typeprivate bool _boolprivate string _stringprivate long _longprivate double _doubleprivate string[] _listdouble 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.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.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.NoneMarker type representing the absence of a value.TypeThe type of value stored in this ArgValue.Type alias for the argument map returned by docopt.
Maps argument names (like "--verbose", "<file>", "command") to their values.
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.
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.bool opEquals(Object other) const @safeCompares patterns for equality based on their 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.
string _nameArgValue _valuesize_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).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.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.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.
Tuple!(int, LeafPattern) singleMatch(Pattern[] left)Finds a single match for this argument in the left array.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.
Tuple!(int, LeafPattern) singleMatch(Pattern[] left)Finds a single match for this command in the left array.Represents a command-line option (flag).
Options can have short form (-v), long form (--verbose), or both. They may also accept an argument value.
private string _shortprivate string _longprivate int _argCountTuple!(int, LeafPattern) singleMatch(Pattern[] left)Finds a single match for this option in the left array.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.
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.
Pattern[] childrenThe child patterns contained in this branch.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.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.
Represents an optional sequence of patterns.
Children may or may not match. Corresponds to patterns in square brackets.
Represents one or more occurrences of a pattern.
Corresponds to patterns followed by "..." in the usage pattern.
Represents mutually exclusive alternatives.
Corresponds to patterns separated by "|" in the usage pattern.
Tokenizer for parsing docopt patterns and arguments.
Tokens splits input strings into individual tokens and provides methods to iterate through them during parsing.
private string[] _tokensprivate bool _isParsingPatternprivate string[] _originalprivate size_t _consumedTokens fromPattern(string source)Creates a Tokens instance for parsing a usage pattern.string move()Removes and returns the first token.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.
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.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.
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
T 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.ResolvedDefault resolveEnvDefault(string spec) @safeResolves a default value specification possibly referencing an environment variable.Either transform(Pattern pattern)Expands a pattern into an (almost) equivalent one with a single Either at top.string ctfeFindSection(string name, string source) @safe pureExtracts a section block (e.g. "usage:" or "options:") from a doc string.string ctfeFormalFromUsage(string usageSection) @safe pureCreates a very simple formal usage string from a `Usage:` section.CtfeOptionSpec[] ctfeParseOptions(string optionsSection) @safe pureParses the `Options:` section into a list of `CtfeOptionSpec`.CtfeDoc ctfeParseDocopt(string doc) @safe pureCompile-time docopt parser that extracts `Usage:` and `Options:`.Option[] buildOptionsFromCtfe(const CtfeOptionSpec[] specs)Builds runtime `Option` objects from CTFE specs.ArgMap docopt(CtfeDoc parsed, string[] argv, bool help = true, string versn = null, bool optionsFirst = false)Overload of `docopt` that accepts a compile-time parsed descriptor.Pattern[] parseLong(Tokens tokens, ref Option[] options)Parses a long option from the token stream.Pattern[] parseShorts(Tokens tokens, ref Option[] options)Parses short option(s) from the token stream.Pattern[] parseAtom(Tokens tokens, ref Option[] options)Parses a single atom from the token stream.Pattern[] parseSeq(Tokens tokens, ref Option[] options)Parses a sequence of atoms from the token stream.Pattern[] parseExpr(Tokens tokens, ref Option[] options)Parses an expression from the token stream.Pattern[] parseArgv(Tokens tokens, ref Option[] options, bool optionsFirst = false)Parses command-line argument vector.string[] parseSection(string name, string source)Parses sections matching a name from the doc string.Option[] parseDefaults(string doc)Parses option defaults from the Options section of the doc string.Templates 1
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;