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

Merge pull request #7744 from BenWiederhake/dev-clippy-0-1-87-nightly

Apply suggestions from clippy 0.1.87+nightly
This commit is contained in:
Sylvestre Ledru 2025-04-13 12:11:50 +02:00 committed by GitHub
commit 291473e3a4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
15 changed files with 83 additions and 119 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

@ -82,7 +82,7 @@ fn get_local_to_root_parent(
/// Given an iterator, return all its items except the last. /// Given an iterator, return all its items except the last.
fn skip_last<T>(mut iter: impl Iterator<Item = T>) -> impl Iterator<Item = T> { fn skip_last<T>(mut iter: impl Iterator<Item = T>) -> impl Iterator<Item = T> {
let last = iter.next(); let last = iter.next();
iter.scan(last, |state, item| std::mem::replace(state, Some(item))) iter.scan(last, |state, item| state.replace(item))
} }
/// Paths that are invariant throughout the traversal when copying a directory. /// Paths that are invariant throughout the traversal when copying a directory.

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

@ -168,21 +168,17 @@ fn execute(
} }
fn bytes_from_os_string(input: &OsStr) -> Option<&[u8]> { fn bytes_from_os_string(input: &OsStr) -> Option<&[u8]> {
let option = { #[cfg(target_family = "unix")]
#[cfg(target_family = "unix")] {
{ use std::os::unix::ffi::OsStrExt;
use std::os::unix::ffi::OsStrExt;
Some(input.as_bytes()) Some(input.as_bytes())
} }
#[cfg(not(target_family = "unix"))] #[cfg(not(target_family = "unix"))]
{ {
// TODO // TODO
// Verify that this works correctly on these platforms // Verify that this works correctly on these platforms
input.to_str().map(|st| st.as_bytes()) input.to_str().map(|st| st.as_bytes())
} }
};
option
} }

View file

@ -283,8 +283,7 @@ impl<'a> NativeStr<'a> {
match &self.native { match &self.native {
Cow::Borrowed(b) => { Cow::Borrowed(b) => {
let slice = f_borrow(b); let slice = f_borrow(b);
let os_str = slice.map(|x| from_native_int_representation(Cow::Borrowed(x))); slice.map(|x| from_native_int_representation(Cow::Borrowed(x)))
os_str
} }
Cow::Owned(o) => { Cow::Owned(o) => {
let slice = f_owned(o); let slice = f_owned(o);

View file

@ -164,9 +164,7 @@ fn break_knuth_plass<'a, T: Clone + Iterator<Item = &'a WordInfo<'a>>>(
// We find identical breakpoints here by comparing addresses of the references. // We find identical breakpoints here by comparing addresses of the references.
// This is OK because the backing vector is not mutating once we are linebreaking. // This is OK because the backing vector is not mutating once we are linebreaking.
let winfo_ptr = winfo as *const _; if std::ptr::eq(winfo, next_break) {
let next_break_ptr = next_break as *const _;
if winfo_ptr == next_break_ptr {
// OK, we found the matching word // OK, we found the matching word
if break_before { if break_before {
write_newline(args.indent_str, args.ostream)?; write_newline(args.indent_str, args.ostream)?;

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

@ -55,7 +55,7 @@ fn tabstops_parse(s: &str) -> Result<Vec<usize>, ParseError> {
} }
} }
if nums.iter().any(|&n| n == 0) { if nums.contains(&0) {
return Err(ParseError::TabSizeCannotBeZero); return Err(ParseError::TabSizeCannotBeZero);
} }

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(()),
} }
} }