sum: return UResult from uumain() function

This commit is contained in:
Jeffrey Finkelstein 2021-12-31 13:53:36 -05:00
parent cb051e7416
commit 29d7103670

View file

@ -12,9 +12,10 @@ extern crate uucore;
use clap::{crate_version, App, Arg}; use clap::{crate_version, App, Arg};
use std::fs::File; use std::fs::File;
use std::io::{stdin, Read, Result}; use std::io::{stdin, Read};
use std::path::Path; use std::path::Path;
use uucore::display::Quotable; use uucore::display::Quotable;
use uucore::error::{FromIo, UResult, USimpleError};
use uucore::InvalidEncodingHandling; use uucore::InvalidEncodingHandling;
static NAME: &str = "sum"; static NAME: &str = "sum";
@ -65,26 +66,25 @@ fn sysv_sum(mut reader: Box<dyn Read>) -> (usize, u16) {
(blocks_read, ret as u16) (blocks_read, ret as u16)
} }
fn open(name: &str) -> Result<Box<dyn Read>> { fn open(name: &str) -> UResult<Box<dyn Read>> {
match name { match name {
"-" => Ok(Box::new(stdin()) as Box<dyn Read>), "-" => Ok(Box::new(stdin()) as Box<dyn Read>),
_ => { _ => {
let path = &Path::new(name); let path = &Path::new(name);
if path.is_dir() { if path.is_dir() {
return Err(std::io::Error::new( return Err(USimpleError::new(
std::io::ErrorKind::InvalidInput, 2,
"Is a directory", format!("{}: Is a directory", name.maybe_quote()),
)); ));
}; };
// Silent the warning as we want to the error message // Silent the warning as we want to the error message
#[allow(clippy::question_mark)]
if path.metadata().is_err() { if path.metadata().is_err() {
return Err(std::io::Error::new( return Err(USimpleError::new(
std::io::ErrorKind::NotFound, 2,
"No such file or directory", format!("{}: No such file or directory", name.maybe_quote()),
)); ));
}; };
let f = File::open(path)?; let f = File::open(path).map_err_context(String::new)?;
Ok(Box::new(f) as Box<dyn Read>) Ok(Box::new(f) as Box<dyn Read>)
} }
} }
@ -96,7 +96,8 @@ mod options {
pub static SYSTEM_V_COMPATIBLE: &str = "sysv"; pub static SYSTEM_V_COMPATIBLE: &str = "sysv";
} }
pub fn uumain(args: impl uucore::Args) -> i32 { #[uucore_procs::gen_uumain]
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let args = args let args = args
.collect_str(InvalidEncodingHandling::ConvertLossy) .collect_str(InvalidEncodingHandling::ConvertLossy)
.accept_any(); .accept_any();
@ -116,13 +117,11 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
files.len() > 1 files.len() > 1
}; };
let mut exit_code = 0;
for file in &files { for file in &files {
let reader = match open(file) { let reader = match open(file) {
Ok(f) => f, Ok(f) => f,
Err(error) => { Err(error) => {
show_error!("{}: {}", file.maybe_quote(), error); show!(error);
exit_code = 2;
continue; continue;
} }
}; };
@ -138,8 +137,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
println!("{} {}", sum, blocks); println!("{} {}", sum, blocks);
} }
} }
Ok(())
exit_code
} }
pub fn uu_app() -> App<'static, 'static> { pub fn uu_app() -> App<'static, 'static> {