structopt_utilities/
traits.rs

1use super::completions;
2use std::{env::args, ffi::OsString, process::exit};
3use structopt::{clap, StructOpt};
4
5/// Utility trait for all `StructOpt` types.
6pub trait StructOptUtils: StructOpt + Sized {
7    /// If the flags are invalid or unknown, print error and exit with code 1.
8    /// If `--help`, print help message and exit with code 0.
9    /// If `--version`, print version and exit with code 0.
10    /// Otherwise, return parsing result.
11    fn strict_from_iter(input: impl IntoIterator<Item = impl Into<OsString> + Clone>) -> Self {
12        match Self::from_iter_safe(input) as Result<Self, clap::Error> {
13            Ok(value) => value,
14            Err(clap::Error { kind, message, .. }) => match kind {
15                clap::ErrorKind::HelpDisplayed | clap::ErrorKind::VersionDisplayed => {
16                    println!("{}", message);
17                    exit(0);
18                }
19                _ => {
20                    eprintln!("{}", message);
21                    exit(1);
22                }
23            },
24        }
25    }
26
27    /// Apply `parse_strict` on main CLI arguments.
28    fn strict_from_args() -> Self {
29        Self::strict_from_iter(args())
30    }
31
32    /// Run completion generator program.
33    fn run_completion_generator(name: &str, bin: &str) {
34        completions::App::new(name, bin).exec::<Self>()
35    }
36}
37
38impl<Args: StructOpt> StructOptUtils for Args {}