Skip to content

Commit

Permalink
Merge pull request #272 from jellehelsen/fix-223
Browse files Browse the repository at this point in the history
Fix clippy warning on 'format!' strings
  • Loading branch information
sylvestre authored Sep 5, 2023
2 parents c9a78ed + 6068512 commit fc6eb6f
Show file tree
Hide file tree
Showing 9 changed files with 92 additions and 39 deletions.
2 changes: 1 addition & 1 deletion src/find/matchers/delete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ impl Matcher for DeleteMatcher {
match self.delete(path, file_info.file_type()) {
Ok(_) => true,
Err(e) => {
writeln!(&mut stderr(), "Failed to delete {}: {}", path_str, e).unwrap();
writeln!(&mut stderr(), "Failed to delete {path_str}: {e}").unwrap();
false
}
}
Expand Down
3 changes: 1 addition & 2 deletions src/find/matchers/logical_matchers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,7 @@ impl OrMatcherBuilder {
if self.submatchers.last().unwrap().submatchers.is_empty() {
return Err(From::from(format!(
"invalid expression; you have used a binary operator \
'{}' with nothing before it.",
arg
'{arg}' with nothing before it."
)));
}
self.submatchers.push(AndMatcherBuilder::new());
Expand Down
11 changes: 4 additions & 7 deletions src/find/matchers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,9 +203,8 @@ fn convert_arg_to_number(
match value_as_string.parse::<usize>() {
Ok(val) => Ok(val),
_ => Err(From::from(format!(
"Expected a positive decimal integer argument to {}, but got \
`{}'",
option_name, value_as_string
"Expected a positive decimal integer argument to {option_name}, but got \
`{value_as_string}'"
))),
}
}
Expand All @@ -226,8 +225,7 @@ fn convert_arg_to_comparable_value(
}
Err(From::from(format!(
"Expected a decimal integer (with optional + or - prefix) argument \
to {}, but got `{}'",
option_name, value_as_string
to {option_name}, but got `{value_as_string}'"
)))
}

Expand All @@ -250,8 +248,7 @@ fn convert_arg_to_comparable_value_and_suffix(
}
Err(From::from(format!(
"Expected a decimal integer (with optional + or - prefix) and \
(optional suffix) argument to {}, but got `{}'",
option_name, value_as_string
(optional suffix) argument to {option_name}, but got `{value_as_string}'"
)))
}

Expand Down
20 changes: 10 additions & 10 deletions src/find/matchers/printf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ impl FormatStringParser<'_> {
let octal = self.advance_by(OCTAL_LEN).unwrap();
return match char::from_u32(code) {
Some(c) => Ok(FormatComponent::Literal(c.to_string())),
None => Err(format!("Invalid character value: \\{}", octal).into()),
None => Err(format!("Invalid character value: \\{octal}").into()),
};
}
}
Expand All @@ -186,7 +186,7 @@ impl FormatStringParser<'_> {
'v' => "\x0B",
'0' => "\0",
'\\' => "\\",
c => return Err(format!("Invalid escape sequence: \\{}", c).into()),
c => return Err(format!("Invalid escape sequence: \\{c}").into()),
};

Ok(FormatComponent::Literal(c.to_string()))
Expand Down Expand Up @@ -220,10 +220,10 @@ impl FormatStringParser<'_> {
// We can't store the parsed items inside TimeFormat, because the items
// take a reference to the full format string, but we still try to parse
// it here so that errors get caught early.
let format = format!("%{}", c);
let format = format!("%{c}");
match StrftimeItems::new(&format).next() {
None | Some(chrono::format::Item::Error) => {
Err(format!("Invalid time specifier: %{}{}", first, c).into())
Err(format!("Invalid time specifier: %{first}{c}").into())
}
Some(_item) => Ok(TimeFormat::Strftime(format)),
}
Expand Down Expand Up @@ -318,7 +318,7 @@ impl FormatStringParser<'_> {
let component = match self.advance_one().unwrap() {
'\\' => self.parse_escape_sequence()?,
'%' => self.parse_format_specifier()?,
_ => panic!("Stopped at unexpected character: {}", self.string),
_ => panic!("{}", "Stopped at unexpected character: {self.string}"),
};
components.push(component);
}
Expand Down Expand Up @@ -620,7 +620,7 @@ impl Matcher for Printf {

for component in &self.format.components {
match component {
FormatComponent::Literal(literal) => write!(out, "{}", literal).unwrap(),
FormatComponent::Literal(literal) => write!(out, "{literal}").unwrap(),
FormatComponent::Flush => out.flush().unwrap(),
FormatComponent::Directive {
directive,
Expand All @@ -631,14 +631,14 @@ impl Matcher for Printf {
if let Some(width) = width {
match justify {
Justify::Left => {
write!(out, "{:<width$}", content, width = width).unwrap();
write!(out, "{content:<width$}").unwrap();
}
Justify::Right => {
write!(out, "{:>width$}", content, width = width).unwrap();
write!(out, "{content:>width$}").unwrap();
}
}
} else {
write!(out, "{}", content).unwrap();
write!(out, "{content}").unwrap();
}
}
Err(e) => {
Expand Down Expand Up @@ -1102,7 +1102,7 @@ mod tests {
let matcher = Printf::new("%u %U %g %G").unwrap();
assert!(matcher.matches(&file_info, &mut deps.new_matcher_io()));
assert_eq!(
format!("{} {} {} {}", user, uid, group, gid),
format!("{user} {uid} {group} {gid}"),
deps.get_output_as_string()
);
}
Expand Down
5 changes: 2 additions & 3 deletions src/find/matchers/size.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,8 @@ impl FromStr for Unit {
"G" => Self::GibiByte,
_ => {
return Err(From::from(format!(
"Invalid suffix {} for -size. Only allowed \
values are <nothing>, b, c, w, k, M or G",
s
"Invalid suffix {s} for -size. Only allowed \
values are <nothing>, b, c, w, k, M or G"
)));
}
})
Expand Down
6 changes: 2 additions & 4 deletions src/find/matchers/type_matcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,12 @@ impl TypeMatcher {
// D: door (Solaris)
"D" => {
return Err(From::from(format!(
"Type argument {} not supported yet",
type_string
"Type argument {type_string} not supported yet"
)))
}
_ => {
return Err(From::from(format!(
"Unrecognised type argument {}",
type_string
"Unrecognised type argument {type_string}"
)))
}
};
Expand Down
4 changes: 2 additions & 2 deletions src/find/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ fn process_dir<'a>(
let mut it = walkdir.into_iter();
while let Some(result) = it.next() {
match result {
Err(err) => writeln!(&mut stderr(), "Error: {}: {}", dir, err).unwrap(),
Err(err) => writeln!(&mut stderr(), "Error: {dir}: {err}").unwrap(),
Ok(entry) => {
let mut matcher_io = matchers::MatcherIO::new(deps);
if matcher.matches(&entry, &mut matcher_io) {
Expand Down Expand Up @@ -255,7 +255,7 @@ pub fn find_main<'a>(args: &[&str], deps: &'a dyn Dependencies<'a>) -> i32 {
match do_find(&args[1..], deps) {
Ok(_) => 0,
Err(e) => {
writeln!(&mut stderr(), "Error: {}", e).unwrap();
writeln!(&mut stderr(), "Error: {e}").unwrap();
1
}
}
Expand Down
20 changes: 10 additions & 10 deletions src/xargs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,9 +318,9 @@ impl Display for CommandExecutionError {
match self {
CommandExecutionError::UrgentlyFailed => write!(f, "Command exited with code 255"),
CommandExecutionError::Killed { signal } => {
write!(f, "Command was killed with signal {}", signal)
write!(f, "Command was killed with signal {signal}")
}
CommandExecutionError::CannotRun(err) => write!(f, "Command could not be run: {}", err),
CommandExecutionError::CannotRun(err) => write!(f, "Command could not be run: {err}"),
CommandExecutionError::NotFound => write!(f, "Command not found"),
CommandExecutionError::Unknown => write!(f, "Unknown error running command"),
}
Expand Down Expand Up @@ -407,7 +407,7 @@ impl CommandBuilder<'_> {
command.stdin(Stdio::null());
}
if self.options.verbose {
eprintln!("{:?}", command);
eprintln!("{command:?}");
}

match &self.options.action {
Expand Down Expand Up @@ -511,7 +511,7 @@ where
if let Some(Escape::Quote(q)) = &escape {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("Unterminated quote: {}", q),
format!("Unterminated quote: {q}"),
));
} else if i == 0 {
return Ok(None);
Expand Down Expand Up @@ -622,9 +622,9 @@ impl Display for XargsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
XargsError::ArgumentTooLarge => write!(f, "Argument too large"),
XargsError::CommandExecution(e) => write!(f, "{}", e),
XargsError::Io(e) => write!(f, "{}", e),
XargsError::Untyped(s) => write!(f, "{}", s),
XargsError::CommandExecution(e) => write!(f, "{e}"),
XargsError::Io(e) => write!(f, "{e}"),
XargsError::Untyped(s) => write!(f, "{s}"),
}
}
}
Expand Down Expand Up @@ -707,7 +707,7 @@ fn parse_delimiter(s: &str) -> Result<u8, String> {
"v" => Ok(b'\x0B'),
"0" => Ok(b'\0'),
"\\" => Ok(b'\\'),
_ => Err(format!("Invalid escape sequence: {}", s)),
_ => Err(format!("Invalid escape sequence: {s}")),
}
} else {
let bytes = s.as_bytes();
Expand All @@ -722,7 +722,7 @@ fn parse_delimiter(s: &str) -> Result<u8, String> {
fn validate_positive_usize(s: String) -> Result<(), String> {
match s.parse::<usize>() {
Ok(v) if v > 0 => Ok(()),
Ok(v) => Err(format!("Value must be > 0, not: {}", v)),
Ok(v) => Err(format!("Value must be > 0, not: {v}")),
Err(e) => Err(e.to_string()),
}
}
Expand Down Expand Up @@ -922,7 +922,7 @@ pub fn xargs_main(args: &[&str]) -> i32 {
Ok(CommandResult::Success) => 0,
Ok(CommandResult::Failure) => 123,
Err(e) => {
eprintln!("Error: {}", e);
eprintln!("Error: {e}");
if let XargsError::CommandExecution(cx) = e {
match cx {
CommandExecutionError::UrgentlyFailed => 124,
Expand Down
60 changes: 60 additions & 0 deletions tests/xargs_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -324,3 +324,63 @@ fn xargs_exec_not_found() {
.stderr(predicate::str::contains("Error:"))
.stdout(predicate::str::is_empty());
}

#[test]
fn xargs_exec_verbose() {
Command::cargo_bin("xargs")
.expect("found binary")
.args([
"-n2",
"--verbose",
&path_to_testing_commandline(),
"-",
"--print_stdin",
"--no_print_cwd",
])
.write_stdin("a b c\nd")
.assert()
.success()
.stderr(predicate::str::contains("testing-commandline"))
.stdout(predicate::str::diff(
"stdin=\nargs=\n--print_stdin\n--no_print_cwd\na\nb\n\
stdin=\nargs=\n--print_stdin\n--no_print_cwd\nc\nd\n",
));
}

#[test]
fn xargs_unterminated_quote() {
Command::cargo_bin("xargs")
.expect("found binary")
.args([
"-n2",
&path_to_testing_commandline(),
"-",
"--print_stdin",
"--no_print_cwd",
])
.write_stdin("a \"b c\nd")
.assert()
.failure()
.code(1)
.stderr(predicate::str::contains("Error: Unterminated quote:"))
.stdout(predicate::str::is_empty());
}

#[test]
fn xargs_zero_lines() {
Command::cargo_bin("xargs")
.expect("found binary")
.args([
"-L0",
&path_to_testing_commandline(),
"-",
"--print_stdin",
"--no_print_cwd",
])
.write_stdin("a \"b c\nd")
.assert()
.failure()
.code(1)
.stderr(predicate::str::contains("Value must be > 0, not: 0"))
.stdout(predicate::str::is_empty());
}

0 comments on commit fc6eb6f

Please sign in to comment.