• Stars
    star
    227
  • Rank 170,130 (Top 4 %)
  • Language
    Rust
  • License
    MIT License
  • Created about 10 years ago
  • Updated 12 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

The command-line argument parser library for rust

Argparse

The rust-argparse is a command-line parsing module for Rust. It's inspired by Python's argparse module.

Features:

  • Supports standard (GNU) option conventions
  • Properly typed values
  • Automatically generated help and usage messages

Importing

Edit your Cargo.toml to add rust-argparse to your project.

[dependencies]
argparse = "0.2.2"

Example

The following code is a simple Rust program with command-line arguments:

extern crate argparse;

use argparse::{ArgumentParser, StoreTrue, Store};

fn main() {
    let mut verbose = false;
    let mut name = "World".to_string();
    {  // this block limits scope of borrows by ap.refer() method
        let mut ap = ArgumentParser::new();
        ap.set_description("Greet somebody.");
        ap.refer(&mut verbose)
            .add_option(&["-v", "--verbose"], StoreTrue,
            "Be verbose");
        ap.refer(&mut name)
            .add_option(&["--name"], Store,
            "Name for the greeting");
        ap.parse_args_or_exit();
    }

    if verbose {
        println!("name is {}", name);
    }
    println!("Hello {}!", name);
}

Assuming the Rust code above is saved into a file greeting.rs, let's see what we have now:

$ rustc greeting.rs
$ ./greeting -h
Usage:
  ./greeting [OPTIONS]

Greet somebody.

Optional arguments:
  -h, --help  Show this help message and exit
  -v, --verbose
             Be verbose
  --name NAME Name for the greeting
$ ./greeting
Hello World!
$ ./greeting --name Bob
Hello Bob!
$ ./greeting -v --name Alice
name is Alice
Hello Alice!

Basic Workflow

Create ArgumentParser

The argument parser is created empty and is built incrementally. So we create a mutable variable:

extern crate argparse;
use argparse::ArgumentParser;

let mut parser = ArgumentParser::new();

Customize

There are optional customization methods. The most important one is:

parser.set_description("My command-line utility");

The description is rewrapped to fit 80 column string nicely. Just like option descriptions.

Add Options

The refer method creates a cell variable, which the result will be written to:

let mut verbose = false;
parser.refer(&mut verbose);

Next we add options which control the variable. For example:

parser.refer(&mut verbose)
    .add_option(&["-v", "--verbose"], StoreTrue,
                "Be verbose");

You may add multiple options for the same variable:

parser.refer(&mut verbose)
    .add_option(&["-v", "--verbose"], StoreTrue,
                "Be verbose")
    .add_option(&["-q", "--quiet"], StoreFalse,
                "Be verbose");

Similarly positional arguments are added:

let mut command = String::new();
parser.refer(&mut command)
    .add_argument("command", Store,
                  "Command to run");

Organizing Options

It's often useful to organize options into some kind of structure. You can easily borrow variables from the structure into option parser. For example:

struct Options {
    verbose: bool,
}
// ...
let mut options = Options { verbose: false };
parser.refer(&mut options.verbose)
    .add_option(&["-v"], StoreTrue,
                "Be verbose");

Parsing Arguments

All the complex work is done in parser.parse_args(). But there is a simpler option:

parser.parse_args_or_exit();

In case you don't want argparse to exit itself, you might use the parse_args function directly:

use std::process::exit;

match parser.parse_args() {
    Ok(()) => {}
    Err(x) => {
        std::process::exit(x);
    }
}

ArgumentParser Methods

parser.refer<T>(var: &mut T) -> Ref

Attach the variable to the argument parser. The options are added to the returned Ref object and modify a variable passed to the method.

parser.add_option(names: &[&str], action: TypedAction, help: &str)

Add a single option which has no parameters. Most options must be added by refer(..) and methods on Ref object (see below).

Example:

ap.add_option(&["-V", "--version"],
    Print(env!("CARGO_PKG_VERSION").to_string()), "Show version");

parser.set_description(descr: &str)

Set description that is at the top of help message.

parser.stop_on_first_argument(val: bool)

