Skip to content

Commit f0aff87

Browse files
authored
Rewrite docs using Markdown
crates.io does not support reStructuredText
1 parent 3b3848a commit f0aff87

File tree

2 files changed

+327
-1
lines changed

2 files changed

+327
-1
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
name = "argparse"
44
description = "Powerful command-line argument parsing library"
55
license = "MIT"
6-
readme = "README.rst"
6+
readme = "README.md"
77
keywords = ["command-line", "cli", "command", "argument"]
88
categories = ["command-line-interface"]
99
homepage = "http://github.com/tailhook/rust-argparse"

README.md

Lines changed: 326 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,326 @@
1+
# Argparse
2+
3+
The `rust-argparse` is a command-line parsing module for Rust. It's inspired by Python's `argparse` module.
4+
5+
Features:
6+
7+
- Supports standard (GNU) option conventions
8+
- Properly typed values
9+
- Automatically generated help and usage messages
10+
11+
## Importing
12+
13+
Edit your Cargo.toml to add `rust-argparse` to your project.
14+
15+
```toml
16+
[dependencies]
17+
argparse = "0.2.2"
18+
```
19+
20+
## Example
21+
22+
The following code is a simple Rust program with command-line arguments:
23+
24+
```rs
25+
extern crate argparse;
26+
27+
use argparse::{ArgumentParser, StoreTrue, Store};
28+
29+
fn main() {
30+
let mut verbose = false;
31+
let mut name = "World".to_string();
32+
{ // this block limits scope of borrows by ap.refer() method
33+
let mut ap = ArgumentParser::new();
34+
ap.set_description("Greet somebody.");
35+
ap.refer(&mut verbose)
36+
.add_option(&["-v", "--verbose"], StoreTrue,
37+
"Be verbose");
38+
ap.refer(&mut name)
39+
.add_option(&["--name"], Store,
40+
"Name for the greeting");
41+
ap.parse_args_or_exit();
42+
}
43+
44+
if verbose {
45+
println!("name is {}", name);
46+
}
47+
println!("Hello {}!", name);
48+
}
49+
```
50+
51+
Assuming the Rust code above is saved into a file `greeting.rs`, let's see what we have now:
52+
53+
```
54+
$ rustc greeting.rs
55+
$ ./greeting -h
56+
Usage:
57+
./greeting [OPTIONS]
58+
59+
Greet somebody.
60+
61+
Optional arguments:
62+
-h, --help Show this help message and exit
63+
-v, --verbose
64+
Be verbose
65+
--name NAME Name for the greeting
66+
$ ./greeting
67+
Hello World!
68+
$ ./greeting --name Bob
69+
Hello Bob!
70+
$ ./greeting -v --name Alice
71+
name is Alice
72+
Hello Alice!
73+
```
74+
75+
## Basic Workflow
76+
77+
### Create ArgumentParser
78+
79+
The argument parser is created empty and is built incrementally. So we create a mutable variable:
80+
81+
```rs
82+
extern crate argparse;
83+
use argparse::ArgumentParser;
84+
85+
let mut parser = ArgumentParser::new();
86+
```
87+
88+
### Customize
89+
90+
There are optional customization methods. The most important one is:
91+
92+
```rs
93+
parser.set_description("My command-line utility");
94+
```
95+
96+
The description is rewrapped to fit 80 column string nicely. Just like option descriptions.
97+
98+
### Add Options
99+
100+
The `refer` method creates a cell variable, which the result will be written to:
101+
102+
```rs
103+
let mut verbose = false;
104+
parser.refer(&mut verbose);
105+
```
106+
107+
Next we add options which control the variable. For example:
108+
109+
```rs
110+
parser.refer(&mut verbose)
111+
.add_option(&["-v", "--verbose"], StoreTrue,
112+
"Be verbose");
113+
```
114+
115+
You may add multiple options for the same variable:
116+
117+
```rs
118+
parser.refer(&mut verbose)
119+
.add_option(&["-v", "--verbose"], StoreTrue,
120+
"Be verbose")
121+
.add_option(&["-q", "--quiet"], StoreFalse,
122+
"Be verbose");
123+
```
124+
125+
Similarly positional arguments are added:
126+
127+
```rs
128+
let mut command = String::new();
129+
parser.refer(&mut command)
130+
.add_argument("command", Store,
131+
"Command to run");
132+
```
133+
134+
### Organizing Options
135+
136+
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:
137+
138+
```rs
139+
struct Options {
140+
verbose: bool,
141+
}
142+
// ...
143+
let mut options = Options { verbose: false };
144+
parser.refer(&mut options.verbose)
145+
.add_option(&["-v"], StoreTrue,
146+
"Be verbose");
147+
```
148+
149+
### Parsing Arguments
150+
151+
All the complex work is done in `parser.parse_args()`. But there is a simpler option:
152+
153+
```rs
154+
parser.parse_args_or_exit();
155+
```
156+
157+
In case you don't want argparse to exit itself, you might use the `parse_args` function directly:
158+
159+
```rs
160+
use std::process::exit;
161+
162+
match parser.parse_args() {
163+
Ok(()) => {}
164+
Err(x) => {
165+
std::process::exit(x);
166+
}
167+
}
168+
```
169+
170+
## ArgumentParser Methods
171+
172+
***`parser.refer<T>(var: &mut T) -> Ref`***
173+
174+
Attach the variable to the argument parser. The options are added to the returned `Ref` object and modify a variable passed to the method.
175+
176+
***`parser.add_option(names: &[&str], action: TypedAction, help: &str)`***
177+
178+
Add a single option which has no parameters. Most options must be added by `refer(..)` and methods on `Ref` object (see below).
179+
180+
Example:
181+
182+
```rs
183+
ap.add_option(&["-V", "--version"],
184+
Print(env!("CARGO_PKG_VERSION").to_string()), "Show version");
185+
```
186+
187+
***`parser.set_description(descr: &str)`***
188+
189+
Set description that is at the top of help message.
190+
191+
***`parser.stop_on_first_argument(val: bool)`***
192+
193+
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.
194+
195+
***`parser.silence_double_dash(val: bool)`***
196+
197+
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.
198+
199+
***`parser.print_usage(name: &str, writer: &mut Write)`***
200+
201+
Print usage string to stderr.
202+
203+
***`parser.print_help(name: &str, writer: &mut Write)`***
204+
205+
Writes help to `writer`, used by `--help` option internally.
206+
207+
***`parser.parse_args()`***
208+
209+
Method that does all the dirty work and returns `Result`.
210+
211+
***`parser.parse_args_or_exit()`***
212+
213+
Method that does all the dirty work and in case of failure just `exit()`.
214+
215+
## Variable Reference Methods
216+
217+
The `argparse::Ref` object is returned from `parser.refer()`. The following methods are used to add and customize arguments:
218+
219+
***`option.add_option(names: &[&str], action: TypedAction, help: &str)`***
220+
221+
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.
222+
223+
***`option.add_argument(name: &str, action: TypedAction, help: &str)`***
224+
225+
Add a positional argument.
226+
227+
***`option.metavar(var: &str)`***
228+
229+
A name of the argument in usage messages (for options having argument).
230+
231+
***`option.envvar(var: &str)`***
232+
233+
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.
234+
235+
***`option.required()`***
236+
237+
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.
238+
239+
## Actions
240+
241+
The following actions are available out of the box. They may be used in either `add_option` or `add_argument`:
242+
243+
***`Store`***
244+
245+
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.
246+
247+
***`StoreOption`***
248+
249+
As `Store`, but wrap value with `Some` for use with `Option`. For example:
250+
251+
```rs
252+
let mut x: Option<i32> = None; ap.refer(&mut x).add_option(&["-x"], StoreOption, "Set var x");
253+
```
254+
255+
***`StoreConst(value)`***
256+
257+
An option has no arguments. Store a hard-coded `value` into variable, when specified. Any type with the `Clone` trait implemented may be used.
258+
259+
***`PushConst(value)`***
260+
261+
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.
262+
263+
***`StoreTrue`***
264+
265+
Stores boolean `true` value in a variable. (shortcut for `StoreConst(true)`)
266+
267+
***`StoreFalse`***
268+
269+
Stores boolean `false` value in a variable. (shortcut for `StoreConst(false)`)
270+
271+
***`IncrBy(num)`***
272+
273+
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.
274+
275+
***`DecrBy(num)`***
276+
277+
Decrements the value stored in a variable by a value `num`. Any type which has the `Sub` and `Clone` traits may be used.
278+
279+
***`Collect`***
280+
281+
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.
282+
283+
***`List`***
284+
285+
When used for positional argument, works the same as `List`. When used as an option, consumes all remaining arguments.
286+
287+
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.
288+
289+
Let's learn rules by example. For the next options:
290+
291+
```rs
292+
ap.refer(&mut lst1).add_option(&["-X", "--xx"], List, "List1");
293+
ap.refer(&mut lst2).add_argument("yy", List, "List2");
294+
```
295+
296+
The following command line:
297+
298+
```
299+
./run 1 2 3 -X 4 5 6
300+
```
301+
302+
Will return `[1, 2, 3]` in the `lst1` and the `[4, 5, 6]` in the `lst2`.
303+
304+
Note that using when using `=` or equivalent short option mode, the 'consume all' mode is not enabled. I.e. in the following command-line:
305+
306+
```
307+
./run 1 2 -X3 4 --xx=5 6
308+
```
309+
310+
The `lst1` has `[3, 5]` and `lst2` has `[1, 2, 4, 6]`. The argument consuming also stops on `--` or the next option:
311+
312+
```
313+
./run -X 1 2 3 -- 4 5 6
314+
./run -X 1 2 --xx=3 4 5 6
315+
```
316+
317+
Both of the above parse `[4, 5, 6]` as `lst1` and the `[1, 2, 3]` as the `lst2`.
318+
319+
***`Print(value)`***
320+
321+
Print the text and exit (with status `0`). Useful for the `--version` option:
322+
323+
```rs
324+
ap.add_option(&["-V", "--version"],
325+
Print(env!("CARGO_PKG_VERSION").to_string()), "Show version");
326+
```

0 commit comments

Comments
 (0)