1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-30 12:37:49 +00:00

Merge pull request #2793 from tertsdiepraam/cksum-result-io-error

`cksum`: use `UIoError`
This commit is contained in:
Sylvestre Ledru 2022-01-07 21:47:01 +01:00 committed by GitHub
commit 969f3cbf39
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 42 additions and 40 deletions

View file

@ -11,8 +11,7 @@ use std::fs::File;
use std::io::{self, stdin, BufReader, Read}; use std::io::{self, stdin, BufReader, Read};
use std::path::Path; use std::path::Path;
use uucore::display::Quotable; use uucore::display::Quotable;
use uucore::error::UResult; use uucore::error::{FromIo, UResult};
use uucore::error::USimpleError;
use uucore::show; use uucore::show;
use uucore::InvalidEncodingHandling; use uucore::InvalidEncodingHandling;
@ -81,27 +80,18 @@ fn cksum(fname: &str) -> io::Result<(u32, usize)> {
let mut crc = 0u32; let mut crc = 0u32;
let mut size = 0usize; let mut size = 0usize;
let file;
let mut rd: Box<dyn Read> = match fname { let mut rd: Box<dyn Read> = match fname {
"-" => Box::new(stdin()), "-" => Box::new(stdin()),
_ => { _ => {
let path = &Path::new(fname); let p = Path::new(fname);
if path.is_dir() {
return Err(std::io::Error::new( // Directories should not give an error, but should be interpreted
io::ErrorKind::InvalidInput, // as empty files to match GNU semantics.
"Is a directory", if p.is_dir() {
)); Box::new(BufReader::new(io::empty())) as Box<dyn Read>
}; } else {
// Silent the warning as we want to the error message Box::new(BufReader::new(File::open(p)?)) as Box<dyn Read>
#[allow(clippy::question_mark)] }
if path.metadata().is_err() {
return Err(std::io::Error::new(
io::ErrorKind::NotFound,
"No such file or directory",
));
};
file = File::open(&path)?;
Box::new(BufReader::new(file))
} }
}; };
@ -136,23 +126,16 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
}; };
if files.is_empty() { if files.is_empty() {
match cksum("-") { let (crc, size) = cksum("-")?;
Ok((crc, size)) => println!("{} {}", crc, size), println!("{} {}", crc, size);
Err(err) => {
return Err(USimpleError::new(2, format!("{}", err)));
}
}
return Ok(()); return Ok(());
} }
for fname in &files { for fname in &files {
match cksum(fname.as_ref()) { match cksum(fname.as_ref()).map_err_context(|| format!("{}", fname.maybe_quote())) {
Ok((crc, size)) => println!("{} {} {}", crc, size, fname), Ok((crc, size)) => println!("{} {} {}", crc, size, fname),
Err(err) => show!(USimpleError::new( Err(err) => show!(err),
2, };
format!("{}: {}", fname.maybe_quote(), err)
)),
}
} }
Ok(()) Ok(())
} }

View file

@ -371,7 +371,7 @@ impl UError for UUsageError {
/// ``` /// ```
#[derive(Debug)] #[derive(Debug)]
pub struct UIoError { pub struct UIoError {
context: String, context: Option<String>,
inner: std::io::Error, inner: std::io::Error,
} }
@ -379,7 +379,7 @@ impl UIoError {
#[allow(clippy::new_ret_no_self)] #[allow(clippy::new_ret_no_self)]
pub fn new<S: Into<String>>(kind: std::io::ErrorKind, context: S) -> Box<dyn UError> { pub fn new<S: Into<String>>(kind: std::io::ErrorKind, context: S) -> Box<dyn UError> {
Box::new(Self { Box::new(Self {
context: context.into(), context: Some(context.into()),
inner: kind.into(), inner: kind.into(),
}) })
} }
@ -435,7 +435,11 @@ impl Display for UIoError {
capitalize(&mut message); capitalize(&mut message);
&message &message
}; };
write!(f, "{}: {}", self.context, message) if let Some(ctx) = &self.context {
write!(f, "{}: {}", ctx, message)
} else {
write!(f, "{}", message)
}
} }
} }
@ -464,7 +468,7 @@ pub trait FromIo<T> {
impl FromIo<Box<UIoError>> for std::io::Error { impl FromIo<Box<UIoError>> for std::io::Error {
fn map_err_context(self, context: impl FnOnce() -> String) -> Box<UIoError> { fn map_err_context(self, context: impl FnOnce() -> String) -> Box<UIoError> {
Box::new(UIoError { Box::new(UIoError {
context: (context)(), context: Some((context)()),
inner: self, inner: self,
}) })
} }
@ -479,12 +483,28 @@ impl<T> FromIo<UResult<T>> for std::io::Result<T> {
impl FromIo<Box<UIoError>> for std::io::ErrorKind { impl FromIo<Box<UIoError>> for std::io::ErrorKind {
fn map_err_context(self, context: impl FnOnce() -> String) -> Box<UIoError> { fn map_err_context(self, context: impl FnOnce() -> String) -> Box<UIoError> {
Box::new(UIoError { Box::new(UIoError {
context: (context)(), context: Some((context)()),
inner: std::io::Error::new(self, ""), inner: std::io::Error::new(self, ""),
}) })
} }
} }
impl From<std::io::Error> for UIoError {
fn from(f: std::io::Error) -> UIoError {
UIoError {
context: None,
inner: f,
}
}
}
impl From<std::io::Error> for Box<dyn UError> {
fn from(f: std::io::Error) -> Box<dyn UError> {
let u_error: UIoError = f.into();
Box::new(u_error) as Box<dyn UError>
}
}
/// Shorthand to construct [`UIoError`]-instances. /// Shorthand to construct [`UIoError`]-instances.
/// ///
/// This macro serves as a convenience call to quickly construct instances of /// This macro serves as a convenience call to quickly construct instances of

View file

@ -74,9 +74,8 @@ fn test_invalid_file() {
at.mkdir(folder_name); at.mkdir(folder_name);
ts.ucmd() ts.ucmd()
.arg(folder_name) .arg(folder_name)
.fails() .succeeds()
.no_stdout() .stdout_only("4294967295 0 asdf\n");
.stderr_contains("cksum: asdf: Is a directory");
} }
// Make sure crc is correct for files larger than 32 bytes // Make sure crc is correct for files larger than 32 bytes