Skip to content

docopt.net is a .NET implementation of docopt

NuGet Package

Isn't it awesome how CommandLineParser and PowerArgs generate help messages based on your code?

You know what's even more awesome? It's when the option parser is generated based on the beautiful help message that you write yourself! This way you don't need to write this boilerplate parser-code, and instead can write only the help message--the way you want it.

docopt.net helps you create most beautiful command-line interfaces easily:

#nullable enable

using System;
using DocoptNet;

const string usage = @"Naval Fate.

Usage:
  naval_fate.exe ship new <name>...
  naval_fate.exe ship <name> move <x> <y> [--speed=<kn>]
  naval_fate.exe ship shoot <x> <y>
  naval_fate.exe mine (set|remove) <x> <y> [--moored | --drifting]
  naval_fate.exe (-h | --help)
  naval_fate.exe --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.

";

var arguments = new Docopt().Apply(usage, args, version: "Naval Fate 2.0", exit: true)!;
foreach (var (key, value) in arguments)
    Console.WriteLine("{0} = {1}", key, value);

Beat that! The option parser is generated based on the docstring above that is passed to the Docopt.Apply method. Docopt.Apply parses the usage pattern ("Usage: ...") and option descriptions (lines starting with dash "-") and ensures that the program invocation matches the usage pattern; it parses options, arguments and commands based on that. The basic idea is that a good help message has all necessary information in it to make a parser.

Differences from reference Python implementation

docopt.net started as a straightforward port of the Python reference implementation and should support all the features of the docopt language/format. The API was then adjusted to be more idiomatic and provide strong, even compile-time, guarantees. For example, arguments can be parsed into a dictionary of the type IDictionary<string, ArgValue>, where ArgValue is a simple wrapper around an argument value that can be interrogated, cast and pattern-matched based on the actual/expected value type.

Installation

To use docopt.net to your project, add the package using:

dotnet add package docopt.net

Usage

There are templates available for use with dotnet new that can be installed with the following command:

dotnet new --install docopt.net.templates::0.1.0

To create a new console application that uses docopt.net, run the following command in a new and empty directory:

dotnet new docopt-console

then run the new console project with dotnet run. For example:

mkdir MyConsoleApp
cd MyConsoleApp
dotnet new docopt-console
dotnet run -- --help

The console application will use the new API and source generator with the help in an external file called Program.docopt.txt.

API

There are three ways to work with docopt.net:

  1. Use an API that was inspired from the reference Python implementation. This was the first and only API up to version 0.8.0. Developers that have worked with the Python implementation will feel at home with this flavour of the API, but bear in mind that it may be rendered obsolete in a future version.

  2. Starting with version 0.8.0, there is a newer API that provides a more idiomatic model for a statically typed language like C#.

  3. Building on top of the new API introduced with version 0.8.0, docopt.net comes with a source generator for projects using C# 9 or later. It can generate a type containing all the arguments in the docopt usage of a program. It provides the strongest compile-time guarantees such that if the usage changes in some incompatible way, the program will most probably even fail to compile!

This section primarily deals with the newer API introduced with version 0.8.0. There is a separate section for the API inspired by the reference Python implementation.

The following program shows one usage of the new API:

using System;
using System.Collections.Generic;
using DocoptNet;

const string help = @"Naval Fate.

Usage:
  naval_fate.exe ship new <name>...
  naval_fate.exe ship <name> move <x> <y> [--speed=<kn>]
  naval_fate.exe ship shoot <x> <y>
  naval_fate.exe mine (set|remove) <x> <y> [--moored | --drifting]
  naval_fate.exe (-h | --help)
  naval_fate.exe --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.

";

static int ShowHelp(string help) { Console.WriteLine(help); return 0; }
static int ShowVersion(string version) { Console.WriteLine(version); return 0; }
static int OnError(string usage) { Console.Error.WriteLine(usage); return 1; }

static int Run(IDictionary<string, ArgValue> arguments)
{
    foreach (var (key, value) in arguments)
        Console.WriteLine("{0} = {1}", key, value);
    return 0;
}

return Docopt.CreateParser(help)
             .WithVersion("Naval Fate 2.0")
             .Parse(args)
             .Match(Run,
                    result => ShowHelp(result.Help),
                    result => ShowVersion(result.Version),
                    result => OnError(result.Usage));

Instead of using Match, it is also possible to use pattern-matching in C# on the result of the Parse method:

var parser = Docopt.CreateParser(help).WithVersion("Naval Fate 2.0");

return parser.Parse(args) switch
{
    IArgumentsResult<IDictionary<string, ArgValue>> { Arguments: var arguments } => Run(arguments),
    IHelpResult => ShowHelp(help),
    IVersionResult { Version: var version } => ShowVersion(version),
    IInputErrorResult { Usage: var usage } => OnError(usage),
    var result => throw new System.Runtime.CompilerServices.SwitchExpressionException(result)
};

The version using Match provides stronger guarantees because the arity of the Match method will change depending on the requested options. For example, if the call to WithVersion is commented-out, the code will fail to compile unless the second argument to Match is also removed or commented-out:

return Docopt.CreateParser(help)
          // .WithVersion("Naval Fate 2.0")
             .Parse(args)
             .Match(Run,
                    result => ShowHelp(result.Help),
                 // result => ShowVersion(result.Version),
                    result => OnError(result.Usage));

In contrast, the version using the switch expression and pattern-matching will never produce a compile-time error but the switch arm for IVersionResult will simply never match at run-time..

The Docopt.CreateParser method takes a single argument:

  • doc is a string that contains a help message that will be parsed to create the option parser. The simple rules of how to write such a help message are given in later sections.

It returns a parser whose Parse method can then be supplied with the run-time command-line arguments:

const string help = @"Naval Fate.

Usage:
  naval_fate.exe ship new <name>...
  naval_fate.exe ship <name> move <x> <y> [--speed=<kn>]
  naval_fate.exe ship shoot <x> <y>
  naval_fate.exe mine (set|remove) <x> <y> [--moored | --drifting]
  naval_fate.exe (-h | --help)
  naval_fate.exe --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.

";

var parser = Docopt.CreateParser(help);
var result = var parser.Parse(args);

The result of the Parse method is one the following types:

  • IArgumentsResult<T>: the parsed arguments as T when command-line is valid per usage.
  • IHelpResult: the result when help is requested via -h or --help.
  • IVersionResult: the result when version is requested via --version.
  • IInputErrorResult: the input error result if the given command-line arguments do not match the usage.

Docopt.CreateParser returns a parser that by default assumes the program usage supports the help flags, -h or --help. It greedily parses these and returns IHelpResult if found. To disable this behaviour, call DisableHelp() on the parser, as in:

var parser = Docopt.CreateParser(help)
                   .DisableHelp();
var result = var parser.Parse(args);

Doing so means that the parser's Parse method will never return IHelpResult and it is therefore up to the program to handle these flags, for example, as follows:

switch (argsParser.Parse(args))
{
    case IArgumentsResult<IDictionary<string, ArgValue>> { Arguments: var arguments }:
        foreach (var (key, value) in arguments)
            Console.WriteLine("{0} = {1}", key, value);
        if (arguments["--help"].IsTrue)
            Console.WriteLine(help);
        return 0;
    case var result:
        throw new System.Runtime.CompilerServices.SwitchExpressionException(result);
}

Like greedy processing of help flags can be disabled, the parser returned by Docopt.CreateParser can be configured to greedily parse the --version flag. The parser's Parse method will then return IVersionResult. The configuration is done via the WithVersion method as show below:

var parser = Docopt.CreateParser(help)
                   .WithVersion("Naval Fate 2.0");

The version string supplied ("Naval Fate 2.0" in the example above) is then populated in the Version property of the IVersionResult instance.

The API of the parser instance returned by Docopt.CreateParser is adaptive. As certain options are configured, the API returns immutable instances of the parser and limits or expands further composition. Moreover, the result of the parser's Parse method has a Match method that can be supplied callback functions to handle each of the resulting types. The arity of the Match method adjusts depending on the composed features.

If the parsed command-line arguments conform to the program usage then the Parse method returns an instance of IArgumentsResult<IDictionary<string, ArgValue>> whose Arguments property is a dictionary of name-value pairs (that is, IDictionary<string, ArgValue>). ArgValue is a discriminated union of the various kinds of values possible:

  • None: represents a missing or not applicable value for an argument (<argument>) or an option expecting a value (--option=VALUE).
  • Boolean: represents a Boolean that is true when a command or an option (--option) is present and false otherwise.
  • Integer: represents the number of times a command (command...) or option (--option...) has been specified.
  • String: represents the value of a non-repeatable argument (<argument>) or option that expects a value (--option=VALUE).
  • StringList: represent an immutable collection of String values for repeatable arguments (<argument>...) and options (--file=FILE...).

