argparse is a flexible utility for D programming language to parse command line arguments.
Warning
Changelog
-
Changes in
Config:-
Custom error handler function (
Config.errorHandler) now receives message text with ANSI styling if styling is enabled. One can useargparse.ansi.getUnstyledTextfunction to remove any styling - this function returns a range of unstyledstringobjects which can be used as is orjoin'ed into a string if needed:message.getUnstyledText.join. -
Config.addHelpis renamed toConfig.addHelpArgument. -
Config.arraySepis renamed toConfig.valueSep. -
Config.caseSensitiveis replaced withConfig.caseSensitiveShortName,Config.caseSensitiveLongNameandConfig.caseSensitiveSubCommand. There is also a "new"Config.caseSensitivefunction/property helper that sets all above settings to a specific value. -
Config.endOfArgsis renamed toConfig.endOfNamedArgs. -
Config.helpStyleis renamed toConfig.styling. -
Config.namedArgCharis replaced withConfig.shortNamePrefixandConfig.longNamePrefix.
-
-
Style.namedArgumentNameis renamed toStyle.argumentName. -
Underlying type of
ansiStylingArgumentargument is changed. It can now be directly cast to boolean instead comparing againstConfig.StylingMode.So if you use it:
static auto color = ansiStylingArgument;
then you should replace
if(args.color == Config.StylingMode.on)
with
if(args.color) -
@SubCommandsUDA is removed. One should useSubCommandtemplate instead ofSumTypeSimply replace
@SubCommands SumType!(CMD1, CMD2, Default!CMD3) cmd;
with
SubCommand!(CMD1, CMD2, Default!CMD3) cmd;
-
@TrailingArgumentsUDA is removed: all command line parameters that appear after double-dash--are considered as positional arguments. So if those parameters are to be parsed, use@PositionalArgumentinstead of@TrailingArguments. -
Functions for parsing customization (
PreValidation,Parse,ValidationandAction) now accept functions as runtime parameters instead of template argumentsFor example, replace this
.Parse !((string s) { return cast(char) s[1]; }) .Validation!((char v) { return v >= '0' && v <= '9'; })
with
.Parse ((string s) { return cast(char) s[1]; }) .Validation((char v) { return v >= '0' && v <= '9'; })
-
HideFromHelpis renamed toHiddenand now also hides an argument from shell completion. -
AllowedValuesnow accepts values as run-time parameters, not as template parameters.For example, replace this
.AllowedValues!(["value1", "value2", value3"])
with
.AllowedValues("value1", "value2", value3")
-
AllowNoValuenow accepts a value as run-time parameter, not as template parameter.For example, replace this
.AllowNoValue!"myvalue"
with
.AllowNoValue("myvalue") -
RequireNoValueis renamed toForceNoValueand now accepts a value as run-time parameter, not as template parameter.For example, replace this
.RequireNoValue!"myvalue"
with
.ForceNoValue("myvalue") -
ArgumentValueis renamed toAllowedValues.For example, replace this
.ArgumentValue("value1", "value2")
with
.AllowedValues("value1", "value2")
-
parseArgstemplate functions that receivednewMaintemplate argument was removed. One should use eithermaintemplate mixin or non-templatedResult parseArgs(ref COMMAND receiver, string[] args)function. -
Dropped support for DMD-2.099.
-
Parsing procedure follows POSIX.1-2024 meaning that
argparsenow allows at most one value per appearance of named argument in command line. This means thatprog --param value1 value2is not working anymore by default ---parammust be repeated:prog --param value1 --param value2. However,prog --param value1,value2still works.To make
argparse2.* behave like 1.*, one should setConfig.variadicNamedArgumentto true. See documentation for details. -
Fix for
Command()UDA:ArrayIndexErroris not thrown anymore. -
Error messages are printed with
Config.stylingand now have the same styling as help text. -
New
errorMessagePrefixmember inConfig.stylingthat determines the style of "Error:" prefix in error messages. This prefix is printed in red by default. -
New checks:
- Argument is not allowed to be in multiple argument groups.
- Subcommand name can't start with
Config.shortNamePrefix(dash-by default) orConfig.longNamePrefix(double-dash--by default).
-
Functions for parsing customization (
PreValidation,Parse,ValidationandAction) can now returnResultthroughResult.SuccessorResult.Errorand provide error message if needed. -
Fixes for bundling of single-letter arguments. For example, the following cases are supported for
bool b; string s;arguments:./prog -b -s=abc./prog -b -s abc./prog -b -sabc./prog -bsabc./prog -bs=abc
-
Fixes for parsing of multiple values. Only these formats are supported:
./prog --arg value1 value2 value3./prog --arg=value1,value2,value3
-
Values of multi-value positional argument can now be interleaved with named arguments. For example, the following is the same when
arg1andarg2are values for singlestring[] argspositional argument:--flag arg1 arg2arg1 --flag arg2arg1 arg2 --flag
-
Long and short names of arguments are now separated:
- Short names are single-character names by default. This can be overridden by explicitly specifying short and long names in
NamedArgumentUDA. - Short names can be specified with short prefix only (e.g.
-). - Long names can be specified with long prefix only (e.g.
--).
- Short names are single-character names by default. This can be overridden by explicitly specifying short and long names in
-
Removed support for delegate in
Config.errorHandler,Description,ShortDescription,UsageandEpilogbecause of compiler'sclosures are not yet supported in CTFE. -
Added new
Config.assignKeyValueCharparameter to customize assign character inkey=valuesyntax for arguments with associative array type. -
Added support of
@PositionalArgumentwithout explicit position. In this case positions are determined in the order of declarations of members.
- Removed dependency on
std.regex. - New code base: library implementation is almost fully rewritten (public API was not changed in this effort). Unnecessary templates were replaced with regular functions. As a result, compilation time and memory usage were improved: 2x better for
dub buildand 4x better fordub test. - New documentation
- Positional arguments:
- Automatic type conversion of the value.
- Required by default, can be marked as optional.
- Named arguments:
- Multiple names are supported, including short (
-v) and long (--verbose) ones. - Case-sensitive/-insensitive parsing.
- Bundling of short names (
-vvvis same as-v -v -v). - Equals sign is accepted (
-v=debug,--verbose=debug). - Automatic type conversion of the value.
- Optional by default, can be marked as required.
- Multiple names are supported, including short (
- Support different types of destination data member:
- Scalar (e.g.,
int,float,bool). - String arguments.
- Enum arguments.
- Array arguments.
- Hash (associative array) arguments.
- Callbacks.
- Scalar (e.g.,
- Different workflows are supported:
- Mixin to inject standard
mainfunction. - Parsing of known arguments only (returning not recognized ones).
- Enforcing that there are no unknown arguments provided.
- Mixin to inject standard
- Shell completion.
- Options terminator (e.g., parsing up to
--leaving any argument specified after it). - Arguments groups.
- Subcommands.
- Fully customizable parsing:
- Raw (
string) data validation (i.e., before parsing). - Custom conversion of argument value (
string-> anydestination type). - Validation of parsed data (i.e., after conversion to
destination type). - Custom action on parsed data (doing something different from storing the parsed value in a member of destination object).
- Raw (
- ANSI colors and styles.
- Built-in reporting of error happened during argument parsing.
- Built-in help generation.
Please find up-to-date documentation here.