From 0fe86b229a76de1693d6d2a7edf5c30bc7e25b16 Mon Sep 17 00:00:00 2001 From: Herrtian <70463940+Herrtian@users.noreply.github.com> Date: Thu, 23 Jul 2026 21:00:47 +0200 Subject: [PATCH] Add required and repeated option examples --- README.md | 14 ++++++++++++++ examples/repeated_options.rs | 20 ++++++++++++++++++++ examples/required_option.rs | 21 +++++++++++++++++++++ 3 files changed, 55 insertions(+) create mode 100644 examples/repeated_options.rs create mode 100644 examples/required_option.rs diff --git a/README.md b/README.md index 34ebe565..83d309d0 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/examples/repeated_options.rs b/examples/repeated_options.rs new file mode 100644 index 00000000..d381faf2 --- /dev/null +++ b/examples/repeated_options.rs @@ -0,0 +1,20 @@ +use getopts::Options; +use std::{env, process}; + +fn main() { + let args: Vec = 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}"); + } +} diff --git a/examples/required_option.rs b/examples/required_option.rs new file mode 100644 index 00000000..905739b1 --- /dev/null +++ b/examples/required_option.rs @@ -0,0 +1,21 @@ +use getopts::Options; +use std::{env, process}; + +fn main() { + let args: Vec = 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}"); +}