Given the following example usage:

Naval Fate.

Usage:
  naval_fate.exe ship new <name>...
  naval_fate.exe ship <name> move <x> <y> [--speed=<kn>]
  naval_fate.exe ship shoot <x> <y>
  naval_fate.exe mine (set|remove) <x> <y> [--moored | --drifting]
  naval_fate.exe (-h | --help)
  naval_fate.exe --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.

The resulting dictionary will contain the following keys and value kinds:

Name Type
ship Boolean
new Boolean
<name> StringList
move Boolean
<x> String/None
<y> String/None
--speed String
shoot Boolean
mine Boolean
set Boolean
remove Boolean
--moored Boolean
--drifting Boolean
--help Boolean
--version Boolean

The ArgValue type has several properties to interrogate the actual value kind at run-time, conversion to Object as well as support for explicit casts to Boolean, Int32, String and StringList.

Source Generator

docopt.net also comes with a C# source generator starting with version 0.8.0. The source generator is called by the C# compiler as part of the build process. It generates a strong-typed class for the program arguments given its help message in one of two ways:

  • in an extenal text file.
  • directly inlined in a C# source file as a string constant.

If the help text is large, it might be best maintained in a separate text file. If the program usage is very trivial with, for example, just options and arguments, it might be simplest to embed it directly into a string constant and have fewer files to maintain for a project. Both approaches are discussed in their respective sections next.

Help in a External File

The source generator will look for any file that is part of the project and whose name ends in .docopt.txt and use its content as the help message source. It will then generate a C# class representing the command, arguments and options found in the usage section of the help message.

Suppose a C# project contains a text file called Program.docopt.txt with the following content:

Naval Fate.

Usage:
  naval_fate.exe ship new <name>...
  naval_fate.exe ship <name> move <x> <y> [--speed=<kn>]
  naval_fate.exe ship shoot <x> <y>
  naval_fate.exe mine (set|remove) <x> <y> [--moored | --drifting]
  naval_fate.exe (-h | --help)
  naval_fate.exe --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.

The source generator will then generate a class that looks something like the following:

partial class ProgramArguments : IEnumerable<KeyValuePair<string, object?>>
{
    public const string Help = @"Naval Fate.

    Usage:
      naval_fate.exe ship new <name>...
      naval_fate.exe ship <name> move <x> <y> [--speed=<kn>]
      naval_fate.exe ship shoot <x> <y>
      naval_fate.exe mine (set|remove) <x> <y> [--moored | --drifting]
      naval_fate.exe (-h | --help)
      naval_fate.exe --version

    Options:
      -h --help     Show this screen.
      --version     Show version.
      --speed=<kn>  Speed in knots [default: 10].
      --moored      Moored (anchored) mine.
      --drifting    Drifting mine.
";

    public const string Usage = @"Usage:
      naval_fate.exe ship new <name>...
      naval_fate.exe ship <name> move <x> <y> [--speed=<kn>]
      naval_fate.exe ship shoot <x> <y>
      naval_fate.exe mine (set|remove) <x> <y> [--moored | --drifting]
      naval_fate.exe (-h | --help)
      naval_fate.exe --version";

    public bool CmdShip { get; private set; }
    public bool CmdNew { get; private set; }
    public StringList ArgName { get; private set; } = StringList.Empty;
    public bool CmdMove { get; private set; }
    public string? ArgX { get; private set; }
    public string? ArgY { get; private set; }
    public string OptSpeed { get; private set; } = "10";
    public bool CmdShoot { get; private set; }
    public bool CmdMine { get; private set; }
    public bool CmdSet { get; private set; }
    public bool CmdRemove { get; private set; }
    public bool OptMoored { get; private set; }
    public bool OptDrifting { get; private set; }
    public bool OptHelp { get; private set; }
    public bool OptVersion { get; private set; }

    public static IHelpFeaturingParser<ProgramArguments> CreateParser()
    {
        /* omitted for brevity */
    }

    IEnumerator<KeyValuePair<string, object?>> GetEnumerator()
    {
        /* omitted for brevity */
    }

    IEnumerator<KeyValuePair<string, object?>> IEnumerable<KeyValuePair<string, object?>>.GetEnumerator() => GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

The generated class will:

  • have the same name as the text file with the .docopt.txt suffix replaced with Arguments, such that Program.docopt.txt will generate a class named ProgramArguments.
  • be partial so you can continue to enhance through another part in a separate C# source file.
  • sit in the project's namespace.
  • have a public string constant named Help that will contain the entire help text from the source file as a verbatim string literal.
  • have a public string constant named Usage that will contain the usage section of the help message.
  • have a public read-write property for each command, argument and option defined in the usage where the property name will reflect the name of the command, argument or option (after applying Pascal casing transformations) and bear the prefix Cmd for a command, Arg for an argument and Opt for an option. If two distinct options have only short names that differ in case, as in -m and -M then the former will be named OptM and the latter OptUpperM. The type of the property will be either Boolean/bool, Int32/int, String or StringList.
  • implement IEnumerable<KeyValuePair<string, object?>> so the arguments can be iterated, for example, in a foreach loop.
  • have a public static method called CreateParser that takes no arguments and returns a parser whose Parse method, when supplied the command-line arguments, will return IArgumentsResult<T>; the T will be the generated class.

The generated class can then be used in the project as shown below:

// Program.cs

using System;
using NavalFate;

static int ShowHelp(string help) { Console.WriteLine(help); return 0; }
static int ShowVersion(string version) { Console.WriteLine(version); return 0; }
static int OnError(string usage) { Console.WriteLine(usage); return 1; }

static int Main(ProgramArguments args)
{
    foreach (var (name, value) in args)
        Console.WriteLine($"{name} = {value}");

    Console.WriteLine($@"{{
    Ship     = {args.CmdShip    },
    New      = {args.CmdNew     },
    Name     = [{string.Join(", ", args.ArgName)}],
    Move     = {args.CmdMove    },
    X        = {args.ArgX       },
    Y        = {args.ArgY       },
    Speed    = {args.OptSpeed   },
    Shoot    = {args.CmdShoot   },
    Mine     = {args.CmdMine    },
    Set      = {args.CmdSet     },
    Remove   = {args.CmdRemove  },
    Moored   = {args.OptMoored  },
    Drifting = {args.OptDrifting},
    Help     = {args.OptHelp    },
    Version  = {args.OptVersion },
}}");

    return 0;
}

return ProgramArguments.CreateParser()
                       .WithVersion("Naval Fate 2.0")
                       .Parse(args)
                       .Match(Main,
                              result => ShowHelp(result.Help),
                              result => ShowVersion(result.Version),
                              result => OnError(result.Usage));

Help in a String Constant

Much of what has been discussed in the previous section also applies to this as far as the generated code goes. The difference is in how the source generator locates the string constant containing. When the C# compiler builds the project, the source generator will look for any partial class decorated with the [DocoptArguments] attribute and has a string constant named Help:

using DocoptNet;

[DocoptArguments]
partial class ProgramArguments
{
    const string Help = @"Naval Fate.

    Usage:
      naval_fate.exe ship new <name>...
      naval_fate.exe ship <name> move <x> <y> [--speed=<kn>]
      naval_fate.exe ship shoot <x> <y>
      naval_fate.exe mine (set|remove) <x> <y> [--moored | --drifting]
      naval_fate.exe (-h | --help)
      naval_fate.exe --version

    Options:
      -h --help     Show this screen.
      --version     Show version.
      --speed=<kn>  Speed in knots [default: 10].
      --moored      Moored (anchored) mine.
      --drifting    Drifting mine.
";
}

The source generator will then generate another part to the class definition with the methods and properties discussed in the previous section.

The help string constant can have any access modifier. It does not have to be public.

If is possible to give the string constant containing the help message or text another name than Help by supplying the alternate name via the HelpConstName property of the [DocoptArguments] attribute:

using DocoptNet;

[DocoptArguments(HelpConstName = nameof(HelpText))]
partial class ProgramArguments
{
    const string HelpText = @"...";
}

Older API

Warning

This flavour of the API that was inspired by the reference Python implementation may be rendered obsolete in a future version.

using DocoptNet;
public IDictionary<string, ValueObject> Apply(string doc, string cmdLine, bool help = true,
  object version = null, bool optionsFirst = false, bool exit = false);

public IDictionary<string, ValueObject> Apply(string doc, ICollection<string> argv, bool help = true,
  object version = null, bool optionsFirst = false, bool exit = false);

