Run clippy pedantic fixes

Done with:
$ cargo +nightly clippy --tests --fix --allow-dirty -- -W clippy::pedantic
This commit is contained in:
Sylvestre Ledru
2024-04-03 17:50:13 +02:00
parent 05d82cee36
commit b4fbbe50c2
18 changed files with 70 additions and 81 deletions
+1 -1
View File
@@ -44,7 +44,7 @@ impl Matcher for DeleteMatcher {
}
match self.delete(path, file_info.file_type()) {
Ok(_) => true,
Ok(()) => true,
Err(e) => {
writeln!(&mut stderr(), "Failed to delete {path_str}: {e}").unwrap();
false
+1 -1
View File
@@ -100,5 +100,5 @@ impl Matcher for SingleExecMatcher {
#[cfg(test)]
/// No tests here, because we need to call out to an external executable. See
/// tests/exec_unit_tests.rs instead.
/// `tests/exec_unit_tests.rs` instead.
mod tests {}
+1 -1
View File
@@ -201,7 +201,7 @@ mod tests {
#[test]
fn incomplete_escape() {
assert_eq!(glob_to_regex(r"foo\"), r"$.")
assert_eq!(glob_to_regex(r"foo\"), r"$.");
}
#[test]
+1 -2
View File
@@ -74,8 +74,7 @@ mod tests {
if let Err(e) = symlink("abbbc", "test_data/links/link-f") {
assert!(
e.kind() == ErrorKind::AlreadyExists,
"Failed to create sym link: {:?}",
e
"Failed to create sym link: {e:?}"
);
}
#[cfg(windows)]
+9 -3
View File
@@ -47,7 +47,9 @@ impl Matcher for AndMatcher {
}
fn has_side_effects(&self) -> bool {
self.submatchers.iter().any(|x| x.has_side_effects())
self.submatchers
.iter()
.any(super::Matcher::has_side_effects)
}
fn finished_dir(&self, dir: &Path) {
@@ -121,7 +123,9 @@ impl Matcher for OrMatcher {
}
fn has_side_effects(&self) -> bool {
self.submatchers.iter().any(|x| x.has_side_effects())
self.submatchers
.iter()
.any(super::Matcher::has_side_effects)
}
fn finished_dir(&self, dir: &Path) {
@@ -214,7 +218,9 @@ impl Matcher for ListMatcher {
}
fn has_side_effects(&self) -> bool {
self.submatchers.iter().any(|x| x.has_side_effects())
self.submatchers
.iter()
.any(super::Matcher::has_side_effects)
}
fn finished_dir(&self, dir: &Path) {
+9 -7
View File
@@ -74,6 +74,7 @@ impl<'a> MatcherIO<'a> {
self.should_skip_dir = true;
}
#[must_use]
pub fn should_skip_current_dir(&self) -> bool {
self.should_skip_dir
}
@@ -82,10 +83,12 @@ impl<'a> MatcherIO<'a> {
self.quit = true;
}
#[must_use]
pub fn should_quit(&self) -> bool {
self.quit
}
#[must_use]
pub fn now(&self) -> SystemTime {
self.deps.now()
}
@@ -140,11 +143,11 @@ impl Matcher for Box<dyn Matcher> {
}
fn finished_dir(&self, finished_directory: &Path) {
(**self).finished_dir(finished_directory)
(**self).finished_dir(finished_directory);
}
fn finished(&self) {
(**self).finished()
(**self).finished();
}
}
@@ -546,8 +549,8 @@ mod tests {
use crate::find::tests::FakeDependencies;
use walkdir::WalkDir;
/// Helper function for tests to get a DirEntry object. directory should
/// probably be a string starting with "test_data/" (cargo's tests run with
/// Helper function for tests to get a `DirEntry` object. directory should
/// probably be a string starting with `test_data/` (cargo's tests run with
/// a working directory set to the root findutils folder).
pub fn get_dir_entry_for(directory: &str, filename: &str) -> DirEntry {
for wrapped_dir_entry in WalkDir::new(fix_up_slashes(directory)) {
@@ -562,7 +565,7 @@ mod tests {
return dir_entry;
}
}
panic!("Couldn't find {} in {}", filename, directory);
panic!("Couldn't find {filename} in {directory}");
}
#[test]
@@ -1052,8 +1055,7 @@ mod tests {
if let Err(e) = build_top_level_matcher(&["-ctime", "-123."], &mut config) {
assert!(
e.to_string().contains("Expected a decimal integer"),
"bad description: {}",
e
"bad description: {e}"
);
} else {
panic!("parsing a bad ctime value should fail");
+1 -2
View File
@@ -48,8 +48,7 @@ mod tests {
if let Err(e) = symlink("abbbc", "test_data/links/link-f") {
assert!(
e.kind() == ErrorKind::AlreadyExists,
"Failed to create sym link: {:?}",
e
"Failed to create sym link: {e:?}"
);
}
#[cfg(windows)]
+1 -1
View File
@@ -41,7 +41,7 @@ impl ComparisonType {
#[cfg(unix)]
mod parsing {
use super::*;
use super::{parse_numeric, parse_symbolic, ComparisonType, Error};
pub fn split_comparison_type(pattern: &str) -> (ComparisonType, &str) {
let mut chars = pattern.chars();
+10 -17
View File
@@ -158,10 +158,9 @@ impl FormatStringParser<'_> {
// Try parsing an octal sequence first.
let first = self.front()?;
if first.is_digit(OCTAL_RADIX) {
if let Ok(code) = self
.peek(OCTAL_LEN)
.and_then(|octal| u32::from_str_radix(octal, OCTAL_RADIX).map_err(|e| e.into()))
{
if let Ok(code) = self.peek(OCTAL_LEN).and_then(|octal| {
u32::from_str_radix(octal, OCTAL_RADIX).map_err(std::convert::Into::into)
}) {
// safe to unwrap: .peek() already succeeded above.
let octal = self.advance_by(OCTAL_LEN).unwrap();
return match char::from_u32(code) {
@@ -388,7 +387,7 @@ fn format_directive<'entry>(
// symlink itself instead.
file_info.path().symlink_metadata()
} else {
file_info.metadata().map_err(|e| e.into())
file_info.metadata().map_err(std::convert::Into::into)
}
})
};
@@ -468,8 +467,7 @@ fn format_directive<'entry>(
fs_list
.into_iter()
.find(|fs| fs.dev_id == dev_id)
.map(|fs| fs.fs_type)
.unwrap_or_else(String::new)
.map_or_else(String::new, |fs| fs.fs_type)
.into()
}
@@ -949,36 +947,31 @@ mod tests {
if let Err(e) = symlink("abbbc", "test_data/links/link-f") {
assert!(
e.kind() == ErrorKind::AlreadyExists,
"Failed to create sym link: {:?}",
e
"Failed to create sym link: {e:?}"
);
}
if let Err(e) = symlink("subdir", "test_data/links/link-d") {
assert!(
e.kind() == ErrorKind::AlreadyExists,
"Failed to create sym link: {:?}",
e
"Failed to create sym link: {e:?}"
);
}
if let Err(e) = symlink("missing", "test_data/links/link-missing") {
assert!(
e.kind() == ErrorKind::AlreadyExists,
"Failed to create sym link: {:?}",
e
"Failed to create sym link: {e:?}"
);
}
if let Err(e) = symlink("abbbc/x", "test_data/links/link-notdir") {
assert!(
e.kind() == ErrorKind::AlreadyExists,
"Failed to create sym link: {:?}",
e
"Failed to create sym link: {e:?}"
);
}
if let Err(e) = symlink("link-loop", "test_data/links/link-loop") {
assert!(
e.kind() == ErrorKind::AlreadyExists,
"Failed to create sym link: {:?}",
e
"Failed to create sym link: {e:?}"
);
}
}
+1 -1
View File
@@ -23,7 +23,7 @@ impl fmt::Display for ParseRegexTypeError {
self.0,
RegexType::VALUES
.iter()
.map(|t| format!("'{}'", t))
.map(|t| format!("'{t}'"))
.collect::<Vec<_>>()
.join(", ")
)
+1 -2
View File
@@ -147,8 +147,7 @@ mod tests {
if let Err(e) = SizeMatcher::new(ComparableValue::EqualTo(2), "xyz") {
assert!(
e.to_string().contains("Invalid suffix") && e.to_string().contains("xyz"),
"bad description: {}",
e
"bad description: {e}"
);
} else {
panic!("parsing a unit string should fail");
+3 -5
View File
@@ -337,7 +337,7 @@ mod tests {
}
}
/// helper function for file_time_matcher_modified_created_accessed
/// helper function for `file_time_matcher_modified_created_accessed`
fn test_matcher_for_file_time_type(
file_info: &DirEntry,
file_time: SystemTime,
@@ -350,15 +350,13 @@ mod tests {
deps.set_time(file_time);
assert!(
matcher.matches(file_info, &mut deps.new_matcher_io()),
"{:?} time matcher should match",
file_time_type
"{file_time_type:?} time matcher should match"
);
deps.set_time(file_time - Duration::from_secs(1));
assert!(
!matcher.matches(file_info, &mut deps.new_matcher_io()),
"{:?} time matcher shouldn't match a second before",
file_time_type
"{file_time_type:?} time matcher shouldn't match a second before"
);
}
}
+2 -4
View File
@@ -109,15 +109,13 @@ mod tests {
if let Err(e) = symlink("abbbc", "test_data/links/link-f") {
assert!(
e.kind() == ErrorKind::AlreadyExists,
"Failed to create sym link: {:?}",
e
"Failed to create sym link: {e:?}"
);
}
if let Err(e) = symlink("subdir", "test_data/links/link-d") {
assert!(
e.kind() == ErrorKind::AlreadyExists,
"Failed to create sym link: {:?}",
e
"Failed to create sym link: {e:?}"
);
}
};
+3 -3
View File
@@ -51,6 +51,7 @@ pub struct StandardDependencies {
}
impl StandardDependencies {
#[must_use]
pub fn new() -> Self {
Self {
output: Rc::new(RefCell::new(stdout())),
@@ -338,8 +339,7 @@ mod tests {
if let Err(e) = symlink("abbbc", "test_data/links/link-f") {
assert!(
e.kind() == ErrorKind::AlreadyExists,
"Failed to create sym link: {:?}",
e
"Failed to create sym link: {e:?}"
);
}
#[cfg(windows)]
@@ -692,7 +692,7 @@ mod tests {
}
}
/// Helper function for the find_ctime/find_atime/find_mtime tests.
/// Helper function for the `find_ctime/find_atime/find_mtime` tests.
fn file_time_helper(file_time: SystemTime, arg: &str) {
// check file time matches a file that's old enough
{
+10 -10
View File
@@ -79,7 +79,7 @@ trait CommandSizeLimiter {
}
/// A pointer to the next limiter. A limiter should *always* call the cursor's
/// try_next *before* updating its own state, to ensure that all other limiters
/// `try_next` *before* updating its own state, to ensure that all other limiters
/// are okay with the argument first.
struct LimiterCursor<'collection> {
limiters: &'collection mut [Box<dyn CommandSizeLimiter>],
@@ -353,7 +353,7 @@ impl CommandBuilderOptions {
replace: Option<String>,
) -> Result<Self, ExhaustedCommandSpace> {
let initial_args = match &action {
ExecAction::Command(args) => args.iter().map(|arg| arg.as_ref()).collect(),
ExecAction::Command(args) => args.iter().map(std::convert::AsRef::as_ref).collect(),
ExecAction::Echo => vec![OsStr::new("echo")],
};
@@ -726,10 +726,10 @@ fn process_input(
fn parse_delimiter(s: &str) -> Result<u8, String> {
match s.strip_prefix('\\') {
Some(hex) if hex.starts_with('x') => {
u8::from_str_radix(&hex[1..], 16).map_err(|e| format!("Invalid hex sequence: {}", e))
u8::from_str_radix(&hex[1..], 16).map_err(|e| format!("Invalid hex sequence: {e}"))
}
Some(oct) if oct.starts_with('0') => {
u8::from_str_radix(&oct[1..], 8).map_err(|e| format!("Invalid octal sequence: {}", e))
u8::from_str_radix(&oct[1..], 8).map_err(|e| format!("Invalid octal sequence: {e}"))
}
Some(special) => match special {
"a" => Ok(b'\x07'),
@@ -741,7 +741,7 @@ fn parse_delimiter(s: &str) -> Result<u8, String> {
"v" => Ok(b'\x0B'),
"\\" => Ok(b'\\'),
"0" => Ok(b'\0'),
_ => Err(format!("Invalid escape sequence: \\{}", special)),
_ => Err(format!("Invalid escape sequence: \\{special}")),
},
None if s.len() == 1 => Ok(s.as_bytes()[0]),
None => Err("Delimiter must be one byte".to_owned()),
@@ -880,7 +880,7 @@ fn do_xargs(args: &[&str]) -> Result<CommandResult, XargsError> {
let options = Options {
arg_file: matches
.get_one::<String>(options::ARG_FILE)
.map(|value| value.to_owned()),
.map(std::borrow::ToOwned::to_owned),
delimiter: matches.get_one::<u8>(options::DELIMITER).copied(),
exit_if_pass_char_limit: matches.get_flag(options::EXIT),
max_args: matches.get_one::<usize>(options::MAX_ARGS).copied(),
@@ -894,8 +894,7 @@ fn do_xargs(args: &[&str]) -> Result<CommandResult, XargsError> {
matches.contains_id(option).then(|| {
matches
.get_one::<String>(option)
.map(|value| value.to_owned())
.unwrap_or_else(|| "{}".to_string())
.map_or_else(|| "{}".to_string(), std::borrow::ToOwned::to_owned)
})
}),
verbose: matches.get_flag(options::VERBOSE),
@@ -918,7 +917,7 @@ fn do_xargs(args: &[&str]) -> Result<CommandResult, XargsError> {
let action = match matches.get_many::<OsString>(options::COMMAND) {
Some(args) if args.len() > 0 => {
ExecAction::Command(args.map(|arg| arg.to_owned()).collect())
ExecAction::Command(args.map(std::borrow::ToOwned::to_owned).collect())
}
_ => ExecAction::Echo,
};
@@ -960,7 +959,7 @@ fn do_xargs(args: &[&str]) -> Result<CommandResult, XargsError> {
builder_options.close_stdin = options.arg_file.is_none();
let args_file: Box<dyn Read> = if let Some(path) = &options.arg_file {
Box::new(fs::File::open(path).map_err(|e| format!("Failed to open {}: {}", path, e))?)
Box::new(fs::File::open(path).map_err(|e| format!("Failed to open {path}: {e}"))?)
} else {
Box::new(io::stdin())
};
@@ -975,6 +974,7 @@ fn do_xargs(args: &[&str]) -> Result<CommandResult, XargsError> {
Ok(result)
}
#[must_use]
pub fn xargs_main(args: &[&str]) -> i32 {
match do_xargs(args) {
Ok(CommandResult::Success) => 0,
+1 -1
View File
@@ -90,5 +90,5 @@ pub fn get_dir_entry_for(directory: &str, filename: &str) -> DirEntry {
return dir_entry;
}
}
panic!("Couldn't find {} in {}", directory, filename);
panic!("Couldn't find {directory} in {filename}");
}
+5 -10
View File
@@ -285,36 +285,31 @@ fn find_printf() {
if let Err(e) = symlink("abbbc", "test_data/links/link-f") {
assert!(
e.kind() == ErrorKind::AlreadyExists,
"Failed to create sym link: {:?}",
e
"Failed to create sym link: {e:?}"
);
}
if let Err(e) = symlink("subdir", "test_data/links/link-d") {
assert!(
e.kind() == ErrorKind::AlreadyExists,
"Failed to create sym link: {:?}",
e
"Failed to create sym link: {e:?}"
);
}
if let Err(e) = symlink("missing", "test_data/links/link-missing") {
assert!(
e.kind() == ErrorKind::AlreadyExists,
"Failed to create sym link: {:?}",
e
"Failed to create sym link: {e:?}"
);
}
if let Err(e) = symlink("abbbc/x", "test_data/links/link-notdir") {
assert!(
e.kind() == ErrorKind::AlreadyExists,
"Failed to create sym link: {:?}",
e
"Failed to create sym link: {e:?}"
);
}
if let Err(e) = symlink("link-loop", "test_data/links/link-loop") {
assert!(
e.kind() == ErrorKind::AlreadyExists,
"Failed to create sym link: {:?}",
e
"Failed to create sym link: {e:?}"
);
}
}
+10 -10
View File
@@ -220,11 +220,11 @@ fn xargs_exec() {
])
.write_stdin("a b c\nd")
.output();
assert!(result.is_ok(), "xargs failed: {:?}", result);
assert!(result.is_ok(), "xargs failed: {result:?}");
let result = result.unwrap();
assert_eq!(result.status.code(), Some(0));
assert!(result.stderr.is_empty(), "stderr: {:?}", result);
assert!(result.stderr.is_empty(), "stderr: {result:?}");
let stdout_string = String::from_utf8(result.stdout).expect("Found invalid UTF-8");
@@ -255,11 +255,11 @@ fn xargs_exec_stdin_open() {
.write_stdin("test")
.output();
assert!(result.is_ok(), "xargs failed: {:?}", result);
assert!(result.is_ok(), "xargs failed: {result:?}");
let result = result.unwrap();
assert_eq!(result.status.code(), Some(0));
assert!(result.stderr.is_empty(), "stderr: {:?}", result);
assert!(result.stderr.is_empty(), "stderr: {result:?}");
let stdout_string = String::from_utf8(result.stdout).expect("Found invalid UTF-8");
@@ -283,11 +283,11 @@ fn xargs_exec_failure() {
.write_stdin("a b")
.output();
assert!(result.is_ok(), "xargs failed: {:?}", result);
assert!(result.is_ok(), "xargs failed: {result:?}");
let result = result.unwrap();
assert_eq!(result.status.code(), Some(123));
assert!(result.stderr.is_empty(), "stderr: {:?}", result);
assert!(result.stderr.is_empty(), "stderr: {result:?}");
let stdout_string = String::from_utf8(result.stdout).expect("Found invalid UTF-8");
@@ -312,11 +312,11 @@ fn xargs_exec_urgent_failure() {
.write_stdin("a b")
.output();
assert!(result.is_ok(), "xargs failed: {:?}", result);
assert!(result.is_ok(), "xargs failed: {result:?}");
let result = result.unwrap();
assert_eq!(result.status.code(), Some(124));
assert!(!result.stderr.is_empty(), "stderr: {:?}", result);
assert!(!result.stderr.is_empty(), "stderr: {result:?}");
let stdout_string = String::from_utf8(result.stdout).expect("Found invalid UTF-8");
@@ -341,10 +341,10 @@ fn xargs_exec_with_signal() {
.write_stdin("a b")
.output();
assert!(result.is_ok(), "xargs failed: {:?}", result);
assert!(result.is_ok(), "xargs failed: {result:?}");
let result = result.unwrap();
assert_eq!(result.status.code(), Some(125));
assert!(!result.stderr.is_empty(), "stderr: {:?}", result);
assert!(!result.stderr.is_empty(), "stderr: {result:?}");
let stdout_string = String::from_utf8(result.stdout).expect("Found invalid UTF-8");