Search code examples
rustdocopt

How do I retrieve the subcommand used when using docopt in Rust?


I am writing a command line utility which has a couple of subcommands:

Usage: 
    example start [-w | --write] [-F | --force] <name>
    example stop [-F | --force] <name>
    example restart [-F | --force] <name>
    example status [-F | --force] <name>
    example ls
    example install <name>
    example uninstall <name>
    example show
    example edit <name>
    example (-h | --help)

Options:
    -h --help     Show help message
    -F --force    Force start/stop/restart
    -w --write    TODO

This parses out the arguments perfectly, but it doesn't allow me to retrieve the subcommand which was used.

An alternative would be to use example <command> <name> [<args>...] but this no longer gives you the features of docopt and you could parse it using different methods again ...

Any idea how to setup the docopt inside Rust to deal with that?


Solution

  • If you have cmd_start: bool, cmd_stop: bool, etc in your struct, Docopt will set the used one to true.

    More info here: https://github.com/docopt/docopt.rs#struct-field-name-mapping, copied below for posterity:

    Struct field name mapping

    The field names of the struct map like this:

    -g            => flag_g
    --group       => flag_group
    --group <arg> => flag_group
    FILE          => arg_FILE
    <file>        => arg_file
    build         => cmd_build