Apply takes 1 required and 5 optional arguments:

  • doc is a string that contains a help message that will be parsed to create the option parser. The simple rules of how to write such a help message are given in next sections. Here is a quick example of such a string:

    const string USAGE =
    @"Usage: my_program [-hso FILE] [--quiet | --verbose] [INPUT ...]
    
    -h --help    show this
    -s --sorted  sorted output
    -o FILE      specify output file [default: ./test.txt]
    --quiet      print less text
    --verbose    print more text
    
    ";
    
  • argv is an optional argument.
  • help, by default true, specifies whether the parser should automatically print the help message (supplied as doc) and terminate, in case -h or --help option is encountered (options should exist in usage pattern, more on that below). If you want to handle -h or --help options manually (as other options), set help: false.

    Note, you can override the print and exit behaviour by providing a custom handler for the Docopt.PrintExit event. e.g.

    var docopt = new Docopt();
    docopt.PrintExit += MyCustomPrintExit;
    
  • version, by default null, is an optional argument that specifies the version of your program. If supplied, then, (assuming --version option is mentioned in usage pattern) when parser encounters the --version option, it will print the supplied version and terminate. version could be any printable object, but most likely a string, e.g. "2.1.0rc1".

    Note, when docopt.net is set to automatically handle -h, --help and --version options, you still need to mention them in usage pattern for this to work. Also, for your users to know about them.

  • optionsFirst, by default false. If set to true will disallow mixing options and positional argument; i.e. after first positional argument, all arguments will be interpreted as positional even if they look like options. This can be used for strict compatibility with POSIX, or if you want to dispatch your arguments to other programs.
  • exit, by default false. If set to false will raise exceptions based on DocoptBaseException and will not print or exit. If set to true any occurence of DocoptBaseException will be caught by Docopt.Apply(), the error message or the usage will be printed, and the program will exit with error code 0 if it's a DocoptExitException, 1 otherwise.

The return value is a simple dictionary with options, arguments and commands as keys, spelled exactly like in your help message. Long versions of options are given priority. For example, if you invoke the top example as:

naval_fate ship Guardian move 100 150 --speed=15

the return dictionary will be:

{
    ["--drifting"] = false,    ["mine"] = false,
    ["--help"] = false,        ["move"] = true,
    ["--moored"] = false,      ["new"] = false,
    ["--speed"] = "15",        ["remove"] = false,
    ["--version"] = false,     ["set"] = false,
    ["<name>"] = ["Guardian"], ["ship"] = true,
    ["<x>"] = "100",           ["shoot"] = false,
    ["<y>"] = "150"
}

Help message format

Help message consists of 2 parts:

  • Usage pattern, e.g.:
    Usage: my_program [-hso FILE] [--quiet | --verbose] [INPUT ...]
    
  • Option descriptions, e.g.:
    -h --help    show this
    -s --sorted  sorted output
    -o FILE      specify output file [default: ./test.txt]
    --quiet      print less text
    --verbose    print more text
    

Their format is described below; other text is ignored.

Usage pattern format

Usage pattern is a substring of doc that starts with usage: (case insensitive) and ends with a visibly empty line. Minimum example:

const string USAGE = "Usage: my_program";

The first word after usage: is interpreted as your program's name. You can specify your program's name several times to signify several exclusive patterns:

const string USAGE =
@"Usage: my_program FILE
         my_program COUNT FILE";

Each pattern can consist of the following elements:

  • \<arguments>, ARGUMENTS. Arguments are specified as either upper-case words, e.g. my_program CONTENT-PATH or words surrounded by angular brackets: my_program <content-path>.
  • --options. Options are words started with dash (-), e.g. --output, -o. You can "stack" several of one-letter options, e.g. -oiv which will be the same as -o -i -v. The options can have arguments, e.g. --input=FILE or -i FILE or even -iFILE. However it is important that you specify option descriptions if you want your option to have an argument, a default value, or specify synonymous short/long versions of the option (see next section on option descriptions).
  • commands are words that do not follow the described above conventions of --options or <arguments> or ARGUMENTS, plus two special commands: dash "-" and double dash "--" (see below).