If called with true, parser will stop searching for options when first non-option (the one doesn't start with -) argument is encountered. This is useful if you want to parse following options with another argparser or external program.

parser.silence_double_dash(val: bool)

If called with true (default), parser will not treat first double dash -- as positional argument. Use false if you need to add some meaning to the -- marker.

parser.print_usage(name: &str, writer: &mut Write)

Print usage string to stderr.

parser.print_help(name: &str, writer: &mut Write)

Writes help to writer, used by --help option internally.

parser.parse_args()

Method that does all the dirty work and returns Result.

parser.parse_args_or_exit()

Method that does all the dirty work and in case of failure just exit().

Variable Reference Methods

The argparse::Ref object is returned from parser.refer(). The following methods are used to add and customize arguments:

option.add_option(names: &[&str], action: TypedAction, help: &str)

Add an option. All items in names should be either in format -X or --long-option (i.e. one dash and one char or two dashes and long name). How this option will be interpreted and whether it will have an argument dependes on the action. See below list of actions.

option.add_argument(name: &str, action: TypedAction, help: &str)

Add a positional argument.

option.metavar(var: &str)

A name of the argument in usage messages (for options having argument).

option.envvar(var: &str)

A name of the environment variable to get option value from. The value would be parsed with FromStr::from_str, just like an option having Store action.

option.required()

The option or argument is required (it's optional by default). If multiple options or multiple arguments are defined for this reference at least one of them is required.

Actions

The following actions are available out of the box. They may be used in either add_option or add_argument:

Store

An option has single argument. Stores a value from command-line in a variable. Any type that has the FromStr and Clone traits implemented may be used.

StoreOption

As Store, but wrap value with Some for use with Option. For example:

let mut x: Option<i32> = None; ap.refer(&mut x).add_option(&["-x"], StoreOption, "Set var x");

StoreConst(value)

An option has no arguments. Store a hard-coded value into variable, when specified. Any type with the Clone trait implemented may be used.

PushConst(value)

An option has no arguments. Push a hard-coded value into variable, when specified. Any type which has the Clone trait implemented may be used. Option might used for a list of operations to perform, when required is set for this variable, at least one operation is required.

StoreTrue

Stores boolean true value in a variable. (shortcut for StoreConst(true))

StoreFalse

Stores boolean false value in a variable. (shortcut for StoreConst(false))

IncrBy(num)

An option has no arguments. Increments the value stored in a variable by a value num. Any type which has the Add and Clone traits may be used.

DecrBy(num)

Decrements the value stored in a variable by a value num. Any type which has the Sub and Clone traits may be used.

Collect

When used for an --option, requires single argument. When used for a positional argument consumes all remaining arguments. Parsed options are added to the list. I.e. a Collect action requires a Vec<int> variable. Parses arguments using FromStr trait.

List

When used for positional argument, works the same as List. When used as an option, consumes all remaining arguments.

Note the usage of List is strongly discouraged, because of complex rules below. Use Collect and positional options if possible. But usage of List action may be useful if you need shell expansion of anything other than last positional argument.

Let's learn rules by example. For the next options:

ap.refer(&mut lst1).add_option(&["-X", "--xx"], List, "List1");
ap.refer(&mut lst2).add_argument("yy", List, "List2");

The following command line:

./run 1 2 3 -X 4 5 6

Will return [1, 2, 3] in the lst1 and the [4, 5, 6] in the lst2.

Note that using when using = or equivalent short option mode, the 'consume all' mode is not enabled. I.e. in the following command-line:

./run 1 2 -X3 4 --xx=5 6

The lst1 has [3, 5] and lst2 has [1, 2, 4, 6]. The argument consuming also stops on -- or the next option:

./run -X 1 2 3 -- 4 5 6
./run -X 1 2 --xx=3 4 5 6

Both of the above parse [4, 5, 6] as lst1 and the [1, 2, 3] as the lst2.

Print(value)

Print the text and exit (with status 0). Useful for the --version option:

ap.add_option(&["-V", "--version"],
        Print(env!("CARGO_PKG_VERSION").to_string()), "Show version");

More Repositories

1

vagga

Vagga is a containerization tool without daemons
Rust
1,842
star
2

rotor

The mio-based framework for rust for doing I/O in simple and composable way (ABANDONED)
Rust
362
star
3

quick-error

A rust-macro which makes errors easy to write
Rust
313
star
4

humantime

A parser and formatter for std::time::{SystemTime, Duration}
Rust
273
star
5

zerogw

A fast HTTP/WebSocket to zeromq gateway (UNMAINTAINED, take a look at swindon web server instead)
C
252
star
6

unshare

The low-level linux containers creation library for rust
Rust
115
star
7

rotor-http

The mio/rotor based http server library for rust (UNMAINTAINED, use tk-http)
Rust
110
star
8

lithos

Process supervisor that supports linux containers
Rust
107
star
9

dns-parser

The parser of DNS protocol packets in rust
Rust
82
star
10

knuffel

Rust KDL parser and derive implementation
Rust
72
star
11

ciruela

A peer-to-peer synchronization software for servers in datacenters.
Rust
66
star
12

tilenol

Yet another tiling window manager
Python
61
star
13

serde-regex

A serde wrapper that allows to (de)serialize regular expressions
Rust
59
star
14

probor

A protocol on top of CBOR that provides protobuf-like functionality
Rust
48
star
15

cantal

Heartbeating and monitoring solution
Rust
45
star
16

zorro

Network communication library based on greenlets, with zeromq and redis support
Python
44
star
17

trafaret-config

A small wrapper around trafaret and yaml that does nice error reporting (python)
Python
41
star
18

libwebsite

An HTTP and websocket protocol implementation for libev event loop (UNMAINTAINED, use rust and tk-http crate)
C
39
star
19

injections

Simple dependency injection library for python2 and python3
Python
39
star
20

verwalter

A tool which manages cluster of services
Rust
34
star
21

libmount

A type-safe wrapper around mount() system call for rust with good error reporting
Rust
30
star
22

tk-listen

A library that allows to listen network sockets with proper resource limits and error handling
Rust
30
star
23

nginx-config

An (unofficial) nginx configuration parser
Rust
28
star
24

tk-sendfile

A thread pool for rust/tokio that can process file requests and send data to the socket with zero copy (using sendfile)
Rust
26
star
25

resolv-conf

The /etc/resolv.conf file parser in rust
Rust
25
star
26

tk-pool

A connection pool implementation for tokio
Rust
22
star
27

cpu-time

CPU time measurement library for rust
Rust
22
star
28

openat

A wrapper around openat, symlinkat, and similar system calls
Rust
21
star
29

signal

Signal handling for rust
Rust
21
star
30

khufu

A template language for incremental-dom or DSL for javascript views
JavaScript
19
star
31

rotor-stream

The stream abstraction on top of rotor (UNMAINTAINED, use tokio)
Rust
19
star
32

abstract-ns

Abstract name service traits for rust
Rust
18
star
33

async-listen

A rust crate with various helpers for writing production-ready servers in rust using async-std
Rust
18
star
34

paperjam

Devices and commandline tools for zeromq and crossroads io
C
16
star
35

netbuf

Network buffers for rust
Rust
15
star
36

self-meter

A tiny library to measure resource usage of the process it's used in
Rust
15
star
37

rust-quire

A YAML-based configuration library for Rust
Rust
14
star
38

tokio-tutorial

My futures/tokio tutorial for Rust Belt Rust (OUT OF DATE)
Rust
13
star
39

rust-gron

A rust reimplementation of a gron utility which makes JSON greppable (https://github.com/tomnomnom/gron)
Rust
13
star
40

aio-s3

The asyncio client for Amazon S3
Python
12
star
41

trimmer

A whitespace and memory friendly template engine
Rust
12
star
42

ssh-keys

Parser of ssh public and private keys
Rust
12
star
43

coyaml

Configuration file parser generator, that uses YAML for configuration files. Currently generates only C code
C
12
star
44

sortedsets

Sorted sets implementation in pure python
Python
11
star
45

stator

A wrapper around rotor library for rust which provides C API and scripting language bindings
Rust
11
star
46

marafet

Compiler for Jade-like template language to cito.js-based virtual dom
Rust
11
star
47

httpbin-rs

A httpbin reimplementation in rust
HTML
10
star
48

quire

A YAMLy configuration parser-generator for C
C
10
star
49

vagga-docker

This is a prototype which brings vagga as the first-class tool to OS X and (possibly) windows through docker's layer of compatibility
Dockerfile
10
star
50

pyarchive

Cython-based python bindings for libarchive
C
10
star
51

procboss

Process supervisor
C
9
star
52

bulk

A tool that builds packages, updates package repos, and bumps versions
Rust
9
star
53

tk-easyloop

Thread-local loop and other simplifications for tokio loop
Rust
9
star
54

serde-str

A serde wrapper, that can be used to serialize data types using Display and FromStr
Rust
9
star
55

graphql-cli

A command-line tool for working with graphql written in rust
Rust
9
star
56

vagga-box

A virtualbox wrapper around vagga
Python
9
star
57

url-tail

A clone of unix "tail" utility which uses HTTP Range requests to watch remote files
Rust
8
star
58

ns-router

An abstraction around domain name system that allows to resolve different names by different means
Rust
7
star
59

flake8-import-graph

A flake8 lint to enforce that some modules can't be imported from other modules
Python
7
star
60

capturing-glob

A glob (file matching utility) with capture groups (similar to regex)
Rust
7
star
61

battleship

Battle ship implementation in Nim language (hackaton project)
Nim
7
star
62

serde-millis

A serde wrapper that stores integer millisecond value for timestamps and durations (used similarly to serde_bytes)
Rust
7
star
63

mglawica

A simple PaaS inspired by dokku but built with vagga, cantal, lithos, verwalter, ciruela and possibly swindon
Lua
6
star
64

pyzza

A compiler of a python-like programming language, targeting the Flash platform
Python
6
star
65

reqtxt2nix

Generator of nix expressions from pythonic requirements.txt
Python
5
star
66

aio-routes

URL routing library for asyncio
Python
5
star
67

aio-beanstalk

The asyncio client for beanstalkd work queue
Python
5
star
68

string-intern

Another implementation of string interning in rust
Rust
4
star
69

jarred

a web interface for viewing collectd statistics
JavaScript
4
star
70

dir-signature

A library to create a signature (or index) of the directory suitable for using by file synchronization utilities
Rust
4
star
71

tk-carbon

Carbon client for tokio
Rust
4
star
72

rotor-carbon

(ABANDONED. Use `tk-carbon` instead) The asynchronous rust + rotor bindings for carbon (graphite)
Python
4
star
73

objpath

A library that allows to traverse data structures by path
C
4
star
74

vagga2lithos

A tool which helps to generate lithos config from a vagga config
Python
4
star
75

tk-cantal

The cantal client library (on top of tokio main loop)
Rust
3
star
76

rotor-redis

Redis implementation for rotor library (using mio in Rust language)
Rust
3
star
77

amfy

AMF serializer/deserializer for python3
Python
3
star
78

scan_dir

A easier read_dir for rust, useful for reading directory of config files
Rust
3
star
79

magickpy

ImageMagick bindings for python3
Python
3
star
80

nginx-config-mod

A command-line utility and a rust library to validate and make certain tweaks/rewrites of nginx configs
Rust
3
star
81

tk-bufstream

A buffered stream backed by contiguous buffers for tokio (rust)
Rust
2
star
82

humannum

A human friendly format parser for numeric types
Rust
2
star
83

cantal-go

Go bindings to cantal
Go
2
star
84

mesos-tests

Few semi-automated tests of mesos in various network failure conditions
Python
2
star
85

cantal-py

Python library for cantal
Python
2
star
86

xsnano

C
2
star
87

async-presentation

Talk about asynchronous IO. WARNING: Presentation contains both good and bad examples without any markup. Use your own judgement.
CSS
2
star
88

vagga-presentation

Presentation for vagga
JavaScript
2
star
89

digest-writer

Adds an `io::Write` interface on top of `digest::Digest`
Rust
2
star
90

zerogw.com

zerogw.com website
CSS
1
star
91

containers_presentation

Linux Containers Ecosystem presentation for PyCon Ukraine 2014
CSS
1
star
92

self-meter-http

A HTTP renderer for self-meter data
Rust
1
star
93

fedor

Federated organizer (basically todo list on steroids with multiple servers support to be implemented)
JavaScript
1
star
94

dotns

And experimental name service for nanomsg
Python
1
star
95

debian-libwebsite

Debian packaging for libwebsite
C
1
star
96

clojureday-presentation

CSS
1
star
97

trimmer-derive

A derive implementation for `trimmer::Variable` trait
Rust
1
star
98

rulens

Experimental rule-based namesystem for nanomsg
Python
1
star
99

debian-coyaml

Debian packaging for coyaml
C
1
star
100

rotor-dns

A DNS resolver for rotor
Rust
1
star