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

Fix some clippy warnings

This commit is contained in:
Sylvestre Ledru 2023-08-21 08:11:38 +02:00
parent 682f488720
commit 7c9f4ba92a
23 changed files with 50 additions and 55 deletions

View file

@ -192,7 +192,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
NumberingMode::None NumberingMode::None
}; };
let show_nonprint = vec![ let show_nonprint = [
options::SHOW_ALL.to_owned(), options::SHOW_ALL.to_owned(),
options::SHOW_NONPRINTING_ENDS.to_owned(), options::SHOW_NONPRINTING_ENDS.to_owned(),
options::SHOW_NONPRINTING_TABS.to_owned(), options::SHOW_NONPRINTING_TABS.to_owned(),
@ -201,7 +201,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
.iter() .iter()
.any(|v| matches.get_flag(v)); .any(|v| matches.get_flag(v));
let show_ends = vec![ let show_ends = [
options::SHOW_ENDS.to_owned(), options::SHOW_ENDS.to_owned(),
options::SHOW_ALL.to_owned(), options::SHOW_ALL.to_owned(),
options::SHOW_NONPRINTING_ENDS.to_owned(), options::SHOW_NONPRINTING_ENDS.to_owned(),
@ -209,7 +209,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
.iter() .iter()
.any(|v| matches.get_flag(v)); .any(|v| matches.get_flag(v));
let show_tabs = vec![ let show_tabs = [
options::SHOW_ALL.to_owned(), options::SHOW_ALL.to_owned(),
options::SHOW_TABS.to_owned(), options::SHOW_TABS.to_owned(),
options::SHOW_NONPRINTING_TABS.to_owned(), options::SHOW_NONPRINTING_TABS.to_owned(),

View file

@ -438,25 +438,25 @@ mod tests {
fn test_extract_negative_modes() { fn test_extract_negative_modes() {
// "chmod -w -r file" becomes "chmod -w,-r file". clap does not accept "-w,-r" as MODE. // "chmod -w -r file" becomes "chmod -w,-r file". clap does not accept "-w,-r" as MODE.
// Therefore, "w" is added as pseudo mode to pass clap. // Therefore, "w" is added as pseudo mode to pass clap.
let (c, a) = extract_negative_modes(vec!["-w", "-r", "file"].iter().map(OsString::from)); let (c, a) = extract_negative_modes(["-w", "-r", "file"].iter().map(OsString::from));
assert_eq!(c, Some("-w,-r".to_string())); assert_eq!(c, Some("-w,-r".to_string()));
assert_eq!(a, vec!["w", "file"]); assert_eq!(a, ["w", "file"]);
// "chmod -w file -r" becomes "chmod -w,-r file". clap does not accept "-w,-r" as MODE. // "chmod -w file -r" becomes "chmod -w,-r file". clap does not accept "-w,-r" as MODE.
// Therefore, "w" is added as pseudo mode to pass clap. // Therefore, "w" is added as pseudo mode to pass clap.
let (c, a) = extract_negative_modes(vec!["-w", "file", "-r"].iter().map(OsString::from)); let (c, a) = extract_negative_modes(["-w", "file", "-r"].iter().map(OsString::from));
assert_eq!(c, Some("-w,-r".to_string())); assert_eq!(c, Some("-w,-r".to_string()));
assert_eq!(a, vec!["w", "file"]); assert_eq!(a, ["w", "file"]);
// "chmod -w -- -r file" becomes "chmod -w -r file", where "-r" is interpreted as file. // "chmod -w -- -r file" becomes "chmod -w -r file", where "-r" is interpreted as file.
// Again, "w" is needed as pseudo mode. // Again, "w" is needed as pseudo mode.
let (c, a) = extract_negative_modes(vec!["-w", "--", "-r", "f"].iter().map(OsString::from)); let (c, a) = extract_negative_modes(["-w", "--", "-r", "f"].iter().map(OsString::from));
assert_eq!(c, Some("-w".to_string())); assert_eq!(c, Some("-w".to_string()));
assert_eq!(a, vec!["w", "--", "-r", "f"]); assert_eq!(a, ["w", "--", "-r", "f"]);
// "chmod -- -r file" becomes "chmod -r file". // "chmod -- -r file" becomes "chmod -r file".
let (c, a) = extract_negative_modes(vec!["--", "-r", "file"].iter().map(OsString::from)); let (c, a) = extract_negative_modes(["--", "-r", "file"].iter().map(OsString::from));
assert_eq!(c, None); assert_eq!(c, None);
assert_eq!(a, vec!["--", "-r", "file"]); assert_eq!(a, ["--", "-r", "file"]);
} }
} }

View file

@ -168,9 +168,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
println!("{s}"); println!("{s}");
Ok(()) Ok(())
} }
Err(s) => { Err(s) => Err(USimpleError::new(1, s)),
return Err(USimpleError::new(1, s));
}
} }
} }

