Skip to main content

nonstandard/
nonstandard.rs

1//! Some programs accept options with an unusual syntax. For example, tail
2//! accepts `-13` as an alias for `-n 13`.
3//!
4//! This program shows how to use `Parser::try_raw_args()` to handle them
5//! manually.
6//!
7//! (Note: actual tail implementations handle it slightly differently! This
8//! is just an example.)
9
10use std::path::PathBuf;
11
12fn parse_dashnum(parser: &mut lexopt::Parser) -> Option<u64> {
13    let mut raw = parser.try_raw_args()?;
14    let arg = raw.peek()?.to_str()?;
15    let num = arg.strip_prefix('-')?.parse::<u64>().ok()?;
16    raw.next(); // Consume the argument we just parsed
17    Some(num)
18}
19
20fn main() -> Result<(), lexopt::Error> {
21    use lexopt::prelude::*;
22
23    let mut parser = lexopt::Parser::from_env();
24    loop {
25        if let Some(num) = parse_dashnum(&mut parser) {
26            println!("Got number {}", num);
27        } else if let Some(arg) = parser.next()? {
28            match arg {
29                Short('f') | Long("follow") => {
30                    println!("Got --follow");
31                }
32                Short('n') | Long("number") => {
33                    let num: u64 = parser.value()?.parse()?;
34                    println!("Got number {}", num);
35                }
36                Value(path) => {
37                    let path = PathBuf::from(path);
38                    println!("Got file {}", path.display());
39                }
40                _ => return Err(arg.unexpected()),
41            }
42        } else {
43            break;
44        }
45    }
46
47    Ok(())
48}