diff --git a/src/main.rs b/src/main.rs index 7ec6450..415f9fd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -20,12 +20,7 @@ use hyper_util as _; use indicatif as _; use regex as _; -fn print_help(error: Option) { - let error = if let Some(err_msg) = error { - format!("{}\n", err_msg) - } else { - String::new() - }; +fn print_help(error: String) { let first_line = if cfg!(feature = "http") { "wait-for-them [-t timeout] [-s] host:port|url [host:port|url [host:port|url...]] [-- command [arg [arg...]]" } else { @@ -57,10 +52,18 @@ async fn main() { silent, } = match options::parse(args) { Ok(options) => options, - Err(message) => { + Err(options::Action::Failed(message)) => { print_help(message); exit(999); } + Err(options::Action::Version) => { + println!("wait-for-them {}", env!("CARGO_PKG_VERSION")); + exit(0); + } + Err(options::Action::Help) => { + print_help(String::new()); + exit(0); + } }; let instant = Instant::now(); diff --git a/src/options.rs b/src/options.rs index 883fa48..af3db3b 100644 --- a/src/options.rs +++ b/src/options.rs @@ -1,6 +1,6 @@ use wait_for_them::ToCheck; -#[derive(Default)] +#[derive(Default, PartialEq, Debug)] pub struct Options { pub to_check: Vec, pub timeout: Option, @@ -14,7 +14,14 @@ enum ParseState { Command, } -pub fn parse(args: Vec) -> Result> { +#[derive(PartialEq, Debug)] +pub enum Action { + Help, + Version, + Failed(String), +} + +pub fn parse(args: Vec) -> Result { let mut options = Options::default(); let mut state = ParseState::Host; @@ -34,26 +41,29 @@ pub fn parse(args: Vec) -> Result> { ParseState::Timeout => { options.timeout = Some( arg.parse() - .map_err(|_| Some("Failed to parse timeout".to_string()))?, + .map_err(|_| Action::Failed("Failed to parse timeout".to_string()))?, ); state = ParseState::Host; } ParseState::Host => match arg.as_ref() { "-t" | "--timeout" => state = ParseState::Timeout, "-s" | "--silent" => options.silent = true, - "-h" | "--help" => return Err(None), + "-v" | "--version" => return Err(Action::Version), + "-h" | "--help" => return Err(Action::Help), "--" => { state = ParseState::Command; } _ => { - options.to_check.push(arg.parse::()?); + options + .to_check + .push(arg.parse::().map_err(|e| Action::Failed(e))?); } }, } } if options.to_check.is_empty() { - Err(Some( + Err(Action::Failed( "You need to set at least one item to verify".to_string(), )) } else { @@ -116,6 +126,22 @@ mod tests { assert!(options.unwrap().silent); } + #[test] + fn version() { + assert_eq!( + parse(vec!["--version".into(), "www.example.com:888".into()]), + Err(super::Action::Version) + ); + } + + #[test] + fn help() { + assert_eq!( + parse(vec!["--help".into(), "www.example.com:888".into()]), + Err(super::Action::Help) + ); + } + #[cfg(feature = "http")] #[test] fn uri() {