1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-27 19:17:43 +00:00

replace Error::new(ErrorKind::Other, _) as suggested by clippy

See also:
https://rust-lang.github.io/rust-clippy/master/index.html#io_other_error
This commit is contained in:
Ben Wiederhake 2025-04-13 03:49:08 +02:00
parent e4c7bd0641
commit 11cd0b1bbf
10 changed files with 68 additions and 97 deletions

View file

@ -267,7 +267,7 @@ fn open_file(name: &str, line_ending: LineEnding) -> io::Result<LineReader> {
Ok(LineReader::new(Input::Stdin(stdin()), line_ending)) Ok(LineReader::new(Input::Stdin(stdin()), line_ending))
} else { } else {
if metadata(name)?.is_dir() { if metadata(name)?.is_dir() {
return Err(io::Error::new(io::ErrorKind::Other, "Is a directory")); return Err(io::Error::other("Is a directory"));
} }
let f = File::open(name)?; let f = File::open(name)?;
Ok(LineReader::new( Ok(LineReader::new(

View file

@ -580,20 +580,18 @@ fn read_files_from(file_name: &str) -> Result<Vec<PathBuf>, std::io::Error> {
// First, check if the file_name is a directory // First, check if the file_name is a directory
let path = PathBuf::from(file_name); let path = PathBuf::from(file_name);
if path.is_dir() { if path.is_dir() {
return Err(std::io::Error::new( return Err(std::io::Error::other(format!(
std::io::ErrorKind::Other, "{file_name}: read error: Is a directory"
format!("{file_name}: read error: Is a directory"), )));
));
} }
// Attempt to open the file and handle the error if it does not exist // Attempt to open the file and handle the error if it does not exist
match File::open(file_name) { match File::open(file_name) {
Ok(file) => Box::new(BufReader::new(file)), Ok(file) => Box::new(BufReader::new(file)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => { Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
return Err(std::io::Error::new( return Err(std::io::Error::other(format!(
std::io::ErrorKind::Other, "cannot open '{file_name}' for reading: No such file or directory"
format!("cannot open '{file_name}' for reading: No such file or directory"), )));
));
} }
Err(e) => return Err(e), Err(e) => return Err(e),
} }
@ -637,13 +635,10 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let files = if let Some(file_from) = matches.get_one::<String>(options::FILES0_FROM) { let files = if let Some(file_from) = matches.get_one::<String>(options::FILES0_FROM) {
if file_from == "-" && matches.get_one::<String>(options::FILE).is_some() { if file_from == "-" && matches.get_one::<String>(options::FILE).is_some() {
return Err(std::io::Error::new( return Err(std::io::Error::other(format!(
std::io::ErrorKind::Other, "extra operand {}\nfile operands cannot be combined with --files0-from",
format!( matches.get_one::<String>(options::FILE).unwrap().quote()
"extra operand {}\nfile operands cannot be combined with --files0-from", ))
matches.get_one::<String>(options::FILE).unwrap().quote()
),
)
.into()); .into());
} }

View file

@ -370,7 +370,7 @@ fn handle_two_paths(source: &Path, target: &Path, opts: &Options) -> UResult<()>
OverwriteMode::NoClobber => return Ok(()), OverwriteMode::NoClobber => return Ok(()),
OverwriteMode::Interactive => { OverwriteMode::Interactive => {
if !prompt_yes!("overwrite {}? ", target.quote()) { if !prompt_yes!("overwrite {}? ", target.quote()) {
return Err(io::Error::new(io::ErrorKind::Other, "").into()); return Err(io::Error::other("").into());
} }
} }
OverwriteMode::Force => {} OverwriteMode::Force => {}
@ -609,7 +609,7 @@ fn rename(
if opts.update == UpdateMode::ReplaceNoneFail { if opts.update == UpdateMode::ReplaceNoneFail {
let err_msg = format!("not replacing {}", to.quote()); let err_msg = format!("not replacing {}", to.quote());
return Err(io::Error::new(io::ErrorKind::Other, err_msg)); return Err(io::Error::other(err_msg));
} }
match opts.overwrite { match opts.overwrite {
@ -621,7 +621,7 @@ fn rename(
} }
OverwriteMode::Interactive => { OverwriteMode::Interactive => {
if !prompt_yes!("overwrite {}?", to.quote()) { if !prompt_yes!("overwrite {}?", to.quote()) {
return Err(io::Error::new(io::ErrorKind::Other, "")); return Err(io::Error::other(""));
} }
} }
OverwriteMode::Force => {} OverwriteMode::Force => {}
@ -640,7 +640,7 @@ fn rename(
if is_empty_dir(to) { if is_empty_dir(to) {
fs::remove_dir(to)?; fs::remove_dir(to)?;
} else { } else {
return Err(io::Error::new(io::ErrorKind::Other, "Directory not empty")); return Err(io::Error::other("Directory not empty"));
} }
} }
} }
@ -756,7 +756,7 @@ fn rename_with_fallback(
io::ErrorKind::PermissionDenied, io::ErrorKind::PermissionDenied,
"Permission denied", "Permission denied",
)), )),
_ => Err(io::Error::new(io::ErrorKind::Other, format!("{err:?}"))), _ => Err(io::Error::other(format!("{err:?}"))),
}; };
} }
} else { } else {
@ -811,8 +811,7 @@ fn rename_symlink_fallback(from: &Path, to: &Path) -> io::Result<()> {
} }
#[cfg(not(any(windows, unix)))] #[cfg(not(any(windows, unix)))]
{ {
return Err(io::Error::new( return Err(io::Error::other(
io::ErrorKind::Other,
"your operating system does not support symlinks", "your operating system does not support symlinks",
)); ));
} }

