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

chore: manual inline formatting

Minor manual cleanup - inlined many format args.  This makes the code a bit more readable, and helps spot a few inefficiencies and possible bugs.  Note that `&foo` in a `format!` parameter results in a 6% extra performance cost, and does not get inlined by the compiler (yet).
This commit is contained in:
Yuri Astrakhan 2025-04-08 00:18:53 -04:00
parent 9cb4348a55
commit 2d95850700
74 changed files with 226 additions and 319 deletions

View file

@ -64,7 +64,7 @@ fn main() -> io::Result<()> {
for platform in ["unix", "macos", "windows", "unix_android"] {
let platform_utils: Vec<String> = String::from_utf8(
std::process::Command::new("./util/show-utils.sh")
.arg(format!("--features=feat_os_{}", platform))
.arg(format!("--features=feat_os_{platform}"))
.output()?
.stdout,
)
@ -138,7 +138,7 @@ fn main() -> io::Result<()> {
if name == "[" {
continue;
}
let p = format!("docs/src/utils/{}.md", name);
let p = format!("docs/src/utils/{name}.md");
let markdown = File::open(format!("src/uu/{name}/{name}.md"))
.and_then(|mut f: File| {
@ -158,11 +158,11 @@ fn main() -> io::Result<()> {
markdown,
}
.markdown()?;
println!("Wrote to '{}'", p);
println!("Wrote to '{p}'");
} else {
println!("Error writing to {}", p);
println!("Error writing to {p}");
}
writeln!(summary, "* [{0}](utils/{0}.md)", name)?;
writeln!(summary, "* [{name}](utils/{name}.md)")?;
}
Ok(())
}
@ -214,7 +214,7 @@ impl MDWriter<'_, '_> {
.iter()
.any(|u| u == self.name)
{
writeln!(self.w, "<i class=\"fa fa-brands fa-{}\"></i>", icon)?;
writeln!(self.w, "<i class=\"fa fa-brands fa-{icon}\"></i>")?;
}
}
writeln!(self.w, "</div>")?;
@ -242,7 +242,7 @@ impl MDWriter<'_, '_> {
let usage = usage.replace("{}", self.name);
writeln!(self.w, "\n```")?;
writeln!(self.w, "{}", usage)?;
writeln!(self.w, "{usage}")?;
writeln!(self.w, "```")
} else {
Ok(())
@ -293,14 +293,14 @@ impl MDWriter<'_, '_> {
writeln!(self.w)?;
for line in content.lines().skip_while(|l| !l.starts_with('-')) {
if let Some(l) = line.strip_prefix("- ") {
writeln!(self.w, "{}", l)?;
writeln!(self.w, "{l}")?;
} else if line.starts_with('`') {
writeln!(self.w, "```shell\n{}\n```", line.trim_matches('`'))?;
} else if line.is_empty() {
writeln!(self.w)?;
} else {
println!("Not sure what to do with this line:");
println!("{}", line);
println!("{line}");
}
}
writeln!(self.w)?;
@ -332,14 +332,14 @@ impl MDWriter<'_, '_> {
write!(self.w, ", ")?;
}
write!(self.w, "<code>")?;
write!(self.w, "--{}", l)?;
write!(self.w, "--{l}")?;
if let Some(names) = arg.get_value_names() {
write!(
self.w,
"={}",
names
.iter()
.map(|x| format!("&lt;{}&gt;", x))
.map(|x| format!("&lt;{x}&gt;"))
.collect::<Vec<_>>()
.join(" ")
)?;
@ -353,14 +353,14 @@ impl MDWriter<'_, '_> {
write!(self.w, ", ")?;
}
write!(self.w, "<code>")?;
write!(self.w, "-{}", s)?;
write!(self.w, "-{s}")?;
if let Some(names) = arg.get_value_names() {
write!(
self.w,
" {}",
names
.iter()
.map(|x| format!("&lt;{}&gt;", x))
.map(|x| format!("&lt;{x}&gt;"))
.collect::<Vec<_>>()
.join(" ")
)?;

View file

@ -68,7 +68,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
//
for path in name_args {
print!("{}{}", basename(path, &suffix), line_ending);
print!("{}{line_ending}", basename(path, &suffix));
}
Ok(())

View file

@ -101,7 +101,7 @@ enum CatError {
#[error("{0}")]
Nix(#[from] nix::Error),
/// Unknown file type; it's not a regular file, socket, etc.
#[error("unknown filetype: {}", ft_debug)]
#[error("unknown filetype: {ft_debug}")]
UnknownFiletype {
/// A debug print of the file type
ft_debug: String,
@ -457,7 +457,7 @@ fn cat_files(files: &[String], options: &OutputOptions) -> UResult<()> {
for path in files {
if let Err(err) = cat_path(path, options, &mut state, out_info.as_ref()) {
error_messages.push(format!("{}: {}", path.maybe_quote(), err));
error_messages.push(format!("{}: {err}", path.maybe_quote()));
}
}
if state.skipped_carriage_return {

View file

@ -106,7 +106,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
Err(err) => {
return Err(USimpleError::new(
1,
format!("cannot stat attributes of {}: {}", fref.quote(), err),
format!("cannot stat attributes of {}: {err}", fref.quote()),
));
}
},
@ -373,7 +373,7 @@ impl Chmoder {
format!("{}: Permission denied", file.quote()),
));
} else {
return Err(USimpleError::new(1, format!("{}: {}", file.quote(), err)));
return Err(USimpleError::new(1, format!("{}: {err}", file.quote())));
}
}
};
@ -441,24 +441,21 @@ impl Chmoder {
if fperm == mode {
if self.verbose && !self.changes {
println!(
"mode of {} retained as {:04o} ({})",
"mode of {} retained as {fperm:04o} ({})",
file.quote(),
fperm,
display_permissions_unix(fperm as mode_t, false),
);
}
Ok(())
} else if let Err(err) = fs::set_permissions(file, fs::Permissions::from_mode(mode)) {
if !self.quiet {
show_error!("{}", err);
show_error!("{err}");
}
if self.verbose {
println!(
"failed to change mode of file {} from {:04o} ({}) to {:04o} ({})",
"failed to change mode of file {} from {fperm:04o} ({}) to {mode:04o} ({})",
file.quote(),
fperm,
display_permissions_unix(fperm as mode_t, false),
mode,
display_permissions_unix(mode as mode_t, false)
);
}
@ -466,11 +463,9 @@ impl Chmoder {
} else {
if self.verbose || self.changes {
println!(
"mode of {} changed from {:04o} ({}) to {:04o} ({})",
"mode of {} changed from {fperm:04o} ({}) to {mode:04o} ({})",
file.quote(),
fperm,
display_permissions_unix(fperm as mode_t, false),
mode,
display_permissions_unix(mode as mode_t, false)
);
}

View file

@ -485,7 +485,7 @@ pub(crate) fn copy_directory(
}
// Print an error message, but continue traversing the directory.
Err(e) => show_error!("{}", e),
Err(e) => show_error!("{e}"),
}
}

View file

@ -53,11 +53,11 @@ quick_error! {
#[derive(Debug)]
pub enum Error {
/// Simple io::Error wrapper
IoErr(err: io::Error) { from() source(err) display("{}", err)}
IoErr(err: io::Error) { from() source(err) display("{err}")}
/// Wrapper for io::Error with path context
IoErrContext(err: io::Error, path: String) {
display("{}: {}", path, err)
display("{path}: {err}")
context(path: &'a str, err: io::Error) -> (err, path.to_owned())
context(context: String, err: io::Error) -> (err, context)
source(err)
@ -65,7 +65,7 @@ quick_error! {
/// General copy error
Error(err: String) {
display("{}", err)
display("{err}")
from(err: String) -> (err)
from(err: &'static str) -> (err.to_string())
}
@ -75,7 +75,7 @@ quick_error! {
NotAllFilesCopied {}
/// Simple walkdir::Error wrapper
WalkDirErr(err: walkdir::Error) { from() display("{}", err) source(err) }
WalkDirErr(err: walkdir::Error) { from() display("{err}") source(err) }
/// Simple std::path::StripPrefixError wrapper
StripPrefixError(err: StripPrefixError) { from() }
@ -87,15 +87,15 @@ quick_error! {
Skipped(exit_with_error:bool) { }
/// Result of a skipped file
InvalidArgument(description: String) { display("{}", description) }
InvalidArgument(description: String) { display("{description}") }
/// All standard options are included as an an implementation
/// path, but those that are not implemented yet should return
/// a NotImplemented error.
NotImplemented(opt: String) { display("Option '{}' not yet implemented.", opt) }
NotImplemented(opt: String) { display("Option '{opt}' not yet implemented.") }
/// Invalid arguments to backup
Backup(description: String) { display("{}\nTry '{} --help' for more information.", description, uucore::execution_phrase()) }
Backup(description: String) { display("{description}\nTry '{} --help' for more information.", uucore::execution_phrase()) }
NotADirectory(path: PathBuf) { display("'{}' is not a directory", path.display()) }
}
@ -791,7 +791,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
// code should still be EXIT_ERR as does GNU cp
Error::NotAllFilesCopied => {}
// Else we caught a fatal bubbled-up error, log it to stderr
_ => show_error!("{}", error),
_ => show_error!("{error}"),
};
set_exit_code(EXIT_ERR);
}
@ -1283,7 +1283,7 @@ fn show_error_if_needed(error: &Error) {
// should return an error from GNU 9.2
}
_ => {
show_error!("{}", error);
show_error!("{error}");
}
}
}
@ -1686,18 +1686,13 @@ pub(crate) fn copy_attributes(
handle_preserve(&attributes.context, || -> CopyResult<()> {
let context = selinux::SecurityContext::of_path(source, false, false).map_err(|e| {
format!(
"failed to get security context of {}: {}",
"failed to get security context of {}: {e}",
source.display(),
e
)
})?;
if let Some(context) = context {
context.set_for_path(dest, false, false).map_err(|e| {
format!(
"failed to set security context for {}: {}",
dest.display(),
e
)
format!("failed to set security context for {}: {e}", dest.display(),)
})?;
}

View file

@ -30,9 +30,9 @@ impl std::fmt::Display for Pattern {
match self {
Self::UpToLine(n, _) => write!(f, "{n}"),
Self::UpToMatch(regex, 0, _) => write!(f, "/{}/", regex.as_str()),
Self::UpToMatch(regex, offset, _) => write!(f, "/{}/{:+}", regex.as_str(), offset),
Self::UpToMatch(regex, offset, _) => write!(f, "/{}/{offset:+}", regex.as_str()),
Self::SkipToMatch(regex, 0, _) => write!(f, "%{}%", regex.as_str()),
Self::SkipToMatch(regex, offset, _) => write!(f, "%{}%{:+}", regex.as_str(), offset),
Self::SkipToMatch(regex, offset, _) => write!(f, "%{}%{offset:+}", regex.as_str()),
}
}
}
@ -168,7 +168,7 @@ fn validate_line_numbers(patterns: &[Pattern]) -> Result<(), CsplitError> {
(_, 0) => Err(CsplitError::LineNumberIsZero),
// two consecutive numbers should not be equal
(n, m) if n == m => {
show_warning!("line number '{}' is the same as preceding line number", n);
show_warning!("line number '{n}' is the same as preceding line number");
Ok(n)
}
// a number cannot be greater than the one that follows

View file

@ -83,7 +83,7 @@ pub(crate) fn to_magnitude_and_suffix(n: u128, suffix_type: SuffixType) -> Strin
if quotient < 10.0 {
format!("{quotient:.1} {suffix}")
} else {
format!("{} {}", quotient.round(), suffix)
format!("{} {suffix}", quotient.round())
}
}

View file

@ -29,29 +29,28 @@ fn unimplemented_flags_should_error_non_linux() {
"noctty",
"nofollow",
] {
let args = vec![format!("iflag={}", flag)];
let args = vec![format!("iflag={flag}")];
if Parser::new()
.parse(&args.iter().map(AsRef::as_ref).collect::<Vec<_>>()[..])
.is_ok()
{
succeeded.push(format!("iflag={}", flag));
succeeded.push(format!("iflag={flag}"));
}
let args = vec![format!("oflag={}", flag)];
let args = vec![format!("oflag={flag}")];
if Parser::new()
.parse(&args.iter().map(AsRef::as_ref).collect::<Vec<_>>()[..])
.is_ok()
{
succeeded.push(format!("iflag={}", flag));
succeeded.push(format!("iflag={flag}"));
}
}
assert!(
succeeded.is_empty(),
"The following flags did not panic as expected: {:?}",
succeeded
"The following flags did not panic as expected: {succeeded:?}",
);
}

View file

@ -98,9 +98,9 @@ pub(crate) fn to_magnitude_and_suffix(n: u128, suffix_type: SuffixType) -> Strin
if rem % (bases[i] / 10) == 0 {
format!("{quot}.{tenths_place}{suffix}")
} else if tenths_place + 1 == 10 || quot >= 10 {
format!("{}{}", quot + 1, suffix)
format!("{}{suffix}", quot + 1)
} else {
format!("{}.{}{}", quot, tenths_place + 1, suffix)
format!("{quot}.{}{suffix}", tenths_place + 1)
}
}
}

View file

@ -114,13 +114,7 @@ fn generate_ls_colors(fmt: &OutputFmt, sep: &str) -> String {
}
let (prefix, suffix) = get_colors_format_strings(fmt);
let ls_colors = parts.join(sep);
format!(
"{}{}:{}:{}",
prefix,
generate_type_output(fmt),
ls_colors,
suffix
)
format!("{prefix}{}:{ls_colors}:{suffix}", generate_type_output(fmt),)
}
}
}
@ -233,10 +227,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
);
}
Err(e) => {
return Err(USimpleError::new(
1,
format!("{}: {}", path.maybe_quote(), e),
));
return Err(USimpleError::new(1, format!("{}: {e}", path.maybe_quote())));
}
}
}
@ -388,9 +379,8 @@ where
if val.is_empty() {
return Err(format!(
// The double space is what GNU is doing
"{}:{}: invalid line; missing second token",
"{}:{num}: invalid line; missing second token",
fp.maybe_quote(),
num
));
}

View file

@ -466,7 +466,7 @@ fn build_exclude_patterns(matches: &ArgMatches) -> UResult<Vec<Pattern>> {
let mut exclude_patterns = Vec::new();
for f in excludes_iterator.chain(exclude_from_iterator) {
if matches.get_flag(options::VERBOSE) {
println!("adding {:?} to the exclude list ", &f);
println!("adding {f:?} to the exclude list ");
}
match parse_glob::from_str(&f) {
Ok(glob) => exclude_patterns.push(glob),
@ -559,7 +559,7 @@ impl StatPrinter {
let secs = get_time_secs(time, stat)?;
let tm = DateTime::<Local>::from(UNIX_EPOCH + Duration::from_secs(secs));
let time_str = tm.format(&self.time_format).to_string();
print!("{}\t{}\t", self.convert_size(size), time_str);
print!("{}\t{time_str}\t", self.convert_size(size));
} else {
print!("{}\t", self.convert_size(size));
}
@ -1095,12 +1095,12 @@ fn format_error_message(error: &ParseSizeError, s: &str, option: &str) -> String
// GNU's du echos affected flag, -B or --block-size (-t or --threshold), depending user's selection
match error {
ParseSizeError::InvalidSuffix(_) => {
format!("invalid suffix in --{} argument {}", option, s.quote())
format!("invalid suffix in --{option} argument {}", s.quote())
}
ParseSizeError::ParseFailure(_) | ParseSizeError::PhysicalMem(_) => {
format!("invalid --{} argument {}", option, s.quote())
format!("invalid --{option} argument {}", s.quote())
}
ParseSizeError::SizeTooBig(_) => format!("--{} argument {} too large", option, s.quote()),
ParseSizeError::SizeTooBig(_) => format!("--{option} argument {} too large", s.quote()),
}
}

16
src/uu/env/src/env.rs vendored
View file

@ -193,7 +193,7 @@ fn load_config_file(opts: &mut Options) -> UResult<()> {
};
let conf =
conf.map_err(|e| USimpleError::new(1, format!("{}: {}", file.maybe_quote(), e)))?;
conf.map_err(|e| USimpleError::new(1, format!("{}: {e}", file.maybe_quote())))?;
for (_, prop) in &conf {
// ignore all INI section lines (treat them as comments)
@ -338,7 +338,7 @@ pub fn parse_args_from_str(text: &NativeIntStr) -> UResult<Vec<NativeIntString>>
fn debug_print_args(args: &[OsString]) {
eprintln!("input args:");
for (i, arg) in args.iter().enumerate() {
eprintln!("arg[{}]: {}", i, arg.quote());
eprintln!("arg[{i}]: {}", arg.quote());
}
}
@ -378,7 +378,7 @@ impl EnvAppData {
fn make_error_no_such_file_or_dir(&self, prog: &OsStr) -> Box<dyn UError> {
uucore::show_error!("{}: No such file or directory", prog.quote());
if !self.had_string_argument {
uucore::show_error!("{}", ERROR_MSG_S_SHEBANG);
uucore::show_error!("{ERROR_MSG_S_SHEBANG}");
}
ExitCode::new(127)
}
@ -451,9 +451,9 @@ impl EnvAppData {
let s = format!("{e}");
if !s.is_empty() {
let s = s.trim_end();
uucore::show_error!("{}", s);
uucore::show_error!("{s}");
}
uucore::show_error!("{}", ERROR_MSG_S_SHEBANG);
uucore::show_error!("{ERROR_MSG_S_SHEBANG}");
uucore::error::ExitCode::new(125)
}
}
@ -545,9 +545,9 @@ impl EnvAppData {
if do_debug_printing {
eprintln!("executing: {}", prog.maybe_quote());
let arg_prefix = " arg";
eprintln!("{}[{}]= {}", arg_prefix, 0, arg0.quote());
eprintln!("{arg_prefix}[{}]= {}", 0, arg0.quote());
for (i, arg) in args.iter().enumerate() {
eprintln!("{}[{}]= {}", arg_prefix, i + 1, arg.quote());
eprintln!("{arg_prefix}[{}]= {}", i + 1, arg.quote());
}
}
@ -590,7 +590,7 @@ impl EnvAppData {
return Err(126.into());
}
_ => {
uucore::show_error!("unknown error: {:?}", err);
uucore::show_error!("unknown error: {err:?}");
return Err(126.into());
}
},

View file

@ -448,7 +448,7 @@ fn expand(options: &Options) -> UResult<()> {
for file in &options.files {
if Path::new(file).is_dir() {
show_error!("{}: Is a directory", file);
show_error!("{file}: Is a directory");
set_exit_code(1);
continue;
}
@ -463,7 +463,7 @@ fn expand(options: &Options) -> UResult<()> {
}
}
Err(e) => {
show_error!("{}", e);
show_error!("{e}");
set_exit_code(1);
continue;
}

View file

@ -105,7 +105,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
}
Err(e) => {
set_exit_code(1);
show_error!("error reading input: {}", e);
show_error!("error reading input: {e}");
return Ok(());
}
}
@ -113,7 +113,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
}
if let Err(e) = w.flush() {
show_error!("{}", e);
show_error!("{e}");
}
Ok(())

View file

@ -36,7 +36,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
// Try to display this error.
if let Err(print_fail) = error {
// Completely ignore any error here, no more failover and we will fail in any case.
let _ = writeln!(std::io::stderr(), "{}: {}", uucore::util_name(), print_fail);
let _ = writeln!(std::io::stderr(), "{}: {print_fail}", uucore::util_name());
}
}

View file

@ -143,7 +143,7 @@ impl FmtOptions {
Err(e) => {
return Err(USimpleError::new(
1,
format!("Invalid TABWIDTH specification: {}: {}", s.quote(), e),
format!("Invalid TABWIDTH specification: {}: {e}", s.quote()),
));
}
};

View file

@ -43,7 +43,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
Some(inp_width) => inp_width.parse::<usize>().map_err(|e| {
USimpleError::new(
1,
format!("illegal width value ({}): {}", inp_width.quote(), e),
format!("illegal width value ({}): {e}", inp_width.quote()),
)
})?,
None => 80,

View file

@ -69,7 +69,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
match Passwd::locate(user.as_str()) {
Ok(p) => {
let groups: Vec<String> = p.belongs_to().iter().map(infallible_gid2grp).collect();
println!("{} : {}", user, groups.join(" "));
println!("{user} : {}", groups.join(" "));
}
Err(_) => {
// The `show!()` macro sets the global exit code for the program.

View file

@ -181,7 +181,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
#[cfg(all(any(target_os = "linux", target_os = "android"), feature = "selinux"))]
if let Ok(context) = selinux::SecurityContext::current(false) {
let bytes = context.as_bytes();
print!("{}{}", String::from_utf8_lossy(bytes), line_ending);
print!("{}{line_ending}", String::from_utf8_lossy(bytes));
} else {
// print error because `cflag` was explicitly requested
return Err(USimpleError::new(1, "can't get process context"));
@ -246,7 +246,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
"{}",
if state.nflag {
entries::gid2grp(gid).unwrap_or_else(|_| {
show_error!("cannot find name for group ID {}", gid);
show_error!("cannot find name for group ID {gid}");
set_exit_code(1);
gid.to_string()
})
@ -261,7 +261,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
"{}",
if state.nflag {
entries::uid2usr(uid).unwrap_or_else(|_| {
show_error!("cannot find name for user ID {}", uid);
show_error!("cannot find name for user ID {uid}");
set_exit_code(1);
uid.to_string()
})
@ -286,7 +286,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
.map(|&id| {
if state.nflag {
entries::gid2grp(id).unwrap_or_else(|_| {
show_error!("cannot find name for group ID {}", id);
show_error!("cannot find name for group ID {id}");
set_exit_code(1);
id.to_string()
})
@ -557,39 +557,37 @@ fn id_print(state: &State, groups: &[u32]) {
let egid = state.ids.as_ref().unwrap().egid;
print!(
"uid={}({})",
uid,
"uid={uid}({})",
entries::uid2usr(uid).unwrap_or_else(|_| {
show_error!("cannot find name for user ID {}", uid);
show_error!("cannot find name for user ID {uid}");
set_exit_code(1);
uid.to_string()
})
);
print!(
" gid={}({})",
gid,
" gid={gid}({})",
entries::gid2grp(gid).unwrap_or_else(|_| {
show_error!("cannot find name for group ID {}", gid);
show_error!("cannot find name for group ID {gid}");
set_exit_code(1);
gid.to_string()
})
);
if !state.user_specified && (euid != uid) {
print!(
" euid={}({})",
euid,
" euid={euid}({})",
entries::uid2usr(euid).unwrap_or_else(|_| {
show_error!("cannot find name for user ID {}", euid);
show_error!("cannot find name for user ID {euid}");
set_exit_code(1);
euid.to_string()
})
);
}
if !state.user_specified && (egid != gid) {
// BUG? printing egid={euid} ?
print!(
" egid={egid}({})",
entries::gid2grp(egid).unwrap_or_else(|_| {
show_error!("cannot find name for group ID {}", egid);
show_error!("cannot find name for group ID {egid}");
set_exit_code(1);
egid.to_string()
})
@ -600,10 +598,9 @@ fn id_print(state: &State, groups: &[u32]) {
groups
.iter()
.map(|&gr| format!(
"{}({})",
gr,
"{gr}({})",
entries::gid2grp(gr).unwrap_or_else(|_| {
show_error!("cannot find name for group ID {}", gr);
show_error!("cannot find name for group ID {gr}");
set_exit_code(1);
gr.to_string()
})

View file

@ -353,7 +353,7 @@ fn behavior(matches: &ArgMatches) -> UResult<Behavior> {
let specified_mode: Option<u32> = if matches.contains_id(OPT_MODE) {
let x = matches.get_one::<String>(OPT_MODE).ok_or(1)?;
Some(mode::parse(x, considering_dir, get_umask()).map_err(|err| {
show_error!("Invalid mode string: {}", err);
show_error!("Invalid mode string: {err}");
1
})?)
} else {
@ -753,9 +753,8 @@ fn copy_file(from: &Path, to: &Path) -> UResult<()> {
if let Err(e) = fs::remove_file(to) {
if e.kind() != std::io::ErrorKind::NotFound {
show_error!(
"Failed to remove existing file {}. Error: {:?}",
"Failed to remove existing file {}. Error: {e:?}",
to.display(),
e
);
}
}
@ -871,7 +870,7 @@ fn preserve_timestamps(from: &Path, to: &Path) -> UResult<()> {
match set_file_times(to, accessed_time, modified_time) {
Ok(_) => Ok(()),
Err(e) => {
show_error!("{}", e);
show_error!("{e}");
Ok(())
}
}

View file

@ -25,7 +25,7 @@ pub fn chmod(path: &Path, mode: u32) -> Result<(), ()> {
use std::os::unix::fs::PermissionsExt;
use uucore::{display::Quotable, show_error};
fs::set_permissions(path, fs::Permissions::from_mode(mode)).map_err(|err| {
show_error!("{}: chmod failed with error {}", path.maybe_quote(), err);
show_error!("{}: chmod failed with error {err}", path.maybe_quote());
})
}

View file

@ -650,7 +650,7 @@ impl<'a> State<'a> {
if input.check_order == CheckOrder::Enabled {
return Err(JoinError::UnorderedInput(err_msg));
}
eprintln!("{}: {}", uucore::execution_phrase(), err_msg);
eprintln!("{}: {err_msg}", uucore::execution_phrase());
self.has_failed = true;
}

View file

@ -230,7 +230,7 @@ fn parse_pids(pids: &[String]) -> UResult<Vec<i32>> {
pids.iter()
.map(|x| {
x.parse::<i32>().map_err(|e| {
USimpleError::new(1, format!("failed to parse argument {}: {}", x.quote(), e))
USimpleError::new(1, format!("failed to parse argument {}: {e}", x.quote()))
})
})
.collect()

View file

@ -93,8 +93,7 @@ static ARG_FILES: &str = "files";
#[uucore::main]
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let after_help = format!(
"{}\n\n{}",
AFTER_HELP,
"{AFTER_HELP}\n\n{}",
backup_control::BACKUP_CONTROL_LONG_HELP
);
@ -299,7 +298,7 @@ fn link_files_in_dir(files: &[PathBuf], target_dir: &Path, settings: &Settings)
// We need to clean the target
if target_dir.is_file() {
if let Err(e) = fs::remove_file(target_dir) {
show_error!("Could not update {}: {}", target_dir.quote(), e);
show_error!("Could not update {}: {e}", target_dir.quote());
};
}
if target_dir.is_dir() {
@ -307,7 +306,7 @@ fn link_files_in_dir(files: &[PathBuf], target_dir: &Path, settings: &Settings)
// considered as a dir
// See test_ln::test_symlink_no_deref_dir
if let Err(e) = fs::remove_dir(target_dir) {
show_error!("Could not update {}: {}", target_dir.quote(), e);
show_error!("Could not update {}: {e}", target_dir.quote());
};
}
target_dir.to_path_buf()
@ -340,7 +339,7 @@ fn link_files_in_dir(files: &[PathBuf], target_dir: &Path, settings: &Settings)
);
all_successful = false;
} else if let Err(e) = link(srcpath, &targetpath, settings) {
show_error!("{}", e);
show_error!("{e}");
all_successful = false;
}

View file

@ -665,9 +665,8 @@ fn extract_quoting_style(options: &clap::ArgMatches, show_control: bool) -> Quot
match match_quoting_style_name(style.as_str(), show_control) {
Some(qs) => return qs,
None => eprintln!(
"{}: Ignoring invalid value of environment variable QUOTING_STYLE: '{}'",
"{}: Ignoring invalid value of environment variable QUOTING_STYLE: '{style}'",
std::env::args().next().unwrap_or_else(|| "ls".to_string()),
style
),
}
}

View file

@ -64,7 +64,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
if let Err(e) = fs::set_permissions(&f, fs::Permissions::from_mode(mode as u32)) {
return Err(USimpleError::new(
1,
format!("cannot set permissions on {}: {}", f.quote(), e),
format!("cannot set permissions on {}: {e}", f.quote()),
));
}
}

View file

@ -473,7 +473,7 @@ fn make_temp_dir(dir: &Path, prefix: &str, rand: usize, suffix: &str) -> UResult
Ok(path)
}
Err(e) if e.kind() == ErrorKind::NotFound => {
let filename = format!("{}{}{}", prefix, "X".repeat(rand), suffix);
let filename = format!("{prefix}{}{suffix}", "X".repeat(rand));
let path = Path::new(dir).join(filename);
let s = path.display().to_string();
Err(MkTempError::NotFound("directory".to_string(), s).into())
@ -503,7 +503,7 @@ fn make_temp_file(dir: &Path, prefix: &str, rand: usize, suffix: &str) -> UResul
Err(e) => Err(MkTempError::PersistError(e.file.path().to_path_buf()).into()),
},
Err(e) if e.kind() == ErrorKind::NotFound => {
let filename = format!("{}{}{}", prefix, "X".repeat(rand), suffix);
let filename = format!("{prefix}{}{suffix}", "X".repeat(rand));
let path = Path::new(dir).join(filename);
let s = path.display().to_string();
Err(MkTempError::NotFound("file".to_string(), s).into())

View file

@ -591,9 +591,8 @@ impl<'a> Pager<'a> {
write!(
stdout,
"\r{}{}{}",
"\r{}{banner}{}",
Attribute::Reverse,
banner,
Attribute::Reset
)
.unwrap();

View file

@ -372,12 +372,11 @@ fn nl<T: Read>(reader: &mut BufReader<T>, stats: &mut Stats, settings: &Settings
return Err(USimpleError::new(1, "line number overflow"));
};
println!(
"{}{}{}",
"{}{}{line}",
settings
.number_format
.format(line_number, settings.number_width),
settings.number_separator,
line
);
// update line number for the potential next line
match line_number.checked_add(settings.line_increment) {

View file

@ -36,7 +36,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
Err(e) => {
return Err(USimpleError::new(
1,
format!("{} is not a valid number: {}", numstr.quote(), e),
format!("{} is not a valid number: {e}", numstr.quote()),
));
}
},

View file

@ -139,9 +139,7 @@ fn remove_suffix(i: f64, s: Option<Suffix>, u: &Unit) -> Result<f64> {
"missing 'i' suffix in input: '{i}{raw_suffix:?}' (e.g Ki/Mi/Gi)"
)),
(Some((raw_suffix, with_i)), &Unit::None) => Err(format!(
"rejecting suffix in input: '{}{:?}{}' (consider using --from)",
i,
raw_suffix,
"rejecting suffix in input: '{i}{raw_suffix:?}{}' (consider using --from)",
if with_i { "i" } else { "" }
)),
(None, _) => Ok(i),
@ -267,19 +265,13 @@ fn transform_to(
format!(
"{:.precision$}",
round_with_precision(i2, round_method, precision),
precision = precision
)
}
Some(s) if precision > 0 => {
format!(
"{:.precision$}{}",
i2,
DisplayableSuffix(s, opts.to),
precision = precision
)
format!("{i2:.precision$}{}", DisplayableSuffix(s, opts.to),)
}
Some(s) if i2.abs() < 10.0 => format!("{:.1}{}", i2, DisplayableSuffix(s, opts.to)),
Some(s) => format!("{:.0}{}", i2, DisplayableSuffix(s, opts.to)),
Some(s) if i2.abs() < 10.0 => format!("{i2:.1}{}", DisplayableSuffix(s, opts.to)),
Some(s) => format!("{i2:.0}{}", DisplayableSuffix(s, opts.to)),
})
}
@ -323,25 +315,21 @@ fn format_string(
let padded_number = match padding {
0 => number_with_suffix,
p if p > 0 && options.format.zero_padding => {
let zero_padded = format!("{:0>padding$}", number_with_suffix, padding = p as usize);
let zero_padded = format!("{number_with_suffix:0>padding$}", padding = p as usize);
match implicit_padding.unwrap_or(options.padding) {
0 => zero_padded,
p if p > 0 => format!("{:>padding$}", zero_padded, padding = p as usize),
p => format!("{:<padding$}", zero_padded, padding = p.unsigned_abs()),
p if p > 0 => format!("{zero_padded:>padding$}", padding = p as usize),
p => format!("{zero_padded:<padding$}", padding = p.unsigned_abs()),
}
}
p if p > 0 => format!("{:>padding$}", number_with_suffix, padding = p as usize),
p => format!(
"{:<padding$}",
number_with_suffix,
padding = p.unsigned_abs()
),
p if p > 0 => format!("{number_with_suffix:>padding$}", padding = p as usize),
p => format!("{number_with_suffix:<padding$}", padding = p.unsigned_abs()),
};
Ok(format!(
"{}{}{}",
options.format.prefix, padded_number, options.format.suffix
"{}{padded_number}{}",
options.format.prefix, options.format.suffix
))
}

View file

@ -63,7 +63,7 @@ fn format_and_handle_validation(input_line: &str, options: &NumfmtOptions) -> UR
show!(NumfmtError::FormattingError(error_message));
}
InvalidModes::Warn => {
show_error!("{}", error_message);
show_error!("{error_message}");
}
InvalidModes::Ignore => {}
};

View file

@ -48,11 +48,11 @@ impl InputOffset {
pub fn format_byte_offset(&self) -> String {
match (self.radix, self.label) {
(Radix::Decimal, None) => format!("{:07}", self.byte_pos),
(Radix::Decimal, Some(l)) => format!("{:07} ({:07})", self.byte_pos, l),
(Radix::Decimal, Some(l)) => format!("{:07} ({l:07})", self.byte_pos),
(Radix::Hexadecimal, None) => format!("{:06X}", self.byte_pos),
(Radix::Hexadecimal, Some(l)) => format!("{:06X} ({:06X})", self.byte_pos, l),
(Radix::Hexadecimal, Some(l)) => format!("{:06X} ({l:06X})", self.byte_pos),
(Radix::Octal, None) => format!("{:07o}", self.byte_pos),
(Radix::Octal, Some(l)) => format!("{:07o} ({:07o})", self.byte_pos, l),
(Radix::Octal, Some(l)) => format!("{:07o} ({l:07o})", self.byte_pos),
(Radix::NoPrefix, None) => String::new(),
(Radix::NoPrefix, Some(l)) => format!("({l:07o})"),
}

View file

@ -60,9 +60,9 @@ impl MultifileReader<'_> {
Err(e) => {
// If any file can't be opened,
// print an error at the time that the file is needed,
// then move on the the next file.
// then move to the next file.
// This matches the behavior of the original `od`
show_error!("{}: {}", fname.maybe_quote(), e);
show_error!("{}: {e}", fname.maybe_quote());
self.any_err = true;
}
}
@ -95,7 +95,7 @@ impl io::Read for MultifileReader<'_> {
Ok(0) => break,
Ok(n) => n,
Err(e) => {
show_error!("I/O: {}", e);
show_error!("I/O: {e}");
self.any_err = true;
break;
}

View file

@ -148,7 +148,7 @@ impl OdOptions {
cmp::max(max, next.formatter_item_info.byte_size)
});
if line_bytes == 0 || line_bytes % min_bytes != 0 {
show_warning!("invalid width {}; using {} instead", line_bytes, min_bytes);
show_warning!("invalid width {line_bytes}; using {min_bytes} instead");
line_bytes = min_bytes;
}
@ -522,7 +522,7 @@ where
input_offset.increase_position(length as u64);
}
Err(e) => {
show_error!("{}", e);
show_error!("{e}");
input_offset.print_final_offset();
return Err(1.into());
}
@ -575,10 +575,9 @@ fn print_bytes(prefix: &str, input_decoder: &MemoryDecoder, output_info: &Output
.saturating_sub(output_text.chars().count());
write!(
output_text,
"{:>width$} {}",
"{:>missing_spacing$} {}",
"",
format_ascii_dump(input_decoder.get_buffer(0)),
width = missing_spacing
)
.unwrap();
}
@ -624,11 +623,11 @@ fn format_error_message(error: &ParseSizeError, s: &str, option: &str) -> String
// GNU's od echos affected flag, -N or --read-bytes (-j or --skip-bytes, etc.), depending user's selection
match error {
ParseSizeError::InvalidSuffix(_) => {
format!("invalid suffix in --{} argument {}", option, s.quote())
format!("invalid suffix in --{option} argument {}", s.quote())
}
ParseSizeError::ParseFailure(_) | ParseSizeError::PhysicalMem(_) => {
format!("invalid --{} argument {}", option, s.quote())
format!("invalid --{option} argument {}", s.quote())
}
ParseSizeError::SizeTooBig(_) => format!("--{} argument {} too large", option, s.quote()),
ParseSizeError::SizeTooBig(_) => format!("--{option} argument {} too large", s.quote()),
}
}

View file

@ -274,8 +274,7 @@ fn parse_type_string(params: &str) -> Result<Vec<ParsedFormatterItemInfo>, Strin
while let Some(type_char) = ch {
let type_char = format_type(type_char).ok_or_else(|| {
format!(
"unexpected char '{}' in format specification {}",
type_char,
"unexpected char '{type_char}' in format specification {}",
params.quote()
)
})?;
@ -309,8 +308,7 @@ fn parse_type_string(params: &str) -> Result<Vec<ParsedFormatterItemInfo>, Strin
let ft = od_format_type(type_char, byte_size).ok_or_else(|| {
format!(
"invalid size '{}' in format specification {}",
byte_size,
"invalid size '{byte_size}' in format specification {}",
params.quote()
)
})?;

View file

@ -79,11 +79,11 @@ fn format_float(f: f64, width: usize, precision: usize) -> String {
}
if l >= 0 && l <= (precision as i32 - 1) {
format!("{:width$.dec$}", f, dec = (precision - 1) - l as usize)
format!("{f:width$.dec$}", dec = (precision - 1) - l as usize)
} else if l == -1 {
format!("{f:width$.precision$}")
} else {
format!("{:width$.dec$e}", f, dec = precision - 1)
format!("{f:width$.dec$e}", dec = precision - 1)
}
}

View file

@ -140,9 +140,7 @@ fn check_basic(path: &[String]) -> bool {
if component_len > POSIX_NAME_MAX {
writeln!(
std::io::stderr(),
"limit {} exceeded by length {} of file name component {}",
POSIX_NAME_MAX,
component_len,
"limit {POSIX_NAME_MAX} exceeded by length {component_len} of file name component {}",
p.quote()
);
return false;
@ -184,9 +182,8 @@ fn check_default(path: &[String]) -> bool {
if total_len > libc::PATH_MAX as usize {
writeln!(
std::io::stderr(),
"limit {} exceeded by length {} of file name {}",
"limit {} exceeded by length {total_len} of file name {}",
libc::PATH_MAX,
total_len,
joined_path.quote()
);
return false;
@ -208,9 +205,8 @@ fn check_default(path: &[String]) -> bool {
if component_len > libc::FILENAME_MAX as usize {
writeln!(
std::io::stderr(),
"limit {} exceeded by length {} of file name component {}",
"limit {} exceeded by length {component_len} of file name component {}",
libc::FILENAME_MAX,
component_len,
p.quote()
);
return false;
@ -244,8 +240,7 @@ fn check_portable_chars(path_segment: &str) -> bool {
let invalid = path_segment[i..].chars().next().unwrap();
writeln!(
std::io::stderr(),
"nonportable character '{}' in file name component {}",
invalid,
"nonportable character '{invalid}' in file name component {}",
path_segment.quote()
);
return false;

View file

@ -194,7 +194,7 @@ impl Pinky {
}
}
print!(" {}{:<8.*}", mesg, utmpx::UT_LINESIZE, ut.tty_device());
print!(" {mesg}{:<8.*}", utmpx::UT_LINESIZE, ut.tty_device());
if self.include_idle {
if last_change == 0 {

View file

@ -139,28 +139,28 @@ quick_error! {
enum PrError {
Input(err: std::io::Error, path: String) {
context(path: &'a str, err: std::io::Error) -> (err, path.to_owned())
display("pr: Reading from input {0} gave error", path)
display("pr: Reading from input {path} gave error")
source(err)
}
UnknownFiletype(path: String) {
display("pr: {0}: unknown filetype", path)
display("pr: {path}: unknown filetype")
}
EncounteredErrors(msg: String) {
display("pr: {0}", msg)
display("pr: {msg}")
}
IsDirectory(path: String) {
display("pr: {0}: Is a directory", path)
display("pr: {path}: Is a directory")
}
IsSocket(path: String) {
display("pr: cannot open {}, Operation not supported on socket", path)
display("pr: cannot open {path}, Operation not supported on socket")
}
NotExists(path: String) {
display("pr: cannot open {}, No such file or directory", path)
display("pr: cannot open {path}, No such file or directory")
}
}
}
@ -470,7 +470,7 @@ fn parse_usize(matches: &ArgMatches, opt: &str) -> Option<Result<usize, PrError>
let i = value_to_parse.0;
let option = value_to_parse.1;
i.parse().map_err(|_e| {
PrError::EncounteredErrors(format!("invalid {} argument {}", option, i.quote()))
PrError::EncounteredErrors(format!("invalid {option} argument {}", i.quote()))
})
};
matches
@ -1123,8 +1123,7 @@ fn get_line_for_printing(
let formatted_line_number = get_formatted_line_number(options, file_line.line_number, index);
let mut complete_line = format!(
"{}{}",
formatted_line_number,
"{formatted_line_number}{}",
file_line.line_content.as_ref().unwrap()
);
@ -1141,8 +1140,7 @@ fn get_line_for_printing(
};
format!(
"{}{}{}",
offset_spaces,
"{offset_spaces}{}{sep}",
line_width
.map(|i| {
let min_width = (i - (columns - 1)) / columns;
@ -1155,7 +1153,6 @@ fn get_line_for_printing(
complete_line.chars().take(min_width).collect()
})
.unwrap_or(complete_line),
sep
)
}
@ -1168,11 +1165,7 @@ fn get_formatted_line_number(opts: &OutputOptions, line_number: usize, index: us
let width = num_opt.width;
let separator = &num_opt.separator;
if line_str.len() >= width {
format!(
"{:>width$}{}",
&line_str[line_str.len() - width..],
separator
)
format!("{:>width$}{separator}", &line_str[line_str.len() - width..],)
} else {
format!("{line_str:>width$}{separator}")
}
@ -1186,8 +1179,8 @@ fn get_formatted_line_number(opts: &OutputOptions, line_number: usize, index: us
fn header_content(options: &OutputOptions, page: usize) -> Vec<String> {
if options.display_header_and_trailer {
let first_line = format!(
"{} {} Page {}",
options.last_modified_time, options.header, page
"{} {} Page {page}",
options.last_modified_time, options.header
);
vec![
String::new(),

View file

@ -519,9 +519,9 @@ fn get_output_chunks(
// put left context truncation string if needed
if before_beg != 0 && head_beg == head_end {
before = format!("{}{}", config.trunc_str, before);
before = format!("{}{before}", config.trunc_str);
} else if before_beg != 0 && head_beg != 0 {
head = format!("{}{}", config.trunc_str, head);
head = format!("{}{head}", config.trunc_str);
}
(tail, before, after, head)

View file

@ -161,7 +161,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
"?"
}
);
if !prompt_yes!("{}", msg) {
if !prompt_yes!("{msg}") {
return Ok(());
}
}
@ -500,10 +500,7 @@ fn handle_dir(path: &Path, options: &Options) -> bool {
} else if options.dir && (!is_root || !options.preserve_root) {
had_err = remove_dir(path, options).bitor(had_err);
} else if options.recursive {
show_error!(
"it is dangerous to operate recursively on '{}'",
MAIN_SEPARATOR
);
show_error!("it is dangerous to operate recursively on '{MAIN_SEPARATOR}'");
show_error!("use --no-preserve-root to override this failsafe");
had_err = true;
} else {
@ -561,7 +558,7 @@ fn remove_file(path: &Path, options: &Options) -> bool {
// GNU compatibility (rm/fail-eacces.sh)
show_error!("cannot remove {}: {}", path.quote(), "Permission denied");
} else {
show_error!("cannot remove {}: {}", path.quote(), e);
show_error!("cannot remove {}: {e}", path.quote());
}
return true;
}

View file

@ -484,11 +484,9 @@ fn wipe_file(
if verbose {
let pass_name = pass_name(&pass_type);
show_error!(
"{}: pass {:2}/{} ({})...",
"{}: pass {:2}/{total_passes} ({pass_name})...",
path.maybe_quote(),
i + 1,
total_passes,
pass_name
);
}
// size is an optional argument for exactly how many bytes we want to shred
@ -578,10 +576,9 @@ fn wipe_name(orig_path: &Path, verbose: bool, remove_method: RemoveMethod) -> Op
}
Err(e) => {
show_error!(
"{}: Couldn't rename to {}: {}",
"{}: Couldn't rename to {}: {e}",
last_path.maybe_quote(),
new_path.quote(),
e
);
// TODO: replace with our error management
std::process::exit(1);

View file

@ -171,7 +171,7 @@ fn format_disorder(file: &OsString, line_number: &usize, line: &String, silent:
if *silent {
String::new()
} else {
format!("{}:{}: disorder: {}", file.maybe_quote(), line_number, line)
format!("{}:{}: disorder: {line}", file.maybe_quote(), line_number)
}
}
@ -711,11 +711,7 @@ impl KeyPosition {
Ok(f) => f,
Err(e) if *e.kind() == IntErrorKind::PosOverflow => usize::MAX,
Err(e) => {
return Err(format!(
"failed to parse field index {} {}",
field.quote(),
e
));
return Err(format!("failed to parse field index {} {e}", field.quote(),));
}
};
if field == 0 {
@ -724,7 +720,7 @@ impl KeyPosition {
let char = char.map_or(Ok(default_char_index), |char| {
char.parse()
.map_err(|e| format!("failed to parse character index {}: {}", char.quote(), e))
.map_err(|e| format!("failed to parse character index {}: {e}", char.quote()))
})?;
Ok(Self {
@ -1150,7 +1146,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
match n_merge.parse::<usize>() {
Ok(parsed_value) => {
if parsed_value < 2 {
show_error!("invalid --batch-size argument '{}'", n_merge);
show_error!("invalid --batch-size argument '{n_merge}'");
return Err(UUsageError::new(2, "minimum --batch-size argument is '2'"));
}
settings.merge_batch_size = parsed_value;
@ -1889,15 +1885,15 @@ fn open(path: impl AsRef<OsStr>) -> UResult<Box<dyn Read + Send>> {
fn format_error_message(error: &ParseSizeError, s: &str, option: &str) -> String {
// NOTE:
// GNU's sort echos affected flag, -S or --buffer-size, depending user's selection
// GNU's sort echos affected flag, -S or --buffer-size, depending on user's selection
match error {
ParseSizeError::InvalidSuffix(_) => {
format!("invalid suffix in --{} argument {}", option, s.quote())
format!("invalid suffix in --{option} argument {}", s.quote())
}
ParseSizeError::ParseFailure(_) | ParseSizeError::PhysicalMem(_) => {
format!("invalid --{} argument {}", option, s.quote())
format!("invalid --{option} argument {}", s.quote())
}
ParseSizeError::SizeTooBig(_) => format!("--{} argument {} too large", option, s.quote()),
ParseSizeError::SizeTooBig(_) => format!("--{option} argument {} too large", s.quote()),
}
}

View file

@ -58,7 +58,7 @@ impl TmpDirWrapper {
// and the program doesn't terminate before the handler has finished
let _lock = lock.lock().unwrap();
if let Err(e) = remove_tmp_dir(&path) {
show_error!("failed to delete temporary directory: {}", e);
show_error!("failed to delete temporary directory: {e}");
}
std::process::exit(2)
})

View file

@ -1165,7 +1165,7 @@ where
Err(error) => {
return Err(USimpleError::new(
1,
format!("{}: cannot read from input : {}", settings.input, error),
format!("{}: cannot read from input : {error}", settings.input),
));
}
}

View file

@ -674,7 +674,7 @@ impl Stater {
if let Some(&next_char) = chars.get(*i + 1) {
if (chars[*i] == 'H' || chars[*i] == 'L') && (next_char == 'd' || next_char == 'r')
{
let specifier = format!("{}{}", chars[*i], next_char);
let specifier = format!("{}{next_char}", chars[*i]);
*i += 1;
return Ok(Token::Directive {
flag,
@ -747,7 +747,7 @@ impl Stater {
}
}
other => {
show_warning!("unrecognized escape '\\{}'", other);
show_warning!("unrecognized escape '\\{other}'");
Token::Byte(other as u8)
}
}
@ -1039,9 +1039,8 @@ impl Stater {
}
Err(e) => {
show_error!(
"cannot read file system information for {}: {}",
"cannot read file system information for {}: {e}",
display_name.quote(),
e
);
return 1;
}
@ -1077,7 +1076,7 @@ impl Stater {
}
}
Err(e) => {
show_error!("cannot stat {}: {}", display_name.quote(), e);
show_error!("cannot stat {}: {e}", display_name.quote());
return 1;
}
}

View file

@ -54,11 +54,9 @@ fn set_buffer(stream: *mut FILE, value: &str) {
res = libc::setvbuf(stream, buffer, mode, size);
}
if res != 0 {
eprintln!(
"could not set buffering of {} to mode {}",
unsafe { fileno(stream) },
mode
);
eprintln!("could not set buffering of {} to mode {mode}", unsafe {
fileno(stream)
},);
}
}

View file

@ -279,7 +279,7 @@ impl Settings {
Err(e) => {
return Err(USimpleError::new(
1,
format!("invalid PID: {}: {}", pid_str.quote(), e),
format!("invalid PID: {}: {e}", pid_str.quote()),
));
}
}

View file

@ -345,7 +345,7 @@ impl Observer {
show_error!( "{} has been replaced; following new file", display_name.quote());
self.files.update_reader(event_path)?;
} else if old_md.got_truncated(&new_md)? {
show_error!("{}: file truncated", display_name);
show_error!("{display_name}: file truncated");
self.files.update_reader(event_path)?;
}
paths.push(event_path.clone());
@ -410,7 +410,7 @@ impl Observer {
let _ = self.watcher_rx.as_mut().unwrap().unwatch(event_path);
}
} else {
show_error!("{}: {}", display_name, text::NO_SUCH_FILE);
show_error!("{display_name}: {}", text::NO_SUCH_FILE);
if !self.files.files_remaining() && self.use_polling {
// NOTE: GNU's tail exits here for `---disable-inotify`
return Err(USimpleError::new(1, text::NO_FILES_REMAINING));

View file

@ -128,9 +128,8 @@ impl HeaderPrinter {
pub fn print(&mut self, string: &str) {
if self.verbose {
println!(
"{}==> {} <==",
"{}==> {string} <==",
if self.first_header { "" } else { "\n" },
string,
);
self.first_header = false;
}

View file

@ -123,7 +123,7 @@ fn tail_file(
header_printer.print_input(input);
let err_msg = "Is a directory".to_string();
show_error!("error reading '{}': {}", input.display_name, err_msg);
show_error!("error reading '{}': {err_msg}", input.display_name);
if settings.follow.is_some() {
let msg = if settings.retry {
""
@ -131,9 +131,8 @@ fn tail_file(
"; giving up on this name"
};
show_error!(
"{}: cannot follow end of this type of file{}",
"{}: cannot follow end of this type of file{msg}",
input.display_name,
msg
);
}
if !observer.follow_name_retry() {

View file

@ -233,7 +233,7 @@ fn open(
name: name.to_owned(),
})),
Err(f) => {
show_error!("{}: {}", name.maybe_quote(), f);
show_error!("{}: {f}", name.maybe_quote());
match output_error {
Some(OutputErrorMode::Exit | OutputErrorMode::ExitNoPipe) => Some(Err(f)),
_ => None,
@ -270,26 +270,26 @@ fn process_error(
) -> Result<()> {
match mode {
Some(OutputErrorMode::Warn) => {
show_error!("{}: {}", writer.name.maybe_quote(), f);
show_error!("{}: {f}", writer.name.maybe_quote());
*ignored_errors += 1;
Ok(())
}
Some(OutputErrorMode::WarnNoPipe) | None => {
if f.kind() != ErrorKind::BrokenPipe {
show_error!("{}: {}", writer.name.maybe_quote(), f);
show_error!("{}: {f}", writer.name.maybe_quote());
*ignored_errors += 1;
}
Ok(())
}
Some(OutputErrorMode::Exit) => {
show_error!("{}: {}", writer.name.maybe_quote(), f);
show_error!("{}: {f}", writer.name.maybe_quote());
Err(f)
}
Some(OutputErrorMode::ExitNoPipe) => {
if f.kind() == ErrorKind::BrokenPipe {
Ok(())
} else {
show_error!("{}: {}", writer.name.maybe_quote(), f);
show_error!("{}: {f}", writer.name.maybe_quote());
Err(f)
}
}
@ -378,7 +378,7 @@ impl Read for NamedReader {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
match self.inner.read(buf) {
Err(f) => {
show_error!("stdin: {}", f);
show_error!("stdin: {f}");
Err(f)
}
okay => okay,

View file

@ -196,7 +196,7 @@ fn unblock_sigchld() {
fn report_if_verbose(signal: usize, cmd: &str, verbose: bool) {
if verbose {
let s = signal_name_by_value(signal).unwrap();
show_error!("sending signal {} to command {}", s, cmd.quote());
show_error!("sending signal {s} to command {}", cmd.quote());
}
}

View file

@ -675,8 +675,8 @@ fn parse_timestamp(s: &str) -> UResult<FileTime> {
// If we don't add "19" or "20", we have insufficient information to parse
13 => (YYYYMMDDHHMM_DOT_SS, prepend_century(s)?),
10 => (YYYYMMDDHHMM, prepend_century(s)?),
11 => (YYYYMMDDHHMM_DOT_SS, format!("{}{}", current_year(), s)),
8 => (YYYYMMDDHHMM, format!("{}{}", current_year(), s)),
11 => (YYYYMMDDHHMM_DOT_SS, format!("{}{s}", current_year())),
8 => (YYYYMMDDHHMM, format!("{}{s}", current_year())),
_ => {
return Err(USimpleError::new(
1,

View file

@ -364,12 +364,7 @@ impl Sequence {
let origin_octal: &str = std::str::from_utf8(input).unwrap();
let actual_octal_tail: &str = std::str::from_utf8(&input[0..2]).unwrap();
let outstand_char: char = char::from_u32(input[2] as u32).unwrap();
show_warning!(
"the ambiguous octal escape \\{} is being\n interpreted as the 2-byte sequence \\0{}, {}",
origin_octal,
actual_octal_tail,
outstand_char
);
show_warning!("the ambiguous octal escape \\{origin_octal} is being\n interpreted as the 2-byte sequence \\0{actual_octal_tail}, {outstand_char}");
}
result
},

View file

@ -29,7 +29,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
if let Err(print_fail) = error {
// Try to display this error.
let _ = writeln!(std::io::stderr(), "{}: {}", uucore::util_name(), print_fail);
let _ = writeln!(std::io::stderr(), "{}: {print_fail}", uucore::util_name());
// Mirror GNU options. When failing to print warnings or version flags, then we exit
// with FAIL. This avoids allocation some error information which may result in yet
// other types of failure.

View file

@ -241,11 +241,7 @@ fn opt_parsed(opt_name: &str, matches: &ArgMatches) -> UResult<Option<usize>> {
IntErrorKind::PosOverflow => Ok(Some(usize::MAX)),
_ => Err(USimpleError::new(
1,
format!(
"Invalid argument for {}: {}",
opt_name,
arg_str.maybe_quote()
),
format!("Invalid argument for {opt_name}: {}", arg_str.maybe_quote()),
)),
},
},

View file

@ -53,8 +53,7 @@
//! .arg(backup_control::arguments::suffix())
//! .override_usage(usage)
//! .after_help(format!(
//! "{}\n{}",
//! long_usage,
//! "{long_usage}\n{}",
//! backup_control::BACKUP_CONTROL_LONG_HELP
//! ))
//! .get_matches_from(vec![
@ -176,17 +175,13 @@ impl Display for BackupError {
match self {
Self::InvalidArgument(arg, origin) => write!(
f,
"invalid argument {} for '{}'\n{}",
"invalid argument {} for '{origin}'\n{VALID_ARGS_HELP}",
arg.quote(),
origin,
VALID_ARGS_HELP
),
Self::AmbiguousArgument(arg, origin) => write!(
f,
"ambiguous argument {} for '{}'\n{}",
"ambiguous argument {} for '{origin}'\n{VALID_ARGS_HELP}",
arg.quote(),
origin,
VALID_ARGS_HELP
),
Self::BackupImpossible() => write!(f, "cannot create backup"),
// Placeholder for later

View file

@ -1053,11 +1053,10 @@ fn process_checksum_file(
Cow::Borrowed("Unknown algorithm")
};
eprintln!(
"{}: {}: {}: improperly formatted {} checksum line",
"{}: {}: {}: improperly formatted {algo} checksum line",
util_name(),
&filename_input.maybe_quote(),
filename_input.maybe_quote(),
i + 1,
algo
);
}
}

View file

@ -294,7 +294,7 @@ macro_rules! f {
// The same applies for the two cases below.
Err(IOError::new(
ErrorKind::NotFound,
format!("No such id: {}", k),
format!("No such id: {k}"),
))
}
}
@ -313,7 +313,7 @@ macro_rules! f {
} else {
Err(IOError::new(
ErrorKind::NotFound,
format!("No such id: {}", id),
format!("No such id: {id}"),
))
}
}
@ -325,10 +325,7 @@ macro_rules! f {
if !data.is_null() {
Ok($st::from_raw(ptr::read(data as *const _)))
} else {
Err(IOError::new(
ErrorKind::NotFound,
format!("Not found: {}", k),
))
Err(IOError::new(ErrorKind::NotFound, format!("Not found: {k}")))
}
}
}

View file

@ -121,8 +121,7 @@ fn extract_value<T: Default>(p: Result<T, ExtendedParserError<'_, T>>, input: &s
let bytes = input.as_encoded_bytes();
if !bytes.is_empty() && (bytes[0] == b'\'' || bytes[0] == b'"') {
show_warning!(
"{}: character(s) following character constant have been ignored",
&rest,
"{rest}: character(s) following character constant have been ignored"
);
} else {
show_error!("{}: value not completely converted", input.quote());

View file

@ -34,9 +34,9 @@ fn format_prefixed(prefixed: &NumberPrefix<f64>) -> String {
// Check whether we get more than 10 if we round up to the first decimal
// because we want do display 9.81 as "9.9", not as "10".
if (10.0 * bytes).ceil() >= 100.0 {
format!("{:.0}{}", bytes.ceil(), prefix_str)
format!("{:.0}{prefix_str}", bytes.ceil())
} else {
format!("{:.1}{}", (10.0 * bytes).ceil() / 10.0, prefix_str)
format!("{:.1}{prefix_str}", (10.0 * bytes).ceil() / 10.0)
}
}
}

View file

@ -83,7 +83,7 @@ impl Formatter<i64> for SignedInt {
// -i64::MIN is actually 1 larger than i64::MAX, so we need to cast to i128 first.
let abs = (x as i128).abs();
let s = if self.precision > 0 {
format!("{:0>width$}", abs, width = self.precision)
format!("{abs:0>width$}", width = self.precision)
} else {
abs.to_string()
};

View file

@ -460,14 +460,14 @@ pub fn read_fs_list() -> UResult<Vec<MountInfo>> {
unsafe { FindFirstVolumeW(volume_name_buf.as_mut_ptr(), volume_name_buf.len() as u32) };
if INVALID_HANDLE_VALUE == find_handle {
let os_err = IOError::last_os_error();
let msg = format!("FindFirstVolumeW failed: {}", os_err);
let msg = format!("FindFirstVolumeW failed: {os_err}");
return Err(USimpleError::new(EXIT_ERR, msg));
}
let mut mounts = Vec::<MountInfo>::new();
loop {
let volume_name = LPWSTR2String(&volume_name_buf);
if !volume_name.starts_with("\\\\?\\") || !volume_name.ends_with('\\') {
show_warning!("A bad path was skipped: {}", volume_name);
show_warning!("A bad path was skipped: {volume_name}");
continue;
}
if let Some(m) = MountInfo::new(volume_name) {

View file

@ -80,21 +80,19 @@ pub fn wrap_chown<P: AsRef<Path>>(
VerbosityLevel::Silent => (),
level => {
out = format!(
"changing {} of {}: {}",
"changing {} of {}: {e}",
if verbosity.groups_only {
"group"
} else {
"ownership"
},
path.quote(),
e
);
if level == VerbosityLevel::Verbose {
out = if verbosity.groups_only {
let gid = meta.gid();
format!(
"{}\nfailed to change group of {} from {} to {}",
out,
"{out}\nfailed to change group of {} from {} to {}",
path.quote(),
entries::gid2grp(gid).unwrap_or_else(|_| gid.to_string()),
entries::gid2grp(dest_gid).unwrap_or_else(|_| dest_gid.to_string())
@ -103,8 +101,7 @@ pub fn wrap_chown<P: AsRef<Path>>(
let uid = meta.uid();
let gid = meta.gid();
format!(
"{}\nfailed to change ownership of {} from {}:{} to {}:{}",
out,
"{out}\nfailed to change ownership of {} from {}:{} to {}:{}",
path.quote(),
entries::uid2usr(uid).unwrap_or_else(|_| uid.to_string()),
entries::gid2grp(gid).unwrap_or_else(|_| gid.to_string()),
@ -303,13 +300,13 @@ impl ChownExecutor {
) {
Ok(n) => {
if !n.is_empty() {
show_error!("{}", n);
show_error!("{n}");
}
0
}
Err(e) => {
if self.verbosity.level != VerbosityLevel::Silent {
show_error!("{}", e);
show_error!("{e}");
}
1
}
@ -360,7 +357,7 @@ impl ChownExecutor {
}
);
} else {
show_error!("{}", e);
show_error!("{e}");
}
continue;
}
@ -403,13 +400,13 @@ impl ChownExecutor {
) {
Ok(n) => {
if !n.is_empty() {
show_error!("{}", n);
show_error!("{n}");
}
0
}
Err(e) => {
if self.verbosity.level != VerbosityLevel::Silent {
show_error!("{}", e);
show_error!("{e}");
}
1
}
@ -458,9 +455,9 @@ impl ChownExecutor {
_ => entries::uid2usr(uid).unwrap_or_else(|_| uid.to_string()),
};
if self.verbosity.groups_only {
println!("group of {} retained as {}", path.quote(), ownership);
println!("group of {} retained as {ownership}", path.quote());
} else {
println!("ownership of {} retained as {}", path.quote(), ownership);
println!("ownership of {} retained as {ownership}", path.quote());
}
}
}

View file

@ -258,7 +258,7 @@ impl ProcessInformation {
fn get_uid_or_gid_field(&mut self, field: UidGid, index: usize) -> Result<u32, io::Error> {
self.status()
.get(&format!("{:?}", field))
.get(&format!("{field:?}"))
.ok_or(io::ErrorKind::InvalidData)?
.split_whitespace()
.nth(index)
@ -451,11 +451,11 @@ mod tests {
let current_pid = current_pid();
let pid_entry = ProcessInformation::try_new(
PathBuf::from_str(&format!("/proc/{}", current_pid)).unwrap(),
PathBuf::from_str(&format!("/proc/{current_pid}")).unwrap(),
)
.unwrap();
let result = WalkDir::new(format!("/proc/{}/fd", current_pid))
let result = WalkDir::new(format!("/proc/{current_pid}/fd"))
.into_iter()
.flatten()
.map(DirEntry::into_path)

View file

@ -84,7 +84,7 @@ impl Range {
for item in list.split(&[',', ' ']) {
let range_item = FromStr::from_str(item)
.map_err(|e| format!("range {} was invalid: {}", item.quote(), e))?;
.map_err(|e| format!("range {} was invalid: {e}", item.quote()))?;
ranges.push(range_item);
}

View file

@ -20,9 +20,9 @@ pub enum Teletype {
impl Display for Teletype {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::Tty(id) => write!(f, "/dev/pts/{}", id),
Self::TtyS(id) => write!(f, "/dev/tty{}", id),
Self::Pts(id) => write!(f, "/dev/ttyS{}", id),
Self::Tty(id) => write!(f, "/dev/pts/{id}"),
Self::TtyS(id) => write!(f, "/dev/tty{id}"),
Self::Pts(id) => write!(f, "/dev/ttyS{id}"),
Self::Unknown => write!(f, "?"),
}
}

View file

@ -154,7 +154,7 @@ macro_rules! bin {
let code = $util::uumain(uucore::args_os());
// (defensively) flush stdout for utility prior to exit; see <https://github.com/rust-lang/rust/issues/23818>
if let Err(e) = std::io::stdout().flush() {
eprintln!("Error flushing stdout: {}", e);
eprintln!("Error flushing stdout: {e}");
}
std::process::exit(code);
@ -383,7 +383,7 @@ pub fn read_os_string_lines<R: std::io::Read>(
/// ```
/// use uucore::prompt_yes;
/// let file = "foo.rs";
/// prompt_yes!("Do you want to delete '{}'?", file);
/// prompt_yes!("Do you want to delete '{file}'?");
/// ```
/// will print something like below to `stderr` (with `util_name` substituted by the actual
/// util name) and will wait for user input.

View file

@ -91,7 +91,7 @@ macro_rules! show(
use $crate::error::UError;
let e = $err;
$crate::error::set_exit_code(e.code());
eprintln!("{}: {}", $crate::util_name(), e);
eprintln!("{}: {e}", $crate::util_name());
})
);

View file

@ -595,9 +595,9 @@ impl From<nix::Error> for Box<dyn UError> {
/// let other_uio_err = uio_error!(io_err, "Error code: {}", 2);
///
/// // prints "fix me please!: Permission denied"
/// println!("{}", uio_err);
/// println!("{uio_err}");
/// // prints "Error code: 2: Permission denied"
/// println!("{}", other_uio_err);
/// println!("{other_uio_err}");
/// ```
///
/// The [`std::fmt::Display`] impl of [`UIoError`] will then ensure that an
@ -619,7 +619,7 @@ impl From<nix::Error> for Box<dyn UError> {
/// let other_uio_err = uio_error!(io_err, "");
///
/// // prints: ": Permission denied"
/// println!("{}", other_uio_err);
/// println!("{other_uio_err}");
/// ```
//#[macro_use]
#[macro_export]

View file

@ -33,9 +33,9 @@ pub fn main(_args: TokenStream, stream: TokenStream) -> TokenStream {
match result {
Ok(()) => uucore::error::get_exit_code(),
Err(e) => {
let s = format!("{}", e);
let s = format!("{e}");
if s != "" {
uucore::show_error!("{}", s);
uucore::show_error!("{s}");
}
if e.usage() {
eprintln!("Try '{} --help' for more information.", uucore::execution_phrase());