I was reading about the Docopt project the other day and really liked the standardized approach to --help
prompts and argument parsing that it offers.
Luckly, there is a Rust Package to play with!
Add docopt
to your Cargo.toml
# ...
[]
= "git://github.com/docopt/docopt.rs"
Now in foo/src/main.rs
:
extern crate serialize;
extern crate docopt;
use Docopt;
// Define a USAGE string.
static USAGE: &'static str = "
Usage: foo [options] <target> <task>
foo (--help | --version)
Task:
start Starts the task.
stop Stops the task.
restart Restarts the task.
Options:
-h, --help Show this help.
-v, --version Show the version.
";
// Define the struct that results from those options.
// Create a `Task` enum.
// Teach Rust how to decode the `Task`
Now build it, and try some tests:
)
# Invalid arguments.
#
# Usage: foo [options] <target> <task>
# foo (--help | --version)
# ➜ foo git:(master) ✗ ./target/foo -h
# Usage: foo [options] <target> <task>
# foo (--help | --version)
#
# Task:
# start Starts the task.
# stop Stops the task.
# restart Restarts the task.
#
# Options:
# -h, --help Show this help.
# -v, --version Show the version.
)
# Args { arg_target: None, arg_task: None, flag_help: false, flag_version: true }
)
# Args { arg_target: Some(bar), arg_task: Some(Start), flag_help: false, flag_version: false }
)
# Args { arg_target: Some(bar), arg_task: Some(Stop), flag_help: false, flag_version: false }
)
# Args { arg_target: Some(bar), arg_task: Some(Restart), flag_help: false, flag_version: false }
)
# Could not decode 'baz' as task.
# Valid options are (start | stop | restart).
)
# Invalid arguments.
#
# Usage: foo [options] <target> <task>
# foo (--help | --version)
This works great! The README of the project also describes a way to use a macro for this, but I quite like this way.