From 557e7ddab371d41a576c81efffe20a6496ff9dcd Mon Sep 17 00:00:00 2001 From: Alex Date: Sat, 7 Sep 2024 21:43:00 -0700 Subject: [PATCH] Add option to print version and exit --- src/main.rs | 2 +- src/parse_args.rs | 16 ++++++++++++---- src/test.rs | 7 ++++++- 3 files changed, 19 insertions(+), 6 deletions(-) diff --git a/src/main.rs b/src/main.rs index 74a9445..3f6d9cb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -169,7 +169,7 @@ fn real_main() -> Result<(), Box> { &config, )?), parse_args::ParseArgsResult::Error(err) => Err(Box::new(err)), - parse_args::ParseArgsResult::Help => Ok(()), + parse_args::ParseArgsResult::PrintAndExit => Ok(()), } } diff --git a/src/parse_args.rs b/src/parse_args.rs index 532357a..682048f 100644 --- a/src/parse_args.rs +++ b/src/parse_args.rs @@ -31,12 +31,12 @@ impl Default for OutputConfig { pub enum ParseArgsResult { Config(Config), Error(SimpleError), - Help, + PrintAndExit, } enum ParseArgsResultInner { Success, Error(SimpleError), - Help, + PrintAndExit, } #[derive(Default)] @@ -102,6 +102,10 @@ fn print_help() { } } +fn print_version() { + println!("hunk v{}", env!("CARGO_PKG_VERSION")); +} + pub fn parse_args(args: &[&str]) -> ParseArgsResult { struct ParsingState { has_search_string: bool, @@ -185,7 +189,11 @@ pub fn parse_args(args: &[&str]) -> ParseArgsResult { )), ["--help"] | ["-h"] => { print_help(); - ParseArgsResultInner::Help + ParseArgsResultInner::PrintAndExit + } + ["--version"] => { + print_version(); + ParseArgsResultInner::PrintAndExit } ["--", rest @ ..] if !state.has_search_string => { state.no_more_options = true; @@ -231,7 +239,7 @@ pub fn parse_args(args: &[&str]) -> ParseArgsResult { match parse_slice(args, &mut parsing_state, &mut config) { ParseArgsResultInner::Error(err) => ParseArgsResult::Error(err), ParseArgsResultInner::Success => ParseArgsResult::Config(config), - ParseArgsResultInner::Help => ParseArgsResult::Help, + ParseArgsResultInner::PrintAndExit => ParseArgsResult::PrintAndExit, } } diff --git a/src/test.rs b/src/test.rs index fdec89c..94143be 100644 --- a/src/test.rs +++ b/src/test.rs @@ -503,6 +503,11 @@ mod tests { #[test] fn test_parse_help() { - matches!(parse_args(&vec!["asd", "-h"]), ParseArgsResult::Help); + matches!(parse_args(&vec!["asd", "-h"]), ParseArgsResult::PrintAndExit); + } + + #[test] + fn test_parse_version() { + matches!(parse_args(&vec!["hi", "--version"]), ParseArgsResult::PrintAndExit); } }