Use the following constructs to specify patterns:

  • [ ] (brackets) optional elements. e.g.: my_program [-hvqo FILE]
  • ( ) (parens) required elements. All elements that are not put in [ ] are also required, e.g.: my_program --path=<path> <file>... is the same as my_program (--path=<path> <file>...). (Note, "required options" might be not a good idea for your users).
  • | (pipe) mutually exclusive elements. Group them using ( ) if one of the mutually exclusive elements is required: my_program (--clockwise | --counter-clockwise) TIME. Group them using [ ] if none of the mutually-exclusive elements are required: my_program [--left | --right].
  • ... (ellipsis) one or more elements. To specify that arbitrary number of repeating elements could be accepted, use ellipsis (...), e.g. my_program FILE ... means one or more FILE-s are accepted. If you want to accept zero or more elements, use brackets, e.g.: my_program [FILE ...]. Ellipsis works as a unary operator on the expression to the left.
  • [options] (case sensitive) shortcut for any options. You can use it if you want to specify that the usage pattern could be provided with any options defined below in the option-descriptions and do not want to enumerate them all in usage-pattern.
  • "[--]". Double dash "--" is used by convention to separate positional arguments that can be mistaken for options. In order to support this convention add "[--]" to your usage patterns.
  • "[-]". Single dash "-" is used by convention to signify that stdin is used instead of a file. To support this add "[-]" to your usage patterns. "-" acts as a normal command.

If your pattern allows to match argument-less option (a flag) several times:

Usage: my_program [-v | -vv | -vvv]

then number of occurrences of the option will be counted; i.e. args['-v'] will be 2 if program was invoked as my_program -vv. Same works for commands.

If your usage patterns allows to match same-named option with argument or positional argument several times, the matched arguments will be collected into a list:

Usage: my_program <file> <file> --path=<path>...

Therefore invoked with my_program file1 file2 --path=./here --path=./there the returned dict will contain args['<file>'] == ['file1', 'file2'] and args['--path'] == ['./here', './there'].

Option descriptions format

Option descriptions consist of a list of options that you put below your usage patterns.

It is necessary to list option descriptions in order to specify:

  • synonymous short and long options,
  • if an option has an argument,
  • if option's argument has a default value.

The rules are as follows:

  • Every line in doc that starts with - or -- (not counting spaces) is treated as an option description, e.g.:
    Options:
      --verbose   # GOOD
      -o FILE     # GOOD
    Other: --bad  # BAD, line does not start with dash "-"
    
  • To specify that option has an argument, put a word describing that argument after space (or equals "=" sign) as shown below. Follow either \<angular-brackets> or UPPER-CASE convention for options' arguments. You can use comma if you want to separate options. In the example below, both lines are valid, however you are recommended to stick to a single style.:
    -o FILE --output=FILE       # without comma, with "=" sign
    -i <file>, --input <file>   # with comma, without "=" sing
    
  • Use two spaces to separate options with their informal description:
    --verbose More text.   # BAD, will be treated as if verbose option had
                            # an argument "More", so use 2 spaces instead
    -q        Quit.        # GOOD
    -o FILE   Output file. # GOOD
    --stdout  Use stdout.  # GOOD, 2 spaces
    
  • If you want to set a default value for an option with an argument, put it into the option-description, in form [default: <my-default-value>]:
    --coefficient=K  The K coefficient [default: 2.95]
    --output=FILE    Output file [default: test.txt]
    --directory=DIR  Some directory [default: ./]
    
  • If the option is not repeatable, the value inside [default: ...] will be interpreted as string. If it is repeatable, it will be splited into a list on whitespace:
    Usage: my_program [--repeatable=<arg> --repeatable=<arg>]
                          [--another-repeatable=<arg>]...
                          [--not-repeatable=<arg>]
    
    # will be ['./here', './there']
    --repeatable=<arg>          [default: ./here ./there]
    
    # will be ['./here']
    --another-repeatable=<arg>  [default: ./here]
    
    # will be './here ./there', because it is not repeatable
    --not-repeatable=<arg>      [default: ./here ./there]
    

Changelog

docopt.net follows semantic versioning. The first release with stable API will be 1.0.0 (soon). Until then, you are encouraged to specify explicitly the version in your dependency tools, e.g.:

nuget install docopt.net -Version 0.7.0

0.7.0 or later

See releases for changelog and notes.

  • 0.6.1.11 Bug fix.
  • 0.6.1.8 Added support for .NET Core RC2.
  • 0.6.1.6 Double creation of property bug fix. T4DocoptNet.tt assembly path fix.
  • 0.6.1.5 Added strongly typed arguments through T4 macro. ValueObject interface cleanup. exit: true parameter behavior fix.
  • 0.6.1.4 Clarified exit parameter behaviour.
  • 0.6.1.3 Added exit parameter.
  • 0.6.1.2 Fixed docopt capitalisation.
  • 0.6.1.1 Initial port. All reference language agnostic tests pass.