From f8181ee5834ad07e6fe74f6db219e37a79c8cc66 Mon Sep 17 00:00:00 2001 From: Mohammad Kanaan Date: Mon, 27 Jul 2026 13:50:12 +0300 Subject: [PATCH] feat: implement proper cli exit codes --- src/main.rs | 29 +++++++++++++++++++++-------- src/matches.rs | 6 ++++++ test.txt | 2 ++ 3 files changed, 29 insertions(+), 8 deletions(-) diff --git a/src/main.rs b/src/main.rs index 6087b71..235f036 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,8 @@ +use std::process::ExitCode; + use clap::Parser; + +use crate::matches::Matches; mod matches; mod parser; @@ -8,16 +12,25 @@ struct Cli { file_path: String, } -fn main() -> anyhow::Result<()> { +fn main() -> ExitCode { + match run() { + Ok(matches) if matches.is_empty() == true => ExitCode::FAILURE, + Ok(matches) => { + println!("{}", matches); + ExitCode::SUCCESS + } + Err(error) => { + eprintln!("{}", error); + ExitCode::from(2) + } + } +} + +fn run() -> anyhow::Result { let cli = Cli::parse(); let lines_iter = parser::read_lines(&cli.file_path)?; - let matches = parser::match_pattern(lines_iter, &cli.pattern, &cli.file_path); + let matches = parser::match_pattern(lines_iter, &cli.pattern, &cli.file_path)?; - println!("Pattern: {}", cli.pattern); - println!("File path: {}", cli.file_path); - println!("---"); - println!("{}", matches?); - - Ok(()) + Ok(matches) } diff --git a/src/matches.rs b/src/matches.rs index 7461f02..0cc950a 100644 --- a/src/matches.rs +++ b/src/matches.rs @@ -11,6 +11,12 @@ pub struct Matches { pub pattern: String, } +impl Matches { + pub fn is_empty(&self) -> bool { + self.items.is_empty() + } +} + impl Display for Match { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}: line {}: {}", self.file_name, self.line_number, self.text) diff --git a/test.txt b/test.txt index 0c21a56..b75105e 100644 --- a/test.txt +++ b/test.txt @@ -1,2 +1,4 @@ hola no +hola again +yep it's me