View file

@ -550,7 +550,7 @@ fn auditid() {
println!("asid={}", auditinfo.ai_asid); println!("asid={}", auditinfo.ai_asid);
} }
fn id_print(state: &mut State, groups: &[u32]) { fn id_print(state: &State, groups: &[u32]) {
let uid = state.ids.as_ref().unwrap().uid; let uid = state.ids.as_ref().unwrap().uid;
let gid = state.ids.as_ref().unwrap().gid; let gid = state.ids.as_ref().unwrap().gid;
let euid = state.ids.as_ref().unwrap().euid; let euid = state.ids.as_ref().unwrap().euid;

View file

@ -619,7 +619,7 @@ fn copy_files_into_dir(files: &[PathBuf], target_dir: &Path, b: &Behavior) -> UR
if !target_dir.is_dir() { if !target_dir.is_dir() {
return Err(InstallError::TargetDirIsntDir(target_dir.to_path_buf()).into()); return Err(InstallError::TargetDirIsntDir(target_dir.to_path_buf()).into());
} }
for sourcepath in files.iter() { for sourcepath in files {
if let Err(err) = sourcepath if let Err(err) = sourcepath
.metadata() .metadata()
.map_err_context(|| format!("cannot stat {}", sourcepath.quote())) .map_err_context(|| format!("cannot stat {}", sourcepath.quote()))

View file

@ -101,12 +101,10 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
matches.get_one::<u64>("major"), matches.get_one::<u64>("major"),
matches.get_one::<u64>("minor"), matches.get_one::<u64>("minor"),
) { ) {
(_, None) | (None, _) => { (_, None) | (None, _) => Err(UUsageError::new(
return Err(UUsageError::new( 1,
1, "Special files require major and minor device numbers.",
"Special files require major and minor device numbers.", )),
));
}
(Some(&major), Some(&minor)) => { (Some(&major), Some(&minor)) => {
let dev = makedev(major, minor); let dev = makedev(major, minor);
let exit_code = match file_type { let exit_code = match file_type {

View file

@ -364,7 +364,7 @@ fn move_files_into_dir(files: &[PathBuf], target_dir: &Path, b: &Behavior) -> UR
None None
}; };
for sourcepath in files.iter() { for sourcepath in files {
if let Some(ref pb) = count_progress { if let Some(ref pb) = count_progress {
pb.set_message(sourcepath.to_string_lossy().to_string()); pb.set_message(sourcepath.to_string_lossy().to_string());
} }

View file

@ -82,7 +82,7 @@ pub fn format_ascii_dump(bytes: &[u8]) -> String {
let mut result = String::new(); let mut result = String::new();
result.push('>'); result.push('>');
for c in bytes.iter() { for c in bytes {
if *c >= 0x20 && *c <= 0x7e { if *c >= 0x20 && *c <= 0x7e {
result.push_str(C_CHARS[*c as usize]); result.push_str(C_CHARS[*c as usize]);
} else { } else {

View file

@ -54,7 +54,7 @@ pub fn check(path: &OsStr, settings: &GlobalSettings) -> UResult<()> {
let mut prev_chunk: Option<Chunk> = None; let mut prev_chunk: Option<Chunk> = None;
let mut line_idx = 0; let mut line_idx = 0;
for chunk in loaded_receiver.iter() { for chunk in loaded_receiver {
line_idx += 1; line_idx += 1;
if let Some(prev_chunk) = prev_chunk.take() { if let Some(prev_chunk) = prev_chunk.take() {
// Check if the first element of the new chunk is greater than the last // Check if the first element of the new chunk is greater than the last
@ -107,7 +107,7 @@ fn reader(
settings: &GlobalSettings, settings: &GlobalSettings,
) -> UResult<()> { ) -> UResult<()> {
let mut carry_over = vec![]; let mut carry_over = vec![];
for recycled_chunk in receiver.iter() { for recycled_chunk in receiver {
let should_continue = chunks::read( let should_continue = chunks::read(
sender, sender,
recycled_chunk, recycled_chunk,

View file

@ -211,7 +211,7 @@ fn reader(
settings: &GlobalSettings, settings: &GlobalSettings,
separator: u8, separator: u8,
) -> UResult<()> { ) -> UResult<()> {
for (file_idx, recycled_chunk) in recycled_receiver.iter() { for (file_idx, recycled_chunk) in recycled_receiver {
if let Some(ReaderFile { if let Some(ReaderFile {
file, file,
sender, sender,

View file

@ -130,7 +130,7 @@ fn set_command_env(command: &mut process::Command, buffer_name: &str, buffer_typ
} }
} }
fn get_preload_env(tmp_dir: &mut TempDir) -> io::Result<(String, PathBuf)> { fn get_preload_env(tmp_dir: &TempDir) -> io::Result<(String, PathBuf)> {
let (preload, extension) = preload_strings(); let (preload, extension) = preload_strings();
let inject_path = tmp_dir.path().join("libstdbuf").with_extension(extension); let inject_path = tmp_dir.path().join("libstdbuf").with_extension(extension);

View file

@ -33,7 +33,7 @@ fn bsd_sum(mut reader: Box<dyn Read>) -> (usize, u16) {
match reader.read(&mut buf) { match reader.read(&mut buf) {
Ok(n) if n != 0 => { Ok(n) if n != 0 => {
bytes_read += n; bytes_read += n;
for &byte in buf[..n].iter() { for &byte in &buf[..n] {
checksum = checksum.rotate_right(1); checksum = checksum.rotate_right(1);
checksum = checksum.wrapping_add(u16::from(byte)); checksum = checksum.wrapping_add(u16::from(byte));
} }
@ -56,7 +56,7 @@ fn sysv_sum(mut reader: Box<dyn Read>) -> (usize, u16) {
match reader.read(&mut buf) { match reader.read(&mut buf) {
Ok(n) if n != 0 => { Ok(n) if n != 0 => {
bytes_read += n; bytes_read += n;
for &byte in buf[..n].iter() { for &byte in &buf[..n] {
ret = ret.wrapping_add(u32::from(byte)); ret = ret.wrapping_add(u32::from(byte));
} }
} }

View file

@ -173,7 +173,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let path = Path::new(&f); let path = Path::new(&f);
if let Err(e) = open(path, OFlag::O_NONBLOCK, Mode::empty()) { if let Err(e) = open(path, OFlag::O_NONBLOCK, Mode::empty()) {
if e != Errno::EACCES || (e == Errno::EACCES && path.is_dir()) { if e != Errno::EACCES || (e == Errno::EACCES && path.is_dir()) {
return e.map_err_context(|| format!("error opening {}", f.quote()))?; e.map_err_context(|| format!("error opening {}", f.quote()))?;
} }
} }
} }

View file

@ -495,7 +495,7 @@ impl LinesChunk {
fn calculate_bytes_offset_from(&self, offset: usize) -> usize { fn calculate_bytes_offset_from(&self, offset: usize) -> usize {
let mut lines_offset = offset; let mut lines_offset = offset;
let mut bytes_offset = 0; let mut bytes_offset = 0;
for byte in self.get_buffer().iter() { for byte in self.get_buffer() {
if lines_offset == 0 { if lines_offset == 0 {
break; break;
} }

View file

@ -686,7 +686,7 @@ fn compute_number_width(inputs: &Inputs, settings: &Settings) -> usize {
let mut minimum_width = 1; let mut minimum_width = 1;
let mut total: u64 = 0; let mut total: u64 = 0;
for input in inputs.iter() { for input in inputs {
match input { match input {
Input::Stdin(_) => minimum_width = MINIMUM_WIDTH, Input::Stdin(_) => minimum_width = MINIMUM_WIDTH,
Input::Path(path) => { Input::Path(path) => {

View file

@ -845,7 +845,7 @@ mod tests {
let path1 = temp_file.path(); let path1 = temp_file.path();
let path2 = temp_file.path(); let path2 = temp_file.path();
assert_eq!(are_hardlinks_to_same_file(&path1, &path2), true); assert!(are_hardlinks_to_same_file(&path1, &path2));
} }
#[cfg(unix)] #[cfg(unix)]
@ -860,7 +860,7 @@ mod tests {
let path1 = temp_file1.path(); let path1 = temp_file1.path();
let path2 = temp_file2.path(); let path2 = temp_file2.path();
assert_eq!(are_hardlinks_to_same_file(&path1, &path2), false); assert!(are_hardlinks_to_same_file(&path1, &path2));
} }
#[cfg(unix)] #[cfg(unix)]
@ -873,6 +873,6 @@ mod tests {
let path2 = temp_file.path().with_extension("hardlink"); let path2 = temp_file.path().with_extension("hardlink");
fs::hard_link(&path1, &path2).unwrap(); fs::hard_link(&path1, &path2).unwrap();
assert_eq!(are_hardlinks_to_same_file(&path1, &path2), true); assert!(are_hardlinks_to_same_file(&path1, &path2));
} }
} }

View file

@ -2022,12 +2022,12 @@ fn test_cp_reflink_always_override() {
const USERDIR: &str = "dir/"; const USERDIR: &str = "dir/";
const MOUNTPOINT: &str = "mountpoint/"; const MOUNTPOINT: &str = "mountpoint/";
let src1_path: &str = &vec![MOUNTPOINT, USERDIR, "src1"].concat(); let src1_path: &str = &[MOUNTPOINT, USERDIR, "src1"].concat();
let src2_path: &str = &vec![MOUNTPOINT, USERDIR, "src2"].concat(); let src2_path: &str = &[MOUNTPOINT, USERDIR, "src2"].concat();
let dst_path: &str = &vec![MOUNTPOINT, USERDIR, "dst"].concat(); let dst_path: &str = &[MOUNTPOINT, USERDIR, "dst"].concat();
scene.fixtures.mkdir(ROOTDIR); scene.fixtures.mkdir(ROOTDIR);
scene.fixtures.mkdir(vec![ROOTDIR, USERDIR].concat()); scene.fixtures.mkdir([ROOTDIR, USERDIR].concat());
// Setup: // Setup:
// Because neither `mkfs.btrfs` not btrfs `mount` options allow us to have a mountpoint owned // Because neither `mkfs.btrfs` not btrfs `mount` options allow us to have a mountpoint owned

View file

@ -173,7 +173,6 @@ fn test_random() {
break; break;
} }
} }
let factor = factor;
match product.checked_mul(factor) { match product.checked_mul(factor) {
Some(p) => { Some(p) => {
@ -317,7 +316,7 @@ fn run(input_string: &[u8], output_string: &[u8]) {
fn test_primes_with_exponents() { fn test_primes_with_exponents() {
let mut input_string = String::new(); let mut input_string = String::new();
let mut output_string = String::new(); let mut output_string = String::new();
for primes in PRIMES_BY_BITS.iter() { for primes in PRIMES_BY_BITS {
for &prime in *primes { for &prime in *primes {
input_string.push_str(&(format!("{prime} "))[..]); input_string.push_str(&(format!("{prime} "))[..]);
output_string.push_str(&(format!("{prime}: {prime}\n"))[..]); output_string.push_str(&(format!("{prime}: {prime}\n"))[..]);

View file

@ -58,7 +58,7 @@ fn test_link_one_argument() {
#[test] #[test]
fn test_link_three_arguments() { fn test_link_three_arguments() {
let (_, mut ucmd) = at_and_ucmd!(); let (_, mut ucmd) = at_and_ucmd!();
let arguments = vec![ let arguments = [
"test_link_argument1", "test_link_argument1",
"test_link_argument2", "test_link_argument2",
"test_link_argument3", "test_link_argument3",

View file

@ -1278,7 +1278,7 @@ fn test_mv_verbose() {
#[test] #[test]
#[cfg(any(target_os = "linux", target_os = "android"))] // mkdir does not support -m on windows. Freebsd doesn't return a permission error either. #[cfg(any(target_os = "linux", target_os = "android"))] // mkdir does not support -m on windows. Freebsd doesn't return a permission error either.
#[cfg(features = "mkdir")] #[cfg(feature = "mkdir")]
fn test_mv_permission_error() { fn test_mv_permission_error() {
let scene = TestScenario::new("mkdir"); let scene = TestScenario::new("mkdir");
let folder1 = "bar"; let folder1 = "bar";

View file

@ -478,7 +478,7 @@ fn test_rm_prompts() {
// Needed for talking with stdin on platforms where CRLF or LF matters // Needed for talking with stdin on platforms where CRLF or LF matters
const END_OF_LINE: &str = if cfg!(windows) { "\r\n" } else { "\n" }; const END_OF_LINE: &str = if cfg!(windows) { "\r\n" } else { "\n" };
let mut answers = vec![ let mut answers = [
"rm: descend into directory 'a'?", "rm: descend into directory 'a'?",
"rm: remove write-protected regular empty file 'a/empty-no-write'?", "rm: remove write-protected regular empty file 'a/empty-no-write'?",
"rm: remove symbolic link 'a/slink'?", "rm: remove symbolic link 'a/slink'?",

View file

@ -71,7 +71,7 @@ fn test_echo() {
#[test] #[test]
fn test_head_count() { fn test_head_count() {
let repeat_limit = 5; let repeat_limit = 5;
let input_seq = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let input_seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let input = input_seq let input = input_seq
.iter() .iter()
.map(ToString::to_string) .map(ToString::to_string)
@ -102,7 +102,7 @@ fn test_head_count() {
#[test] #[test]
fn test_repeat() { fn test_repeat() {
let repeat_limit = 15000; let repeat_limit = 15000;
let input_seq = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let input_seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let input = input_seq let input = input_seq
.iter() .iter()
.map(ToString::to_string) .map(ToString::to_string)

View file

@ -541,7 +541,7 @@ impl CmdResult {
let contents = String::from_utf8(read_scenario_fixture(&self.tmpd, file_rel_path)).unwrap(); let contents = String::from_utf8(read_scenario_fixture(&self.tmpd, file_rel_path)).unwrap();
let possible_values = template_vars.iter().map(|vars| { let possible_values = template_vars.iter().map(|vars| {
let mut contents = contents.clone(); let mut contents = contents.clone();
for kv in vars.iter() { for kv in vars {
contents = contents.replace(&kv.0, &kv.1); contents = contents.replace(&kv.0, &kv.1);
} }
contents contents
@ -2211,12 +2211,12 @@ impl UChild {
let join_handle = thread::spawn(move || { let join_handle = thread::spawn(move || {
let mut writer = BufWriter::new(stdin); let mut writer = BufWriter::new(stdin);
match writer.write_all(&content).and_then(|_| writer.flush()) { 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::new(
io::ErrorKind::Other, io::ErrorKind::Other,
format!("failed to write to stdin of child: {error}"), format!("failed to write to stdin of child: {error}"),
)), )),
Ok(_) | Err(_) => Ok(()), Ok(()) | Err(_) => Ok(()),
} }
}); });
@ -2263,12 +2263,12 @@ impl UChild {
pub fn try_write_in<T: Into<Vec<u8>>>(&mut self, data: T) -> io::Result<()> { pub fn try_write_in<T: Into<Vec<u8>>>(&mut self, data: T) -> io::Result<()> {
let stdin = self.raw.stdin.as_mut().unwrap(); let stdin = self.raw.stdin.as_mut().unwrap();
match stdin.write_all(&data.into()).and_then(|_| stdin.flush()) { match stdin.write_all(&data.into()).and_then(|()| stdin.flush()) {
Err(error) if !self.ignore_stdin_write_error => Err(io::Error::new( Err(error) if !self.ignore_stdin_write_error => Err(io::Error::new(
io::ErrorKind::Other, io::ErrorKind::Other,
format!("failed to write to stdin of child: {error}"), format!("failed to write to stdin of child: {error}"),
)), )),
Ok(_) | Err(_) => Ok(()), Ok(()) | Err(_) => Ok(()),
} }
} }
@ -2505,11 +2505,11 @@ pub fn expected_result(ts: &TestScenario, args: &[&str]) -> std::result::Result<
/// This is a convenience wrapper to run a ucmd with root permissions. /// This is a convenience wrapper to run a ucmd with root permissions.
/// It can be used to test programs when being root is needed /// It can be used to test programs when being root is needed
/// This runs 'sudo -E --non-interactive target/debug/coreutils util_name args` /// This runs `sudo -E --non-interactive target/debug/coreutils util_name args`
/// This is primarily designed to run in an environment where whoami is in $path /// This is primarily designed to run in an environment where whoami is in $path
/// and where non-interactive sudo is possible. /// and where non-interactive sudo is possible.
/// To check if i) non-interactive sudo is possible and ii) if sudo works, this runs: /// To check if i) non-interactive sudo is possible and ii) if sudo works, this runs:
/// 'sudo -E --non-interactive whoami' first. /// `sudo -E --non-interactive whoami` first.
/// ///
/// This return an `Err()` if run inside CICD because there's no 'sudo'. /// This return an `Err()` if run inside CICD because there's no 'sudo'.
/// ///
@ -3279,7 +3279,7 @@ mod tests {
std::assert_eq!(error.to_string(), "kill: Timeout of '0s' reached"); std::assert_eq!(error.to_string(), "kill: Timeout of '0s' reached");
} }
Err(error) => panic!("Assertion failed: Expected error with timeout but was: {error}"), Err(error) => panic!("Assertion failed: Expected error with timeout but was: {error}"),
Ok(_) => panic!("Assertion failed: Expected timeout of `try_kill`."), Ok(()) => panic!("Assertion failed: Expected timeout of `try_kill`."),
} }
} }