View file

@ -4,7 +4,7 @@
// file that was distributed with this source code. // file that was distributed with this source code.
use std::env; use std::env;
use std::io::Write; use std::io::Write;
use std::io::{BufWriter, Error, ErrorKind, Result}; use std::io::{BufWriter, Error, Result};
use std::path::Path; use std::path::Path;
use std::process::{Child, Command, Stdio}; use std::process::{Child, Command, Stdio};
use uucore::error::USimpleError; use uucore::error::USimpleError;
@ -134,22 +134,14 @@ pub fn instantiate_current_writer(
.create(true) .create(true)
.truncate(true) .truncate(true)
.open(Path::new(&filename)) .open(Path::new(&filename))
.map_err(|_| { .map_err(|_| Error::other(format!("unable to open '{filename}'; aborting")))?
Error::new(
ErrorKind::Other,
format!("unable to open '{filename}'; aborting"),
)
})?
} else { } else {
// re-open file that we previously created to append to it // re-open file that we previously created to append to it
std::fs::OpenOptions::new() std::fs::OpenOptions::new()
.append(true) .append(true)
.open(Path::new(&filename)) .open(Path::new(&filename))
.map_err(|_| { .map_err(|_| {
Error::new( Error::other(format!("unable to re-open '{filename}'; aborting"))
ErrorKind::Other,
format!("unable to re-open '{filename}'; aborting"),
)
})? })?
}; };
Ok(BufWriter::new(Box::new(file) as Box<dyn Write>)) Ok(BufWriter::new(Box::new(file) as Box<dyn Write>))

View file

@ -3,7 +3,7 @@
// For the full copyright and license information, please view the LICENSE // For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code. // file that was distributed with this source code.
use std::io::Write; use std::io::Write;
use std::io::{BufWriter, Error, ErrorKind, Result}; use std::io::{BufWriter, Error, Result};
use std::path::Path; use std::path::Path;
use uucore::fs; use uucore::fs;
@ -23,23 +23,13 @@ pub fn instantiate_current_writer(
.create(true) .create(true)
.truncate(true) .truncate(true)
.open(Path::new(&filename)) .open(Path::new(&filename))
.map_err(|_| { .map_err(|_| Error::other(format!("unable to open '{filename}'; aborting")))?
Error::new(
ErrorKind::Other,
format!("unable to open '{filename}'; aborting"),
)
})?
} else { } else {
// re-open file that we previously created to append to it // re-open file that we previously created to append to it
std::fs::OpenOptions::new() std::fs::OpenOptions::new()
.append(true) .append(true)
.open(Path::new(&filename)) .open(Path::new(&filename))
.map_err(|_| { .map_err(|_| Error::other(format!("unable to re-open '{filename}'; aborting")))?
Error::new(
ErrorKind::Other,
format!("unable to re-open '{filename}'; aborting"),
)
})?
}; };
Ok(BufWriter::new(Box::new(file) as Box<dyn Write>)) Ok(BufWriter::new(Box::new(file) as Box<dyn Write>))
} }

View file

