[][src]Crate rustop

A simple command line parser.

rustop is a simple command line parsing crate in the spirit of Ruby's trollop. It allows to write command line parameters in a type-safe way with as little effort as possible. rustop does not aim to be a full featured command line parser for complex cases but to be a simple, easy to use crate for programs with a simple set of command line options.

Example

use rustop::opts;
fn main() {
    let (args, rest) = opts! {
        synopsis "This is a simple test program.";          // short info message for the help page
        opt verbose:bool, desc:"Be verbose.";               // a flag -v or --verbose
        opt luck:bool=true, desc:"We have no luck.";        // a flag -l or --no-luck
        opt number_of_lines:usize=1,
            desc:"The number of lines.";                    // an option -n or --number-of-lines
        param file:Option<String>, desc:"Input file name."; // an optional (positional) parameter
    }.parse_or_exit();

    if args.verbose {
        println!("Start the test program.");
    }

    if let Some(file) = args.file { println!("Read file: {}", file); }
    println!("Number of lines: {}", args.number_of_lines);
}

Usage

The crate exports a macro opts! that should be used to define the flags, options and parameters of the program. Usually a single line for each optional is sufficient.

Each line within the body of opts! specified an option, a parameter or some additional attributed. A line starts with a command followed by a comma-separated list of (keyword) arguments and must be ended with a semicolon. Options and parameters are specified using opt and param commands:

  • opt var:type[=default], desc:"text", [PARAMS...];
  • param var:type[=default], desc:"text", [PARAMS...];

The opts! macro generates a struct whose fields correspond exactly to the specified options and parameters. The values of the fields are filled during the parsing process.

Actually, the opts! macro returns a Parser whose methods should be called to parse the command line, usually parse(). This method returns a pair (args, rest), where args is the struct of command line arguments and rest is a Vec<...> of the unparsed command line arguments.

The following general commands are supported:

  • auto_shorts bool: Set whether short options should be generated automatically (using the first non-used letter of the variable name). The default is true.
  • stop_on &str: Specify an additional string to stop parsing command line parameters. The parser immediately stops parsing the command line if one of these strings is found. The default is "--".
  • command_name &str: Set the command name. Usually extracted from the command line if parse() is called.
  • synopsis &str: Set a one-line description of the program to be shown on the help page. The default is the empty string.
  • usage &str: Set an explicit usage string. If not specified (the default) an automatic usage string is generated.
  • version &str: Set the program version to be shown on the help page. The default is the empty string.
  • help bool: Add a -h,--help flag to show a usage message. The default is `true.

Option and parameters

An option is specified by a line of the form

This example is not tested
opt var:type[=default], [PARAMS...];

The parameters PARAMS are the following key:value pairs:

  • desc:&str: Set the description text of this option.
  • long:&str: Set the long option name. If not specified, the long option corresponds to the variable name (with '_' replaced by '-').
  • short:char: Set the short option name. If not specified and auto_shorts is true, the short option corresponds to the first unused letter in the variable name.
  • name:&str: Set the name of the argument of this option. This is shown in the help page as --argument=NAME. It is particularly useful for parameters specified by the param command.

A parameter is specified like an option but with the param instead of the opt command. Of course, long and short attributes cannot be specified for parameters.

Option types.

Options in rustop are typed. The command line arguments are parsed and converted to the specified type. However, depending on the option type and the presence of a default value, the parser behaves differently.

Flags

If type is bool the option is a flag. A flag does not take an additional parameter. Instead, the value of the variable is true if the flag is specified on the command line and false otherwise.

If a default value is specified and set to true, the flag becomes a negative flag. The default name of the argument is prepended by "no-" and the variable is set to true if the is not specified on the command line and false otherwise.

use rustop::opts;
let (args, rest) = opts! {
    opt xxx:bool;       // a flag -x or --xxx
    opt yyy:bool=true;  // a negative flag -y or --no-yyy
}.parse_or_exit();

Required options

An option with a plain type and no default value is obligatory: it must be specified on the command line, otherwise an error is raised.

This example panics
use rustop::opts;
let (args, _) = opts! {
    opt xxx:usize;       // an option -x <usize> or --xxx=<usize>
}.parse_or_exit();

Options with a default value

An option with a default value does not have to be specified. In this case the variable is set to its default value.

use rustop::opts;
let (args, _) = opts! {
    opt xxx:usize=42;       // an option -x <usize> or --xxx=<usize>
}.parse_or_exit();
assert_eq!(args.xxx, 42);

Optional options

An option of type Option<T> is optional. If it is specified on the command line, the value is set to Some(...), otherwise it is None.

use rustop::opts;
let (args, _) = opts! {
    opt xxx:Option<usize>;       // an option -x <usize> or --xxx=<usize>
}.parse_or_exit();
assert!(args.xxx.is_none());

Options with an optional argument

An option of type Option<T> with a default value is optional and takes an optional argument. If it is specified on the command line without an argument, e.g. --arg, the variable is set to Some(default). If it is specified with an argument, e.g. --arg=42, the variable is set to Some(42). If the option is not specified at all, the variable is set to None.

Note: there must be a space between the closing '>' and the '='.

use rustop::opts;
let (args, _) = opts! {
    opt xxx:Option<i32> = Some(42); // an option -x <usize> or --xxx[=<usize>]
}.parse_or_exit();
assert!(args.xxx.is_none());

Options with multiple arguments

An option of type Vec<T> can be specified multiple times. The value of the variable is the vector of all arguments. If, in addition, multi:true is set of this option, a single invokation of this option is followed by an arbitrary number of arguments (up to the next option, i.e. a command line argument starting with a dash).

Note that without a default value, the option must be specified at least once.

This variant is in particular useful for parameters, e.g. if the command takes an arbitrary list of file names.

use rustop::opts;
let (args, _) = opts! {
    opt xxx:Vec<usize> = vec![];       // an multi option -x <usize> or --xxx=<usize>
}.parse_or_exit();
assert!(args.xxx.is_empty());

Running the parser

The macro opts! creates and returns a wrapper around the parser struct. In order to parse some command line arguments, one of three methods of the returned struct must be called.

  1. parse_or_exit: The most often used method. Runs the parser on then command line arguments of the program returned by std::env::args() and returns a pair (args, rest). The first element args is the struct of parsed options and the second rest is a vector of unparsed command line arguments. In case of an error the program is stopped and an appropriate error message is written to stderr.
  2. parse: As before but returns Result<.., Error>, so in case of an error the user must handle the error herself.
  3. parse_args: As parse but the command line arguments are not taken from std::env::args() but passed as an iterator of type Iterator<Item=&'a str>. Note that in this case the command name cannot be extracted from std::env::args() so you must specify the command_name attribute.

Macros

_opts
opts

Structs

Multi

A multi argument option.

Opt

A command line option.

Param

A command line parameter.

Parser

The command line parser.

Single

A single argument option.

Enums

ArgError

An error when parsing an argument of an option or parameter.

Error

An error message when parsing command line arguments.

OptName

The name of an option or parameter.

Traits

CommandLineArgument

Trait for variables that can be used as option arguments.

DefaultName

Default name for some type.

Functions

clean_long
error_and_exit

Show a standard error message and quit current process.