Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,20 @@ Add this to your `Cargo.toml`:
getopts = "0.2"
```

## Examples

- [`required_option.rs`](examples/required_option.rs) shows how to define and
read an option that must be provided.
- [`repeated_options.rs`](examples/repeated_options.rs) shows how to collect
repeated option values and count repeated flags.

Run them from this repository with:

```console
cargo run --example required_option -- --config config.toml
cargo run --example repeated_options -- -vv -I src --include vendor
```

## Contributing

The `getopts` library is used by `rustc`, so we have to be careful about not changing its behavior.
20 changes: 20 additions & 0 deletions examples/repeated_options.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
use getopts::Options;
use std::{env, process};

fn main() {
let args: Vec<String> = env::args().collect();

let mut opts = Options::new();
opts.optmulti("I", "include", "add a directory to the search path", "DIR");
opts.optflagmulti("v", "verbose", "increase output verbosity");

let matches = opts.parse(&args[1..]).unwrap_or_else(|error| {
eprintln!("{error}");
process::exit(2);
});

println!("Verbosity: {}", matches.opt_count("verbose"));
for directory in matches.opt_strs("include") {
println!("Include: {directory}");
}
}
21 changes: 21 additions & 0 deletions examples/required_option.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
use getopts::Options;
use std::{env, process};

fn main() {
let args: Vec<String> = env::args().collect();
let program = &args[0];

let mut opts = Options::new();
opts.reqopt("c", "config", "path to the configuration file", "FILE");

let matches = opts.parse(&args[1..]).unwrap_or_else(|error| {
eprintln!("{error}");
eprintln!("{}", opts.short_usage(program));
process::exit(2);
});

let config = matches
.opt_str("config")
.expect("required options are present after parsing");
println!("Using configuration from {config}");
}