@ -535,10 +535,9 @@ impl Settings {
is_new: bool, is_new: bool,
) -> io::Result<BufWriter<Box<dyn Write>>> { ) -> io::Result<BufWriter<Box<dyn Write>>> {
if platform::paths_refer_to_same_file(&self.input, filename) { if platform::paths_refer_to_same_file(&self.input, filename) {
return Err(io::Error::new( return Err(io::Error::other(format!(
ErrorKind::Other, "'{filename}' would overwrite input; aborting"
format!("'{filename}' would overwrite input; aborting"), )));
));
} }
platform::instantiate_current_writer(self.filter.as_deref(), filename, is_new) platform::instantiate_current_writer(self.filter.as_deref(), filename, is_new)
@ -638,10 +637,9 @@ where
} else if input == "-" { } else if input == "-" {
// STDIN stream that did not fit all content into a buffer // STDIN stream that did not fit all content into a buffer
// Most likely continuous/infinite input stream // Most likely continuous/infinite input stream
return Err(io::Error::new( return Err(io::Error::other(format!(
ErrorKind::Other, "{input}: cannot determine input size"
format!("{input}: cannot determine input size"), )));
));
} else { } else {
// Could be that file size is larger than set read limit // Could be that file size is larger than set read limit
// Get the file size from filesystem metadata // Get the file size from filesystem metadata
@ -664,10 +662,9 @@ where
// Give up and return an error // Give up and return an error
// TODO It might be possible to do more here // TODO It might be possible to do more here
// to address all possible file types and edge cases // to address all possible file types and edge cases
return Err(io::Error::new( return Err(io::Error::other(format!(
ErrorKind::Other, "{input}: cannot determine file size"
format!("{input}: cannot determine file size"), )));
));
} }
} }
} }
@ -750,9 +747,10 @@ impl Write for ByteChunkWriter<'_> {
self.num_bytes_remaining_in_current_chunk = self.chunk_size; self.num_bytes_remaining_in_current_chunk = self.chunk_size;
// Allocate the new file, since at this point we know there are bytes to be written to it. // Allocate the new file, since at this point we know there are bytes to be written to it.
let filename = self.filename_iterator.next().ok_or_else(|| { let filename = self
io::Error::new(ErrorKind::Other, "output file suffixes exhausted") .filename_iterator
})?; .next()
.ok_or_else(|| io::Error::other("output file suffixes exhausted"))?;
if self.settings.verbose { if self.settings.verbose {
println!("creating file {}", filename.quote()); println!("creating file {}", filename.quote());
} }
@ -871,9 +869,10 @@ impl Write for LineChunkWriter<'_> {
// corresponding writer. // corresponding writer.
if self.num_lines_remaining_in_current_chunk == 0 { if self.num_lines_remaining_in_current_chunk == 0 {
self.num_chunks_written += 1; self.num_chunks_written += 1;
let filename = self.filename_iterator.next().ok_or_else(|| { let filename = self
io::Error::new(ErrorKind::Other, "output file suffixes exhausted") .filename_iterator
})?; .next()
.ok_or_else(|| io::Error::other("output file suffixes exhausted"))?;
if self.settings.verbose { if self.settings.verbose {
println!("creating file {}", filename.quote()); println!("creating file {}", filename.quote());
} }
@ -948,7 +947,7 @@ impl ManageOutFiles for OutFiles {
// This object is responsible for creating the filename for each chunk // This object is responsible for creating the filename for each chunk
let mut filename_iterator: FilenameIterator<'_> = let mut filename_iterator: FilenameIterator<'_> =
FilenameIterator::new(&settings.prefix, &settings.suffix) FilenameIterator::new(&settings.prefix, &settings.suffix)
.map_err(|e| io::Error::new(ErrorKind::Other, format!("{e}")))?; .map_err(|e| io::Error::other(format!("{e}")))?;
let mut out_files: Self = Self::new(); let mut out_files: Self = Self::new();
for _ in 0..num_files { for _ in 0..num_files {
let filename = filename_iterator let filename = filename_iterator

View file

@ -477,7 +477,7 @@ fn touch_file(
false false
}; };
if is_directory { if is_directory {
let custom_err = Error::new(ErrorKind::Other, "No such file or directory"); let custom_err = Error::other("No such file or directory");
return Err( return Err(
custom_err.map_err_context(|| format!("cannot touch {}", filename.quote())) custom_err.map_err_context(|| format!("cannot touch {}", filename.quote()))
); );

View file

@ -794,8 +794,7 @@ fn files0_iter<'a>(
// ...Windows does not, we must go through Strings. // ...Windows does not, we must go through Strings.
#[cfg(not(unix))] #[cfg(not(unix))]
{ {
let s = String::from_utf8(p) let s = String::from_utf8(p).map_err(io::Error::other)?;
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
Ok(Input::Path(PathBuf::from(s).into())) Ok(Input::Path(PathBuf::from(s).into()))
} }
} }

View file

@ -780,19 +780,18 @@ fn get_input_file(filename: &OsStr) -> UResult<Box<dyn Read>> {
match File::open(filename) { match File::open(filename) {
Ok(f) => { Ok(f) => {
if f.metadata()?.is_dir() { if f.metadata()?.is_dir() {
Err(io::Error::new( Err(
io::ErrorKind::Other, io::Error::other(format!("{}: Is a directory", filename.to_string_lossy()))
format!("{}: Is a directory", filename.to_string_lossy()), .into(),
) )
.into())
} else { } else {
Ok(Box::new(f)) Ok(Box::new(f))
} }
} }
Err(_) => Err(io::Error::new( Err(_) => Err(io::Error::other(format!(
io::ErrorKind::Other, "{}: No such file or directory",
format!("{}: No such file or directory", filename.to_string_lossy()), filename.to_string_lossy()
) ))
.into()), .into()),
} }
} }

View file

@ -2286,10 +2286,10 @@ impl UChild {
if start.elapsed() < timeout { if start.elapsed() < timeout {
self.delay(10); self.delay(10);
} else { } else {
return Err(io::Error::new( return Err(io::Error::other(format!(
io::ErrorKind::Other, "kill: Timeout of '{}s' reached",
format!("kill: Timeout of '{}s' reached", timeout.as_secs_f64()), timeout.as_secs_f64()
)); )));
} }
hint::spin_loop(); hint::spin_loop();
} }
@ -2354,10 +2354,10 @@ impl UChild {
if start.elapsed() < timeout { if start.elapsed() < timeout {
self.delay(10); self.delay(10);
} else { } else {
return Err(io::Error::new( return Err(io::Error::other(format!(
io::ErrorKind::Other, "kill: Timeout of '{}s' reached",
format!("kill: Timeout of '{}s' reached", timeout.as_secs_f64()), timeout.as_secs_f64()
)); )));
} }
hint::spin_loop(); hint::spin_loop();
} }
@ -2446,10 +2446,10 @@ impl UChild {
handle.join().unwrap().unwrap(); handle.join().unwrap().unwrap();
result result
} }
Err(RecvTimeoutError::Timeout) => Err(io::Error::new( Err(RecvTimeoutError::Timeout) => Err(io::Error::other(format!(
io::ErrorKind::Other, "wait: Timeout of '{}s' reached",
format!("wait: Timeout of '{}s' reached", timeout.as_secs_f64()), timeout.as_secs_f64()
)), ))),
Err(RecvTimeoutError::Disconnected) => { Err(RecvTimeoutError::Disconnected) => {
handle.join().expect("Panic caused disconnect").unwrap(); handle.join().expect("Panic caused disconnect").unwrap();
panic!("Error receiving from waiting thread because of unexpected disconnect"); panic!("Error receiving from waiting thread because of unexpected disconnect");
@ -2691,10 +2691,9 @@ impl UChild {
.name("pipe_in".to_string()) .name("pipe_in".to_string())
.spawn( .spawn(
move || match writer.write_all(&content).and_then(|()| writer.flush()) { move || match writer.write_all(&content).and_then(|()| writer.flush()) {
Err(error) if !ignore_stdin_write_error => Err(io::Error::new( Err(error) if !ignore_stdin_write_error => Err(io::Error::other(format!(
io::ErrorKind::Other, "failed to write to stdin of child: {error}"
format!("failed to write to stdin of child: {error}"), ))),
)),
Ok(()) | Err(_) => Ok(()), Ok(()) | Err(_) => Ok(()),
}, },
) )
@ -2736,10 +2735,9 @@ impl UChild {
let mut writer = self.access_stdin_as_writer(); let mut writer = self.access_stdin_as_writer();
match writer.write_all(&data.into()).and_then(|()| writer.flush()) { match writer.write_all(&data.into()).and_then(|()| writer.flush()) {
Err(error) if !ignore_stdin_write_error => Err(io::Error::new( Err(error) if !ignore_stdin_write_error => Err(io::Error::other(format!(
io::ErrorKind::Other, "failed to write to stdin of child: {error}"
format!("failed to write to stdin of child: {error}"), ))),
)),
Ok(()) | Err(_) => Ok(()), Ok(()) | Err(_) => Ok(()),
} }
} }