From ab4036297b16855ce51c3302a5ddaa390a83d163 Mon Sep 17 00:00:00 2001 From: Jeffrey Finkelstein Date: Sun, 16 Jan 2022 13:47:18 -0500 Subject: [PATCH] head: use uucore error handling instead of custom Use `show!()` and `USimpleError` to handle I/O errors instead of using custom code. --- src/uu/head/src/head.rs | 39 +++++++++++++++------------------------ 1 file changed, 15 insertions(+), 24 deletions(-) diff --git a/src/uu/head/src/head.rs b/src/uu/head/src/head.rs index e3325d084..3f6c8dfab 100644 --- a/src/uu/head/src/head.rs +++ b/src/uu/head/src/head.rs @@ -10,8 +10,8 @@ use std::convert::TryFrom; use std::ffi::OsString; use std::io::{self, BufWriter, ErrorKind, Read, Seek, SeekFrom, Write}; use uucore::display::Quotable; -use uucore::error::{UResult, USimpleError}; -use uucore::show_error_custom_description; +use uucore::error::{FromIo, UError, UResult, USimpleError}; +use uucore::show; const BUF_SIZE: usize = 65536; @@ -367,7 +367,6 @@ fn head_file(input: &mut std::fs::File, options: &HeadOptions) -> std::io::Resul } fn uu_head(options: &HeadOptions) -> UResult<()> { - let mut error_count = 0; let mut first = true; for file in &options.files { let res = match file.as_str() { @@ -401,19 +400,10 @@ fn uu_head(options: &HeadOptions) -> UResult<()> { let mut file = match std::fs::File::open(name) { Ok(f) => f, Err(err) => { - let prefix = format!("cannot open {} for reading", name.quote()); - match err.kind() { - ErrorKind::NotFound => { - show_error_custom_description!(prefix, "No such file or directory"); - } - ErrorKind::PermissionDenied => { - show_error_custom_description!(prefix, "Permission denied"); - } - _ => { - show_error_custom_description!(prefix, "{}", err); - } - } - error_count += 1; + show!(err.map_err_context(|| format!( + "cannot open {} for reading", + name.quote() + ))); continue; } }; @@ -432,17 +422,18 @@ fn uu_head(options: &HeadOptions) -> UResult<()> { } else { file }; - let prefix = format!("error reading {}", name); - show_error_custom_description!(prefix, "Input/output error"); - error_count += 1; + show!(USimpleError::new( + 1, + format!("error reading {}: Input/output error", name) + )); } first = false; } - if error_count > 0 { - Err(USimpleError::new(1, "")) - } else { - Ok(()) - } + // Even though this is returning `Ok`, it is possible that a call + // to `show!()` and thus a call to `set_exit_code()` has been + // called above. If that happens, then this process will exit with + // a non-zero exit code. + Ok(()) } #[uucore_procs::gen_uumain]