From 1241db48069906973e6ef1c200d3eb1199fc3fe9 Mon Sep 17 00:00:00 2001 From: Olivier Tilloy Date: Wed, 21 Feb 2024 22:43:17 +0100 Subject: [PATCH] Match GNU diff's implementation for exit codes (fixes #17) --- src/main.rs | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/src/main.rs b/src/main.rs index 8a3e74e..a684ff4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,6 +8,7 @@ use std::env; use std::fs; use std::io::{self, Write}; +use std::process::{exit, ExitCode}; mod context_diff; mod ed_diff; @@ -15,25 +16,35 @@ mod normal_diff; mod params; mod unified_diff; -fn main() -> Result<(), String> { +// Exit codes are documented at +// https://www.gnu.org/software/diffutils/manual/html_node/Invoking-diff.html. +// An exit status of 0 means no differences were found, +// 1 means some differences were found, +// and 2 means trouble. +fn main() -> ExitCode { let opts = env::args_os(); let Params { from, to, context_count, format, - } = parse_params(opts)?; + } = parse_params(opts).unwrap_or_else(|error| { + eprintln!("{error}"); + exit(2); + }); // read files let from_content = match fs::read(&from) { Ok(from_content) => from_content, Err(e) => { - return Err(format!("Failed to read from-file: {e}")); + eprintln!("Failed to read from-file: {e}"); + return ExitCode::from(2); } }; let to_content = match fs::read(&to) { Ok(to_content) => to_content, Err(e) => { - return Err(format!("Failed to read to-file: {e}")); + eprintln!("Failed to read to-file: {e}"); + return ExitCode::from(2); } }; // run diff @@ -53,8 +64,15 @@ fn main() -> Result<(), String> { &to.to_string_lossy(), context_count, ), - Format::Ed => ed_diff::diff(&from_content, &to_content)?, + Format::Ed => ed_diff::diff(&from_content, &to_content).unwrap_or_else(|error| { + eprintln!("{error}"); + exit(2); + }), }; io::stdout().write_all(&result).unwrap(); - Ok(()) + if result.is_empty() { + ExitCode::SUCCESS + } else { + ExitCode::from(1) + } }