From f6b646e4e5aebb89defc24f8202ee41b947199ad Mon Sep 17 00:00:00 2001 From: Daniel Hofstetter Date: Fri, 27 Jan 2023 10:29:45 +0100 Subject: [PATCH] clippy: fix warnings introduced with Rust 1.67.0 --- src/uu/cat/src/cat.rs | 2 +- src/uu/chcon/src/chcon.rs | 2 +- src/uu/chcon/src/errors.rs | 4 +- src/uu/chmod/src/chmod.rs | 2 +- src/uu/chroot/src/error.rs | 4 +- src/uu/cksum/src/cksum.rs | 4 +- src/uu/cp/src/copydir.rs | 2 +- src/uu/cp/src/cp.rs | 7 +- src/uu/cp/src/platform/macos.rs | 4 +- src/uu/csplit/src/csplit.rs | 28 ++--- src/uu/csplit/src/patterns.rs | 20 ++-- src/uu/csplit/src/split_name.rs | 34 +++--- src/uu/date/src/date.rs | 6 +- src/uu/dd/src/dd.rs | 4 +- src/uu/dd/src/numbers.rs | 2 +- src/uu/dd/src/parseargs.rs | 17 ++- src/uu/dd/src/parseargs/unit_tests.rs | 11 +- src/uu/dd/src/progress.rs | 25 +--- src/uu/df/src/blocks.rs | 6 +- src/uu/df/src/df.rs | 4 +- src/uu/df/src/table.rs | 2 +- src/uu/dircolors/src/dircolors.rs | 16 +-- src/uu/dirname/src/dirname.rs | 2 +- src/uu/du/src/du.rs | 10 +- src/uu/echo/src/echo.rs | 4 +- src/uu/env/src/env.rs | 2 +- src/uu/expand/src/expand.rs | 2 +- src/uu/expr/src/expr.rs | 2 +- src/uu/expr/src/syntax_tree.rs | 22 ++-- src/uu/expr/src/tokens.rs | 2 +- src/uu/factor/build.rs | 9 +- src/uu/factor/src/factor.rs | 2 +- src/uu/factor/src/miller_rabin.rs | 7 +- src/uu/factor/src/numeric/gcd.rs | 4 +- src/uu/factor/src/numeric/modular_inverse.rs | 2 +- src/uu/factor/src/numeric/montgomery.rs | 2 +- src/uu/fmt/src/linebreak.rs | 2 +- src/uu/fold/src/fold.rs | 6 +- src/uu/groups/src/groups.rs | 2 +- src/uu/hashsum/src/hashsum.rs | 13 +-- src/uu/head/src/head.rs | 14 +-- src/uu/head/src/parse.rs | 4 +- src/uu/hostid/src/hostid.rs | 2 +- src/uu/hostname/src/hostname.rs | 2 +- src/uu/id/src/id.rs | 10 +- src/uu/install/src/install.rs | 4 +- src/uu/join/src/join.rs | 4 +- src/uu/kill/src/kill.rs | 10 +- src/uu/ln/src/ln.rs | 2 +- src/uu/logname/src/logname.rs | 2 +- src/uu/ls/src/ls.rs | 18 +-- src/uu/mkdir/src/mkdir.rs | 2 +- src/uu/mkfifo/src/mkfifo.rs | 2 +- src/uu/mknod/src/mknod.rs | 2 +- src/uu/mktemp/src/mktemp.rs | 2 +- src/uu/more/src/more.rs | 13 +-- src/uu/mv/src/error.rs | 19 ++- src/uu/mv/src/mv.rs | 11 +- src/uu/nice/src/nice.rs | 4 +- src/uu/nl/src/nl.rs | 2 +- src/uu/nohup/src/nohup.rs | 2 +- src/uu/nproc/src/nproc.rs | 2 +- src/uu/numfmt/src/errors.rs | 2 +- src/uu/numfmt/src/format.rs | 18 ++- src/uu/numfmt/src/numfmt.rs | 10 +- src/uu/numfmt/src/options.rs | 18 ++- src/uu/od/src/formatteriteminfo.rs | 6 +- src/uu/od/src/inputdecoder.rs | 4 +- src/uu/od/src/inputoffset.rs | 2 +- src/uu/od/src/od.rs | 12 +- src/uu/od/src/prn_char.rs | 18 +-- src/uu/od/src/prn_float.rs | 8 +- src/uu/pathchk/src/pathchk.rs | 7 +- src/uu/pinky/src/pinky.rs | 16 +-- src/uu/pr/src/pr.rs | 9 +- src/uu/printenv/src/printenv.rs | 4 +- src/uu/ptx/src/ptx.rs | 10 +- src/uu/readlink/src/readlink.rs | 6 +- src/uu/rm/src/rm.rs | 2 +- src/uu/runcon/src/errors.rs | 4 +- src/uu/runcon/src/runcon.rs | 6 +- src/uu/seq/src/seq.rs | 20 ++-- src/uu/shred/src/shred.rs | 5 +- src/uu/shuf/src/rand_read_adapter.rs | 5 +- src/uu/shuf/src/shuf.rs | 2 +- src/uu/sort/src/ext_sort.rs | 2 +- src/uu/sort/src/sort.rs | 15 +-- src/uu/sort/src/tmp_dir.rs | 2 +- src/uu/split/src/number.rs | 2 +- src/uu/split/src/platform/unix.rs | 2 +- src/uu/split/src/platform/windows.rs | 2 +- src/uu/split/src/split.rs | 25 ++-- src/uu/stat/src/stat.rs | 6 +- src/uu/stdbuf/src/stdbuf.rs | 3 +- src/uu/stty/src/stty.rs | 12 +- src/uu/sum/src/sum.rs | 4 +- src/uu/tac/src/error.rs | 6 +- src/uu/tail/src/args.rs | 14 +-- src/uu/tail/src/chunks.rs | 2 +- src/uu/tail/src/follow/watch.rs | 4 +- src/uu/tail/src/parse.rs | 4 +- src/uu/tail/src/paths.rs | 2 +- src/uu/tail/src/tail.rs | 2 +- src/uu/test/src/parser.rs | 4 +- src/uu/test/src/test.rs | 2 +- src/uu/timeout/src/timeout.rs | 10 +- src/uu/touch/src/touch.rs | 6 +- src/uu/tr/src/operation.rs | 2 +- src/uu/truncate/src/truncate.rs | 4 +- src/uu/tsort/src/tsort.rs | 4 +- src/uu/unexpand/src/unexpand.rs | 2 +- src/uu/uniq/src/uniq.rs | 4 +- src/uu/uptime/src/uptime.rs | 8 +- src/uu/wc/src/wc.rs | 4 +- src/uu/who/src/who.rs | 18 +-- src/uu/yes/src/yes.rs | 2 +- src/uucore/src/lib/features/encoding.rs | 2 +- src/uucore/src/lib/features/fs.rs | 4 +- src/uucore/src/lib/features/fsext.rs | 6 +- src/uucore/src/lib/features/memo.rs | 2 +- src/uucore/src/lib/features/mode.rs | 7 +- src/uucore/src/lib/features/signals.rs | 2 +- .../formatters/cninetyninehexfloatf.rs | 4 +- .../num_format/formatters/float_common.rs | 4 +- .../tokenize/num_format/formatters/intf.rs | 10 +- .../tokenize/num_format/num_format.rs | 10 +- src/uucore/src/lib/features/tokenize/sub.rs | 2 +- .../lib/features/tokenize/unescaped_text.rs | 7 +- src/uucore/src/lib/features/utmpx.rs | 2 +- src/uucore/src/lib/mods/error.rs | 4 +- src/uucore/src/lib/mods/quoting_style.rs | 8 +- src/uucore/src/lib/parser/parse_size.rs | 26 ++--- src/uucore_procs/src/lib.rs | 9 +- tests/by-util/test_chgrp.rs | 2 +- tests/by-util/test_chmod.rs | 13 +-- tests/by-util/test_chown.rs | 24 ++-- tests/by-util/test_chroot.rs | 7 +- tests/by-util/test_cp.rs | 60 +++++----- tests/by-util/test_csplit.rs | 2 +- tests/by-util/test_date.rs | 8 +- tests/by-util/test_dd.rs | 24 ++-- tests/by-util/test_df.rs | 6 +- tests/by-util/test_dircolors.rs | 8 +- tests/by-util/test_du.rs | 16 +-- tests/by-util/test_echo.rs | 2 +- tests/by-util/test_factor.rs | 26 ++--- tests/by-util/test_install.rs | 110 +++++++++--------- tests/by-util/test_ln.rs | 38 +++--- tests/by-util/test_logname.rs | 2 +- tests/by-util/test_ls.rs | 58 +++++---- tests/by-util/test_mktemp.rs | 7 +- tests/by-util/test_mv.rs | 94 +++++++-------- tests/by-util/test_numfmt.rs | 55 ++++----- tests/by-util/test_od.rs | 21 ++-- tests/by-util/test_paste.rs | 2 +- tests/by-util/test_pinky.rs | 6 +- tests/by-util/test_readlink.rs | 42 +++---- tests/by-util/test_realpath.rs | 4 +- tests/by-util/test_relpath.rs | 10 +- tests/by-util/test_rm.rs | 30 +++-- tests/by-util/test_rmdir.rs | 19 +-- tests/by-util/test_sort.rs | 16 +-- tests/by-util/test_split.rs | 4 +- tests/by-util/test_stat.rs | 12 +- tests/by-util/test_tail.rs | 74 +++++------- tests/by-util/test_tee.rs | 10 +- tests/by-util/test_touch.rs | 7 +- tests/by-util/test_truncate.rs | 108 ++++------------- tests/by-util/test_wc.rs | 2 +- tests/by-util/test_who.rs | 8 +- tests/by-util/test_whoami.rs | 2 +- tests/common/util.rs | 14 +-- 172 files changed, 835 insertions(+), 1034 deletions(-) diff --git a/src/uu/cat/src/cat.rs b/src/uu/cat/src/cat.rs index d29ed3c30..35ef5abc1 100644 --- a/src/uu/cat/src/cat.rs +++ b/src/uu/cat/src/cat.rs @@ -424,7 +424,7 @@ fn get_input_type(path: &str) -> CatResult { ft if ft.is_file() => Ok(InputType::File), ft if ft.is_symlink() => Ok(InputType::SymLink), _ => Err(CatError::UnknownFiletype { - ft_debug: format!("{:?}", ft), + ft_debug: format!("{ft:?}"), }), } } diff --git a/src/uu/chcon/src/chcon.rs b/src/uu/chcon/src/chcon.rs index 2abf8d40a..3acd2ea43 100644 --- a/src/uu/chcon/src/chcon.rs +++ b/src/uu/chcon/src/chcon.rs @@ -70,7 +70,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { return Err(r.into()); } - return Err(UUsageError::new(libc::EXIT_FAILURE, format!("{}.\n", r))); + return Err(UUsageError::new(libc::EXIT_FAILURE, format!("{r}.\n"))); } }; diff --git a/src/uu/chcon/src/errors.rs b/src/uu/chcon/src/errors.rs index 1082dc601..0bd61ec4a 100644 --- a/src/uu/chcon/src/errors.rs +++ b/src/uu/chcon/src/errors.rs @@ -67,10 +67,10 @@ impl Error { pub(crate) fn report_full_error(mut err: &dyn std::error::Error) -> String { let mut desc = String::with_capacity(256); - write!(desc, "{}", err).unwrap(); + write!(desc, "{err}").unwrap(); while let Some(source) = err.source() { err = source; - write!(desc, ". {}", err).unwrap(); + write!(desc, ". {err}").unwrap(); } desc } diff --git a/src/uu/chmod/src/chmod.rs b/src/uu/chmod/src/chmod.rs index c21705ccd..4d578eeba 100644 --- a/src/uu/chmod/src/chmod.rs +++ b/src/uu/chmod/src/chmod.rs @@ -75,7 +75,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let modes = matches.get_one::(options::MODE).unwrap(); // should always be Some because required let cmode = if mode_had_minus_prefix { // clap parsing is finished, now put prefix back - format!("-{}", modes) + format!("-{modes}") } else { modes.to_string() }; diff --git a/src/uu/chroot/src/error.rs b/src/uu/chroot/src/error.rs index 059715de1..43ef98595 100644 --- a/src/uu/chroot/src/error.rs +++ b/src/uu/chroot/src/error.rs @@ -77,8 +77,8 @@ impl Display for ChrootError { "cannot change root directory to {}: no such directory", s.quote(), ), - Self::SetGidFailed(s, e) => write!(f, "cannot set gid to {}: {}", s, e), - Self::SetGroupsFailed(e) => write!(f, "cannot set groups: {}", e), + Self::SetGidFailed(s, e) => write!(f, "cannot set gid to {s}: {e}"), + Self::SetGroupsFailed(e) => write!(f, "cannot set groups: {e}"), Self::SetUserFailed(s, e) => { write!(f, "cannot set user to {}: {}", s.maybe_quote(), e) } diff --git a/src/uu/cksum/src/cksum.rs b/src/uu/cksum/src/cksum.rs index fc7f901c9..f567d8bf8 100644 --- a/src/uu/cksum/src/cksum.rs +++ b/src/uu/cksum/src/cksum.rs @@ -123,13 +123,13 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { if files.is_empty() { let (crc, size) = cksum("-")?; - println!("{} {}", crc, size); + println!("{crc} {size}"); return Ok(()); } for fname in &files { match cksum(fname.as_ref()).map_err_context(|| format!("{}", fname.maybe_quote())) { - Ok((crc, size)) => println!("{} {} {}", crc, size, fname), + Ok((crc, size)) => println!("{crc} {size} {fname}"), Err(err) => show!(err), }; } diff --git a/src/uu/cp/src/copydir.rs b/src/uu/cp/src/copydir.rs index 2af1bdb7c..a89bd8537 100644 --- a/src/uu/cp/src/copydir.rs +++ b/src/uu/cp/src/copydir.rs @@ -380,7 +380,7 @@ pub(crate) fn copy_directory( // the target directory. let context = match Context::new(root, target) { Ok(c) => c, - Err(e) => return Err(format!("failed to get current directory {}", e).into()), + Err(e) => return Err(format!("failed to get current directory {e}").into()), }; // Traverse the contents of the directory, copying each one. diff --git a/src/uu/cp/src/cp.rs b/src/uu/cp/src/cp.rs index 96227cec2..d9029810d 100644 --- a/src/uu/cp/src/cp.rs +++ b/src/uu/cp/src/cp.rs @@ -746,7 +746,7 @@ impl Options { let recursive = matches.get_flag(options::RECURSIVE) || matches.get_flag(options::ARCHIVE); let backup_mode = match backup_control::determine_backup_mode(matches) { - Err(e) => return Err(Error::Backup(format!("{}", e))), + Err(e) => return Err(Error::Backup(format!("{e}"))), Ok(mode) => mode, }; @@ -865,8 +865,7 @@ impl Options { "never" => SparseMode::Never, _ => { return Err(Error::InvalidArgument(format!( - "invalid argument {} for \'sparse\'", - val + "invalid argument {val} for \'sparse\'" ))); } } @@ -1857,7 +1856,7 @@ mod tests { #[test] fn test_aligned_ancestors() { - let actual = aligned_ancestors(&Path::new("a/b/c"), &Path::new("d/a/b/c")); + let actual = aligned_ancestors(Path::new("a/b/c"), Path::new("d/a/b/c")); let expected = vec![ (Path::new("a"), Path::new("d/a")), (Path::new("a/b"), Path::new("d/a/b")), diff --git a/src/uu/cp/src/platform/macos.rs b/src/uu/cp/src/platform/macos.rs index 0aecc1466..4407e0edf 100644 --- a/src/uu/cp/src/platform/macos.rs +++ b/src/uu/cp/src/platform/macos.rs @@ -69,9 +69,7 @@ pub(crate) fn copy_on_write( // support COW). match reflink_mode { ReflinkMode::Always => { - return Err( - format!("failed to clone {:?} from {:?}: {}", source, dest, error).into(), - ) + return Err(format!("failed to clone {source:?} from {dest:?}: {error}").into()) } _ => { if source_is_fifo { diff --git a/src/uu/csplit/src/csplit.rs b/src/uu/csplit/src/csplit.rs index bfe2f9512..5e3849687 100644 --- a/src/uu/csplit/src/csplit.rs +++ b/src/uu/csplit/src/csplit.rs @@ -574,7 +574,7 @@ mod tests { assert_eq!(input_splitter.add_line_to_buffer(0, line), None); assert_eq!(input_splitter.buffer_len(), 1); } - item => panic!("wrong item: {:?}", item), + item => panic!("wrong item: {item:?}"), }; match input_splitter.next() { @@ -583,7 +583,7 @@ mod tests { assert_eq!(input_splitter.add_line_to_buffer(1, line), None); assert_eq!(input_splitter.buffer_len(), 2); } - item => panic!("wrong item: {:?}", item), + item => panic!("wrong item: {item:?}"), }; match input_splitter.next() { @@ -595,7 +595,7 @@ mod tests { ); assert_eq!(input_splitter.buffer_len(), 2); } - item => panic!("wrong item: {:?}", item), + item => panic!("wrong item: {item:?}"), }; input_splitter.rewind_buffer(); @@ -605,7 +605,7 @@ mod tests { assert_eq!(line, String::from("bbb")); assert_eq!(input_splitter.buffer_len(), 1); } - item => panic!("wrong item: {:?}", item), + item => panic!("wrong item: {item:?}"), }; match input_splitter.next() { @@ -613,7 +613,7 @@ mod tests { assert_eq!(line, String::from("ccc")); assert_eq!(input_splitter.buffer_len(), 0); } - item => panic!("wrong item: {:?}", item), + item => panic!("wrong item: {item:?}"), }; match input_splitter.next() { @@ -621,7 +621,7 @@ mod tests { assert_eq!(line, String::from("ddd")); assert_eq!(input_splitter.buffer_len(), 0); } - item => panic!("wrong item: {:?}", item), + item => panic!("wrong item: {item:?}"), }; assert!(input_splitter.next().is_none()); @@ -646,7 +646,7 @@ mod tests { assert_eq!(input_splitter.add_line_to_buffer(0, line), None); assert_eq!(input_splitter.buffer_len(), 1); } - item => panic!("wrong item: {:?}", item), + item => panic!("wrong item: {item:?}"), }; match input_splitter.next() { @@ -655,7 +655,7 @@ mod tests { assert_eq!(input_splitter.add_line_to_buffer(1, line), None); assert_eq!(input_splitter.buffer_len(), 2); } - item => panic!("wrong item: {:?}", item), + item => panic!("wrong item: {item:?}"), }; match input_splitter.next() { @@ -664,7 +664,7 @@ mod tests { assert_eq!(input_splitter.add_line_to_buffer(2, line), None); assert_eq!(input_splitter.buffer_len(), 3); } - item => panic!("wrong item: {:?}", item), + item => panic!("wrong item: {item:?}"), }; input_splitter.rewind_buffer(); @@ -675,7 +675,7 @@ mod tests { assert_eq!(input_splitter.add_line_to_buffer(0, line), None); assert_eq!(input_splitter.buffer_len(), 3); } - item => panic!("wrong item: {:?}", item), + item => panic!("wrong item: {item:?}"), }; match input_splitter.next() { @@ -683,7 +683,7 @@ mod tests { assert_eq!(line, String::from("aaa")); assert_eq!(input_splitter.buffer_len(), 2); } - item => panic!("wrong item: {:?}", item), + item => panic!("wrong item: {item:?}"), }; match input_splitter.next() { @@ -691,7 +691,7 @@ mod tests { assert_eq!(line, String::from("bbb")); assert_eq!(input_splitter.buffer_len(), 1); } - item => panic!("wrong item: {:?}", item), + item => panic!("wrong item: {item:?}"), }; match input_splitter.next() { @@ -699,7 +699,7 @@ mod tests { assert_eq!(line, String::from("ccc")); assert_eq!(input_splitter.buffer_len(), 0); } - item => panic!("wrong item: {:?}", item), + item => panic!("wrong item: {item:?}"), }; match input_splitter.next() { @@ -707,7 +707,7 @@ mod tests { assert_eq!(line, String::from("ddd")); assert_eq!(input_splitter.buffer_len(), 0); } - item => panic!("wrong item: {:?}", item), + item => panic!("wrong item: {item:?}"), }; assert!(input_splitter.next().is_none()); diff --git a/src/uu/csplit/src/patterns.rs b/src/uu/csplit/src/patterns.rs index 366794963..652b024d8 100644 --- a/src/uu/csplit/src/patterns.rs +++ b/src/uu/csplit/src/patterns.rs @@ -224,35 +224,35 @@ mod tests { assert_eq!(patterns.len(), 5); match patterns.get(0) { Some(Pattern::UpToMatch(reg, 0, ExecutePattern::Times(1))) => { - let parsed_reg = format!("{}", reg); + let parsed_reg = format!("{reg}"); assert_eq!(parsed_reg, "test1.*end$"); } _ => panic!("expected UpToMatch pattern"), }; match patterns.get(1) { Some(Pattern::UpToMatch(reg, 0, ExecutePattern::Always)) => { - let parsed_reg = format!("{}", reg); + let parsed_reg = format!("{reg}"); assert_eq!(parsed_reg, "test2.*end$"); } _ => panic!("expected UpToMatch pattern"), }; match patterns.get(2) { Some(Pattern::UpToMatch(reg, 0, ExecutePattern::Times(5))) => { - let parsed_reg = format!("{}", reg); + let parsed_reg = format!("{reg}"); assert_eq!(parsed_reg, "test3.*end$"); } _ => panic!("expected UpToMatch pattern"), }; match patterns.get(3) { Some(Pattern::UpToMatch(reg, 3, ExecutePattern::Times(1))) => { - let parsed_reg = format!("{}", reg); + let parsed_reg = format!("{reg}"); assert_eq!(parsed_reg, "test4.*end$"); } _ => panic!("expected UpToMatch pattern"), }; match patterns.get(4) { Some(Pattern::UpToMatch(reg, -3, ExecutePattern::Times(1))) => { - let parsed_reg = format!("{}", reg); + let parsed_reg = format!("{reg}"); assert_eq!(parsed_reg, "test5.*end$"); } _ => panic!("expected UpToMatch pattern"), @@ -277,35 +277,35 @@ mod tests { assert_eq!(patterns.len(), 5); match patterns.get(0) { Some(Pattern::SkipToMatch(reg, 0, ExecutePattern::Times(1))) => { - let parsed_reg = format!("{}", reg); + let parsed_reg = format!("{reg}"); assert_eq!(parsed_reg, "test1.*end$"); } _ => panic!("expected SkipToMatch pattern"), }; match patterns.get(1) { Some(Pattern::SkipToMatch(reg, 0, ExecutePattern::Always)) => { - let parsed_reg = format!("{}", reg); + let parsed_reg = format!("{reg}"); assert_eq!(parsed_reg, "test2.*end$"); } _ => panic!("expected SkipToMatch pattern"), }; match patterns.get(2) { Some(Pattern::SkipToMatch(reg, 0, ExecutePattern::Times(5))) => { - let parsed_reg = format!("{}", reg); + let parsed_reg = format!("{reg}"); assert_eq!(parsed_reg, "test3.*end$"); } _ => panic!("expected SkipToMatch pattern"), }; match patterns.get(3) { Some(Pattern::SkipToMatch(reg, 3, ExecutePattern::Times(1))) => { - let parsed_reg = format!("{}", reg); + let parsed_reg = format!("{reg}"); assert_eq!(parsed_reg, "test4.*end$"); } _ => panic!("expected SkipToMatch pattern"), }; match patterns.get(4) { Some(Pattern::SkipToMatch(reg, -3, ExecutePattern::Times(1))) => { - let parsed_reg = format!("{}", reg); + let parsed_reg = format!("{reg}"); assert_eq!(parsed_reg, "test5.*end$"); } _ => panic!("expected SkipToMatch pattern"), diff --git a/src/uu/csplit/src/split_name.rs b/src/uu/csplit/src/split_name.rs index e7776c330..19e3ac9c2 100644 --- a/src/uu/csplit/src/split_name.rs +++ b/src/uu/csplit/src/split_name.rs @@ -42,9 +42,7 @@ impl SplitName { .unwrap_or(2); // translate the custom format into a function let fn_split_name: Box String> = match format_opt { - None => Box::new(move |n: usize| -> String { - format!("{}{:0width$}", prefix, n, width = n_digits) - }), + None => Box::new(move |n: usize| -> String { format!("{prefix}{n:0n_digits$}") }), Some(custom) => { let spec = Regex::new(r"(?P%((?P[0#-])(?P\d+)?)?(?P[diuoxX]))") @@ -62,16 +60,16 @@ impl SplitName { match (captures.name("FLAG"), captures.name("TYPE")) { (None, Some(ref t)) => match t.as_str() { "d" | "i" | "u" => Box::new(move |n: usize| -> String { - format!("{}{}{}{}", prefix, before, n, after) + format!("{prefix}{before}{n}{after}") }), "o" => Box::new(move |n: usize| -> String { - format!("{}{}{:o}{}", prefix, before, n, after) + format!("{prefix}{before}{n:o}{after}") }), "x" => Box::new(move |n: usize| -> String { - format!("{}{}{:x}{}", prefix, before, n, after) + format!("{prefix}{before}{n:x}{after}") }), "X" => Box::new(move |n: usize| -> String { - format!("{}{}{:X}{}", prefix, before, n, after) + format!("{prefix}{before}{n:X}{after}") }), _ => return Err(CsplitError::SuffixFormatIncorrect), }, @@ -82,19 +80,19 @@ impl SplitName { */ // decimal ("0", "d" | "i" | "u") => Box::new(move |n: usize| -> String { - format!("{}{}{:0width$}{}", prefix, before, n, after) + format!("{prefix}{before}{n:0width$}{after}") }), // octal ("0", "o") => Box::new(move |n: usize| -> String { - format!("{}{}{:0width$o}{}", prefix, before, n, after) + format!("{prefix}{before}{n:0width$o}{after}") }), // lower hexadecimal ("0", "x") => Box::new(move |n: usize| -> String { - format!("{}{}{:0width$x}{}", prefix, before, n, after) + format!("{prefix}{before}{n:0width$x}{after}") }), // upper hexadecimal ("0", "X") => Box::new(move |n: usize| -> String { - format!("{}{}{:0width$X}{}", prefix, before, n, after) + format!("{prefix}{before}{n:0width$X}{after}") }), /* @@ -102,15 +100,15 @@ impl SplitName { */ // octal ("#", "o") => Box::new(move |n: usize| -> String { - format!("{}{}{:>#width$o}{}", prefix, before, n, after) + format!("{prefix}{before}{n:>#width$o}{after}") }), // lower hexadecimal ("#", "x") => Box::new(move |n: usize| -> String { - format!("{}{}{:>#width$x}{}", prefix, before, n, after) + format!("{prefix}{before}{n:>#width$x}{after}") }), // upper hexadecimal ("#", "X") => Box::new(move |n: usize| -> String { - format!("{}{}{:>#width$X}{}", prefix, before, n, after) + format!("{prefix}{before}{n:>#width$X}{after}") }), /* @@ -118,19 +116,19 @@ impl SplitName { */ // decimal ("-", "d" | "i" | "u") => Box::new(move |n: usize| -> String { - format!("{}{}{:<#width$}{}", prefix, before, n, after) + format!("{prefix}{before}{n:<#width$}{after}") }), // octal ("-", "o") => Box::new(move |n: usize| -> String { - format!("{}{}{:<#width$o}{}", prefix, before, n, after) + format!("{prefix}{before}{n:<#width$o}{after}") }), // lower hexadecimal ("-", "x") => Box::new(move |n: usize| -> String { - format!("{}{}{:<#width$x}{}", prefix, before, n, after) + format!("{prefix}{before}{n:<#width$x}{after}") }), // upper hexadecimal ("-", "X") => Box::new(move |n: usize| -> String { - format!("{}{}{:<#width$X}{}", prefix, before, n, after) + format!("{prefix}{before}{n:<#width$X}{after}") }), _ => return Err(CsplitError::SuffixFormatIncorrect), diff --git a/src/uu/date/src/date.rs b/src/uu/date/src/date.rs index 03da2e46d..e02d91f1b 100644 --- a/src/uu/date/src/date.rs +++ b/src/uu/date/src/date.rs @@ -117,7 +117,7 @@ impl<'a> From<&'a str> for Iso8601Format { NS => Self::Ns, DATE => Self::Date, // Should be caught by clap - _ => panic!("Invalid format: {}", s), + _ => panic!("Invalid format: {s}"), } } } @@ -135,7 +135,7 @@ impl<'a> From<&'a str> for Rfc3339Format { SECONDS | SECOND => Self::Seconds, NS => Self::Ns, // Should be caught by clap - _ => panic!("Invalid format: {}", s), + _ => panic!("Invalid format: {s}"), } } } @@ -257,7 +257,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { .format_with_items(format_items) .to_string() .replace("%f", "%N"); - println!("{}", formatted); + println!("{formatted}"); } Err((input, _err)) => show_error!("invalid date {}", input.quote()), } diff --git a/src/uu/dd/src/dd.rs b/src/uu/dd/src/dd.rs index 8f91080fe..813d60ceb 100644 --- a/src/uu/dd/src/dd.rs +++ b/src/uu/dd/src/dd.rs @@ -772,9 +772,7 @@ fn is_stdout_redirected_to_seekable_file() -> bool { let p = Path::new(&s); match File::open(p) { Ok(mut f) => { - f.seek(SeekFrom::Current(0)).is_ok() - && f.seek(SeekFrom::End(0)).is_ok() - && f.seek(SeekFrom::Start(0)).is_ok() + f.stream_position().is_ok() && f.seek(SeekFrom::End(0)).is_ok() && f.rewind().is_ok() } Err(_) => false, } diff --git a/src/uu/dd/src/numbers.rs b/src/uu/dd/src/numbers.rs index 1a32180b7..0cab572b4 100644 --- a/src/uu/dd/src/numbers.rs +++ b/src/uu/dd/src/numbers.rs @@ -80,7 +80,7 @@ pub(crate) fn to_magnitude_and_suffix(n: u128, suffix_type: SuffixType) -> Strin // let quotient = (n as f64) / (base as f64); if quotient < 10.0 { - format!("{:.1} {}", quotient, suffix) + format!("{quotient:.1} {suffix}") } else { format!("{} {}", quotient.round(), suffix) } diff --git a/src/uu/dd/src/parseargs.rs b/src/uu/dd/src/parseargs.rs index beeccc2e3..96f6ebfaa 100644 --- a/src/uu/dd/src/parseargs.rs +++ b/src/uu/dd/src/parseargs.rs @@ -394,7 +394,7 @@ impl std::fmt::Display for ParseError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::UnrecognizedOperand(arg) => { - write!(f, "Unrecognized operand '{}'", arg) + write!(f, "Unrecognized operand '{arg}'") } Self::MultipleFmtTable => { write!( @@ -421,32 +421,31 @@ impl std::fmt::Display for ParseError { ) } Self::ConvFlagNoMatch(arg) => { - write!(f, "Unrecognized conv=CONV -> {}", arg) + write!(f, "Unrecognized conv=CONV -> {arg}") } Self::MultiplierStringParseFailure(arg) => { - write!(f, "Unrecognized byte multiplier -> {}", arg) + write!(f, "Unrecognized byte multiplier -> {arg}") } Self::MultiplierStringOverflow(arg) => { write!( f, - "Multiplier string would overflow on current system -> {}", - arg + "Multiplier string would overflow on current system -> {arg}" ) } Self::BlockUnblockWithoutCBS => { write!(f, "conv=block or conv=unblock specified without cbs=N") } Self::StatusLevelNotRecognized(arg) => { - write!(f, "status=LEVEL not recognized -> {}", arg) + write!(f, "status=LEVEL not recognized -> {arg}") } Self::BsOutOfRange(arg) => { - write!(f, "{}=N cannot fit into memory", arg) + write!(f, "{arg}=N cannot fit into memory") } Self::Unimplemented(arg) => { - write!(f, "feature not implemented on this system -> {}", arg) + write!(f, "feature not implemented on this system -> {arg}") } Self::InvalidNumber(arg) => { - write!(f, "invalid number: ‘{}’", arg) + write!(f, "invalid number: ‘{arg}’") } } } diff --git a/src/uu/dd/src/parseargs/unit_tests.rs b/src/uu/dd/src/parseargs/unit_tests.rs index 7084f8114..a135c3572 100644 --- a/src/uu/dd/src/parseargs/unit_tests.rs +++ b/src/uu/dd/src/parseargs/unit_tests.rs @@ -56,29 +56,28 @@ fn unimplemented_flags_should_error() { // The following flags are not implemented for flag in ["cio", "nocache", "nolinks", "text", "binary"] { - let args = vec![format!("iflag={}", flag)]; + let args = vec![format!("iflag={flag}")]; if Parser::new() .parse(&args.iter().map(AsRef::as_ref).collect::>()[..]) .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::>()[..]) .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:?}" ); } diff --git a/src/uu/dd/src/progress.rs b/src/uu/dd/src/progress.rs index 9302bc7a6..6afd841d2 100644 --- a/src/uu/dd/src/progress.rs +++ b/src/uu/dd/src/progress.rs @@ -100,7 +100,7 @@ impl ProgUpdate { match self.read_stat.records_truncated { 0 => {} 1 => writeln!(w, "1 truncated record")?, - n => writeln!(w, "{} truncated records", n)?, + n => writeln!(w, "{n} truncated records")?, } Ok(()) } @@ -154,29 +154,19 @@ impl ProgUpdate { match btotal { 1 => write!( w, - "{}{} byte copied, {:.1} s, {}/s{}", - carriage_return, btotal, duration, transfer_rate, newline, + "{carriage_return}{btotal} byte copied, {duration:.1} s, {transfer_rate}/s{newline}", ), 0..=999 => write!( w, - "{}{} bytes copied, {:.1} s, {}/s{}", - carriage_return, btotal, duration, transfer_rate, newline, + "{carriage_return}{btotal} bytes copied, {duration:.1} s, {transfer_rate}/s{newline}", ), 1000..=1023 => write!( w, - "{}{} bytes ({}) copied, {:.1} s, {}/s{}", - carriage_return, btotal, btotal_metric, duration, transfer_rate, newline, + "{carriage_return}{btotal} bytes ({btotal_metric}) copied, {duration:.1} s, {transfer_rate}/s{newline}", ), _ => write!( w, - "{}{} bytes ({}, {}) copied, {:.1} s, {}/s{}", - carriage_return, - btotal, - btotal_metric, - btotal_bin, - duration, - transfer_rate, - newline, + "{carriage_return}{btotal} bytes ({btotal_metric}, {btotal_bin}) copied, {duration:.1} s, {transfer_rate}/s{newline}", ), } } @@ -455,10 +445,7 @@ pub(crate) fn gen_prog_updater( register_linux_signal_handler(sigval.clone()).unwrap_or_else(|e| { if Some(StatusLevel::None) != print_level { - eprintln!( - "Internal dd Warning: Unable to register signal handler \n\t{}", - e - ); + eprintln!("Internal dd Warning: Unable to register signal handler \n\t{e}"); } }); diff --git a/src/uu/df/src/blocks.rs b/src/uu/df/src/blocks.rs index 79151f817..f48d2ffd2 100644 --- a/src/uu/df/src/blocks.rs +++ b/src/uu/df/src/blocks.rs @@ -91,12 +91,12 @@ pub(crate) fn to_magnitude_and_suffix(n: u128, suffix_type: SuffixType) -> Strin let suffix = suffixes[i]; if rem == 0 { - format!("{}{}", quot, suffix) + format!("{quot}{suffix}") } else { let tenths_place = rem / (bases[i] / 10); if rem % (bases[i] / 10) == 0 { - format!("{}.{}{}", quot, tenths_place, suffix) + format!("{quot}.{tenths_place}{suffix}") } else if tenths_place + 1 == 10 || quot >= 10 { format!("{}{}", quot + 1, suffix) } else { @@ -205,7 +205,7 @@ impl fmt::Display for BlockSize { to_magnitude_and_suffix(*n as u128, SuffixType::Si) }; - write!(f, "{}", s) + write!(f, "{s}") } } } diff --git a/src/uu/df/src/df.rs b/src/uu/df/src/df.rs index a07605399..b3692f481 100644 --- a/src/uu/df/src/df.rs +++ b/src/uu/df/src/df.rs @@ -146,10 +146,10 @@ impl fmt::Display for OptionsError { } // TODO This needs to vary based on whether `--block-size` // or `-B` were provided. - Self::InvalidBlockSize(s) => write!(f, "invalid --block-size argument {}", s), + Self::InvalidBlockSize(s) => write!(f, "invalid --block-size argument {s}"), // TODO This needs to vary based on whether `--block-size` // or `-B` were provided. - Self::InvalidSuffix(s) => write!(f, "invalid suffix in --block-size argument {}", s), + Self::InvalidSuffix(s) => write!(f, "invalid suffix in --block-size argument {s}"), Self::ColumnError(ColumnError::MultipleColumns(s)) => write!( f, "option --output: field {} used more than once", diff --git a/src/uu/df/src/table.rs b/src/uu/df/src/table.rs index 63a135831..a1a58792d 100644 --- a/src/uu/df/src/table.rs +++ b/src/uu/df/src/table.rs @@ -438,7 +438,7 @@ impl fmt::Display for Table { Alignment::Left => { if is_last_col { // no trailing spaces in last column - write!(f, "{}", elem)?; + write!(f, "{elem}")?; } else { write!(f, "{: UResult<()> { ), )); } - println!("{}", INTERNAL_DB); + println!("{INTERNAL_DB}"); return Ok(()); } @@ -157,7 +157,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { match result { Ok(s) => { - println!("{}", s); + println!("{s}"); Ok(()) } Err(s) => { @@ -368,23 +368,23 @@ where if state != ParseState::Pass { if key.starts_with('.') { if *fmt == OutputFmt::Display { - result.push_str(format!("\x1b[{1}m*{0}\t{1}\x1b[0m\n", key, val).as_str()); + result.push_str(format!("\x1b[{val}m*{key}\t{val}\x1b[0m\n").as_str()); } else { - result.push_str(format!("*{}={}:", key, val).as_str()); + result.push_str(format!("*{key}={val}:").as_str()); } } else if key.starts_with('*') { if *fmt == OutputFmt::Display { - result.push_str(format!("\x1b[{1}m{0}\t{1}\x1b[0m\n", key, val).as_str()); + result.push_str(format!("\x1b[{val}m{key}\t{val}\x1b[0m\n").as_str()); } else { - result.push_str(format!("{}={}:", key, val).as_str()); + result.push_str(format!("{key}={val}:").as_str()); } } else if lower == "options" || lower == "color" || lower == "eightbit" { // Slackware only. Ignore } else if let Some(s) = table.get(lower.as_str()) { if *fmt == OutputFmt::Display { - result.push_str(format!("\x1b[{1}m{0}\t{1}\x1b[0m\n", s, val).as_str()); + result.push_str(format!("\x1b[{val}m{s}\t{val}\x1b[0m\n").as_str()); } else { - result.push_str(format!("{}={}:", s, val).as_str()); + result.push_str(format!("{s}={val}:").as_str()); } } else { return Err(format!( diff --git a/src/uu/dirname/src/dirname.rs b/src/uu/dirname/src/dirname.rs index 1f15ccdca..99495f88d 100644 --- a/src/uu/dirname/src/dirname.rs +++ b/src/uu/dirname/src/dirname.rs @@ -63,7 +63,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { } } } - print!("{}", separator); + print!("{separator}"); } } else { return Err(UUsageError::new(1, "missing operand")); diff --git a/src/uu/du/src/du.rs b/src/uu/du/src/du.rs index f65afa32f..9d1bb776f 100644 --- a/src/uu/du/src/du.rs +++ b/src/uu/du/src/du.rs @@ -389,7 +389,7 @@ fn convert_size_human(size: u64, multiplier: u64, _block_size: u64) -> String { if size == 0 { return "0".to_string(); } - format!("{}B", size) + format!("{size}B") } fn convert_size_b(size: u64, _multiplier: u64, _block_size: u64) -> String { @@ -448,7 +448,7 @@ Try '{} --help' for more information.", 'birth' and 'creation' arguments are not supported on this platform.", s.quote() ), - Self::InvalidGlob(s) => write!(f, "Invalid exclude syntax: {}", s), + Self::InvalidGlob(s) => write!(f, "Invalid exclude syntax: {s}"), } } } @@ -650,12 +650,12 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let time_str = tm.format(time_format_str).to_string(); print!("{}\t{}\t", convert_size(size), time_str); print_verbatim(stat.path).unwrap(); - print!("{}", line_separator); + print!("{line_separator}"); } } else if !summarize || index == len - 1 { print!("{}\t", convert_size(size)); print_verbatim(stat.path).unwrap(); - print!("{}", line_separator); + print!("{line_separator}"); } if options.total && index == (len - 1) { // The last element will be the total size of the the path under @@ -674,7 +674,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { if options.total { print!("{}\ttotal", convert_size(grand_total)); - print!("{}", line_separator); + print!("{line_separator}"); } Ok(()) diff --git a/src/uu/echo/src/echo.rs b/src/uu/echo/src/echo.rs index cae9e6225..e6608682b 100644 --- a/src/uu/echo/src/echo.rs +++ b/src/uu/echo/src/echo.rs @@ -103,7 +103,7 @@ fn print_escaped(input: &str, mut output: impl Write) -> io::Result { // because printing char slices is apparently not available in the standard library for ch in &buffer[start..] { - write!(output, "{}", ch)?; + write!(output, "{ch}")?; } } @@ -173,7 +173,7 @@ fn execute(no_newline: bool, escaped: bool, free: &[String]) -> io::Result<()> { break; } } else { - write!(output, "{}", input)?; + write!(output, "{input}")?; } } diff --git a/src/uu/env/src/env.rs b/src/uu/env/src/env.rs index 0776a6b12..a38e04348 100644 --- a/src/uu/env/src/env.rs +++ b/src/uu/env/src/env.rs @@ -210,7 +210,7 @@ fn run_env(args: impl uucore::Args) -> UResult<()> { Err(error) => { return Err(USimpleError::new( 125, - format!("cannot change directory to \"{}\": {}", d, error), + format!("cannot change directory to \"{d}\": {error}"), )); } }; diff --git a/src/uu/expand/src/expand.rs b/src/uu/expand/src/expand.rs index 63de76fbd..cbb5593f9 100644 --- a/src/uu/expand/src/expand.rs +++ b/src/uu/expand/src/expand.rs @@ -255,7 +255,7 @@ fn expand_shortcuts(args: &[String]) -> Vec { arg[1..] .split(',') .filter(|s| !s.is_empty()) - .for_each(|s| processed_args.push(format!("--tabs={}", s))); + .for_each(|s| processed_args.push(format!("--tabs={s}"))); } else { processed_args.push(arg.to_string()); } diff --git a/src/uu/expr/src/expr.rs b/src/uu/expr/src/expr.rs index 7c262da87..a5fab19f2 100644 --- a/src/uu/expr/src/expr.rs +++ b/src/uu/expr/src/expr.rs @@ -73,7 +73,7 @@ fn process_expr(token_strings: &[&str]) -> Result { } fn print_expr_ok(expr_result: &str) -> UResult<()> { - println!("{}", expr_result); + println!("{expr_result}"); if expr_result.parse::() == Ok(0) || expr_result.is_empty() { Err(1.into()) } else { diff --git a/src/uu/expr/src/syntax_tree.rs b/src/uu/expr/src/syntax_tree.rs index 6a112df75..936760f27 100644 --- a/src/uu/expr/src/syntax_tree.rs +++ b/src/uu/expr/src/syntax_tree.rs @@ -151,7 +151,7 @@ impl AstNode { "index" => Ok(prefix_operator_index(&operand_values)), "substr" => Ok(prefix_operator_substr(&operand_values)), - _ => Err(format!("operation not implemented: {}", op_type)), + _ => Err(format!("operation not implemented: {op_type}")), }, }, } @@ -204,7 +204,7 @@ fn maybe_dump_ast(result: &Result, String>) { println!("EXPR_DEBUG_AST"); match result { Ok(ast) => ast.debug_dump(), - Err(reason) => println!("\terr: {:?}", reason), + Err(reason) => println!("\terr: {reason:?}"), } } } @@ -217,7 +217,7 @@ fn maybe_dump_rpn(rpn: &TokenStack) { if debug_var == "1" { println!("EXPR_DEBUG_RPN"); for token in rpn { - println!("\t{:?}", token); + println!("\t{token:?}"); } } } @@ -238,7 +238,7 @@ fn ast_from_rpn(rpn: &mut TokenStack) -> Result, String> { } Some((token_idx, unexpected_token)) => { - panic!("unexpected token at #{} {:?}", token_idx, unexpected_token) + panic!("unexpected token at #{token_idx} {unexpected_token:?}") } } } @@ -266,14 +266,12 @@ fn move_rest_of_ops_to_out( None => return Ok(()), Some((token_idx, Token::ParOpen)) => { return Err(format!( - "syntax error (Mismatched open-parenthesis at #{})", - token_idx + "syntax error (Mismatched open-parenthesis at #{token_idx})" )) } Some((token_idx, Token::ParClose)) => { return Err(format!( - "syntax error (Mismatched close-parenthesis at #{})", - token_idx + "syntax error (Mismatched close-parenthesis at #{token_idx})" )) } Some(other) => out_stack.push(other), @@ -325,10 +323,10 @@ fn maybe_dump_shunting_yard_step( if let Ok(debug_var) = env::var("EXPR_DEBUG_SYA_STEP") { if debug_var == "1" { println!("EXPR_DEBUG_SYA_STEP"); - println!("\t{} => {:?}", token_idx, token); - println!("\t\tout: {:?}", out_stack); - println!("\t\top : {:?}", op_stack); - println!("\t\tresult: {:?}", result); + println!("\t{token_idx} => {token:?}"); + println!("\t\tout: {out_stack:?}"); + println!("\t\top : {op_stack:?}"); + println!("\t\tresult: {result:?}"); } } } diff --git a/src/uu/expr/src/tokens.rs b/src/uu/expr/src/tokens.rs index 6ff930f81..21220d7dc 100644 --- a/src/uu/expr/src/tokens.rs +++ b/src/uu/expr/src/tokens.rs @@ -122,7 +122,7 @@ fn maybe_dump_tokens_acc(tokens_acc: &[(usize, Token)]) { if debug_var == "1" { println!("EXPR_DEBUG_TOKENS"); for token in tokens_acc { - println!("\t{:?}", token); + println!("\t{token:?}"); } } } diff --git a/src/uu/factor/build.rs b/src/uu/factor/build.rs index aad2aac77..bdd132094 100644 --- a/src/uu/factor/build.rs +++ b/src/uu/factor/build.rs @@ -46,7 +46,7 @@ fn main() { .and_then(|s| s.parse::().ok()) .unwrap_or(DEFAULT_SIZE); - write!(file, "{}", PREAMBLE).unwrap(); + write!(file, "{PREAMBLE}").unwrap(); let mut cols = 3; // we want a total of n + 1 values @@ -60,10 +60,10 @@ fn main() { // format the table let output = format!("({}, {}, {}),", x, modular_inverse(x), std::u64::MAX / x); if cols + output.len() > MAX_WIDTH { - write!(file, "\n {}", output).unwrap(); + write!(file, "\n {output}").unwrap(); cols = 4 + output.len(); } else { - write!(file, " {}", output).unwrap(); + write!(file, " {output}").unwrap(); cols += 1 + output.len(); } @@ -72,8 +72,7 @@ fn main() { write!( file, - "\n];\n\n#[allow(dead_code)]\npub const NEXT_PRIME: u64 = {};\n", - x + "\n];\n\n#[allow(dead_code)]\npub const NEXT_PRIME: u64 = {x};\n" ) .unwrap(); } diff --git a/src/uu/factor/src/factor.rs b/src/uu/factor/src/factor.rs index c776f95ea..5d1615342 100644 --- a/src/uu/factor/src/factor.rs +++ b/src/uu/factor/src/factor.rs @@ -99,7 +99,7 @@ impl fmt::Display for Factors { for (p, exp) in v.iter() { for _ in 0..*exp { - write!(f, " {}", p)?; + write!(f, " {p}")?; } } diff --git a/src/uu/factor/src/miller_rabin.rs b/src/uu/factor/src/miller_rabin.rs index 8906abf59..4908959fb 100644 --- a/src/uu/factor/src/miller_rabin.rs +++ b/src/uu/factor/src/miller_rabin.rs @@ -153,8 +153,7 @@ mod tests { for p in odd_primes() { assert!( test(Montgomery::::new(p)).is_prime(), - "{} reported composite", - p + "{p} reported composite" ); } } @@ -173,7 +172,7 @@ mod tests { fn first_composites() { for (p, q) in primes().zip(odd_primes()) { for i in p + 1..q { - assert!(!is_prime(i), "{} reported prime", i); + assert!(!is_prime(i), "{i} reported prime"); } } } @@ -192,7 +191,7 @@ mod tests { for q in odd_primes().take_while(|q| *q <= p) { let n = p * q; let m = Montgomery::::new(n); - assert!(!test(m).is_prime(), "{} = {} × {} reported prime", n, p, q); + assert!(!test(m).is_prime(), "{n} = {p} × {q} reported prime"); } } } diff --git a/src/uu/factor/src/numeric/gcd.rs b/src/uu/factor/src/numeric/gcd.rs index 089318f48..05eb20cb0 100644 --- a/src/uu/factor/src/numeric/gcd.rs +++ b/src/uu/factor/src/numeric/gcd.rs @@ -32,8 +32,8 @@ pub fn gcd(mut u: u64, mut v: u64) -> u64 { loop { // Loop invariant: u and v are odd - debug_assert!(u % 2 == 1, "u = {} is even", u); - debug_assert!(v % 2 == 1, "v = {} is even", v); + debug_assert!(u % 2 == 1, "u = {u} is even"); + debug_assert!(v % 2 == 1, "v = {v} is even"); // gcd(u, v) = gcd(|u - v|, min(u, v)) if u > v { diff --git a/src/uu/factor/src/numeric/modular_inverse.rs b/src/uu/factor/src/numeric/modular_inverse.rs index 5b37a9782..edf3c6cce 100644 --- a/src/uu/factor/src/numeric/modular_inverse.rs +++ b/src/uu/factor/src/numeric/modular_inverse.rs @@ -13,7 +13,7 @@ use super::traits::Int; pub(crate) fn modular_inverse(a: T) -> T { let zero = T::zero(); let one = T::one(); - debug_assert!(a % (one + one) == one, "{:?} is not odd", a); + debug_assert!(a % (one + one) == one, "{a:?} is not odd"); let mut t = zero; let mut new_t = one; diff --git a/src/uu/factor/src/numeric/montgomery.rs b/src/uu/factor/src/numeric/montgomery.rs index 368a71182..e07b95358 100644 --- a/src/uu/factor/src/numeric/montgomery.rs +++ b/src/uu/factor/src/numeric/montgomery.rs @@ -192,7 +192,7 @@ mod tests { let m_x = m.to_mod(x); for y in 0..=x { let m_y = m.to_mod(y); - println!("{n:?}, {x:?}, {y:?}", n = n, x = x, y = y); + println!("{n:?}, {x:?}, {y:?}"); assert_eq!((x + y) % n, m.to_u64(m.add(m_x, m_y))); } } diff --git a/src/uu/fmt/src/linebreak.rs b/src/uu/fmt/src/linebreak.rs index 75a5f81ac..75cd633bb 100644 --- a/src/uu/fmt/src/linebreak.rs +++ b/src/uu/fmt/src/linebreak.rs @@ -27,7 +27,7 @@ struct BreakArgs<'a> { } impl<'a> BreakArgs<'a> { - fn compute_width<'b>(&self, winfo: &WordInfo<'b>, posn: usize, fresh: bool) -> usize { + fn compute_width(&self, winfo: &WordInfo, posn: usize, fresh: bool) -> usize { if fresh { 0 } else { diff --git a/src/uu/fold/src/fold.rs b/src/uu/fold/src/fold.rs index 3b27549b1..dee30b258 100644 --- a/src/uu/fold/src/fold.rs +++ b/src/uu/fold/src/fold.rs @@ -188,9 +188,9 @@ fn fold_file_bytewise(mut file: BufReader, spaces: bool, width: usiz let at_eol = i >= len; if at_eol { - print!("{}", slice); + print!("{slice}"); } else { - println!("{}", slice); + println!("{slice}"); } } @@ -285,7 +285,7 @@ fn fold_file(mut file: BufReader, spaces: bool, width: usize) -> URe } if !output.is_empty() { - print!("{}", output); + print!("{output}"); output.truncate(0); } diff --git a/src/uu/groups/src/groups.rs b/src/uu/groups/src/groups.rs index 4fa53a232..c866d0e1b 100644 --- a/src/uu/groups/src/groups.rs +++ b/src/uu/groups/src/groups.rs @@ -49,7 +49,7 @@ impl Display for GroupsError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { Self::GetGroupsFailed => write!(f, "failed to fetch groups"), - Self::GroupNotFound(gid) => write!(f, "cannot find name for group ID {}", gid), + Self::GroupNotFound(gid) => write!(f, "cannot find name for group ID {gid}"), Self::UserNotFound(user) => write!(f, "{}: no such user", user.quote()), } } diff --git a/src/uu/hashsum/src/hashsum.rs b/src/uu/hashsum/src/hashsum.rs index 5e0973a16..3271425bc 100644 --- a/src/uu/hashsum/src/hashsum.rs +++ b/src/uu/hashsum/src/hashsum.rs @@ -520,13 +520,12 @@ where // where `n` is the number of bytes. let bytes = options.digest.output_bits() / 4; let modifier = if bytes > 0 { - format!("{{{}}}", bytes) + format!("{{{bytes}}}") } else { "+".to_string() }; let gnu_re = Regex::new(&format!( - r"^(?P[a-fA-F0-9]{}) (?P[ \*])(?P.*)", - modifier, + r"^(?P[a-fA-F0-9]{modifier}) (?P[ \*])(?P.*)", )) .map_err(|_| HashsumError::InvalidRegex)?; let bsd_re = Regex::new(&format!( @@ -579,7 +578,7 @@ where uucore::util_name(), ck_filename ); - println!("{}: FAILED open or read", ck_filename); + println!("{ck_filename}: FAILED open or read"); continue; } Ok(file) => file, @@ -604,11 +603,11 @@ where // easier (and more important) on Unix than on Windows. if sum == real_sum { if !options.quiet { - println!("{}: OK", ck_filename); + println!("{ck_filename}: OK"); } } else { if !options.status { - println!("{}: FAILED", ck_filename); + println!("{ck_filename}: FAILED"); } failed_cksum += 1; } @@ -624,7 +623,7 @@ where if options.tag { println!("{} ({}) = {}", options.algoname, filename.display(), sum); } else if options.nonames { - println!("{}", sum); + println!("{sum}"); } else { println!("{} {}{}", sum, binary_marker, filename.display()); } diff --git a/src/uu/head/src/head.rs b/src/uu/head/src/head.rs index a006d5a90..48debc81f 100644 --- a/src/uu/head/src/head.rs +++ b/src/uu/head/src/head.rs @@ -134,7 +134,7 @@ impl Mode { fn from(matches: &ArgMatches) -> Result { if let Some(v) = matches.get_one::(options::BYTES_NAME) { let (n, all_but_last) = - parse::parse_num(v).map_err(|err| format!("invalid number of bytes: {}", err))?; + parse::parse_num(v).map_err(|err| format!("invalid number of bytes: {err}"))?; if all_but_last { Ok(Self::AllButLastBytes(n)) } else { @@ -142,7 +142,7 @@ impl Mode { } } else if let Some(v) = matches.get_one::(options::LINES_NAME) { let (n, all_but_last) = - parse::parse_num(v).map_err(|err| format!("invalid number of lines: {}", err))?; + parse::parse_num(v).map_err(|err| format!("invalid number of lines: {err}"))?; if all_but_last { Ok(Self::AllButLastLines(n)) } else { @@ -387,13 +387,13 @@ where } // if it were just `n`, if lines == n + 1 { - input.seek(SeekFrom::Start(0))?; + input.rewind()?; return Ok(size - i); } i += 1; } if size - i == 0 { - input.seek(SeekFrom::Start(0))?; + input.rewind()?; return Ok(0); } } @@ -459,7 +459,7 @@ fn uu_head(options: &HeadOptions) -> UResult<()> { if let Err(e) = usize::try_from(n) { show!(USimpleError::new( 1, - format!("{}: number of bytes is too large", e) + format!("{e}: number of bytes is too large") )); continue; }; @@ -493,7 +493,7 @@ fn uu_head(options: &HeadOptions) -> UResult<()> { if !first { println!(); } - println!("==> {} <==", name); + println!("==> {name} <=="); } head_file(&mut file, options) } @@ -506,7 +506,7 @@ fn uu_head(options: &HeadOptions) -> UResult<()> { }; show!(USimpleError::new( 1, - format!("error reading {}: Input/output error", name) + format!("error reading {name}: Input/output error") )); } first = false; diff --git a/src/uu/head/src/parse.rs b/src/uu/head/src/parse.rs index 3b7c718ab..cbfc97152 100644 --- a/src/uu/head/src/parse.rs +++ b/src/uu/head/src/parse.rs @@ -79,10 +79,10 @@ pub fn parse_obsolete(src: &str) -> Option Some(n) => n, None => return Some(Err(ParseError::Overflow)), }; - options.push(OsString::from(format!("{}", num))); + options.push(OsString::from(format!("{num}"))); } else { options.push(OsString::from("-n")); - options.push(OsString::from(format!("{}", num))); + options.push(OsString::from(format!("{num}"))); } Some(Ok(options.into_iter())) } diff --git a/src/uu/hostid/src/hostid.rs b/src/uu/hostid/src/hostid.rs index 293a9cacd..147c7c548 100644 --- a/src/uu/hostid/src/hostid.rs +++ b/src/uu/hostid/src/hostid.rs @@ -50,5 +50,5 @@ fn hostid() { let mask = 0xffff_ffff; result &= mask; - println!("{:0>8x}", result); + println!("{result:0>8x}"); } diff --git a/src/uu/hostname/src/hostname.rs b/src/uu/hostname/src/hostname.rs index 92950f137..03e9fe2e0 100644 --- a/src/uu/hostname/src/hostname.rs +++ b/src/uu/hostname/src/hostname.rs @@ -164,7 +164,7 @@ fn display_hostname(matches: &ArgMatches) -> UResult<()> { } } - println!("{}", hostname); + println!("{hostname}"); Ok(()) } diff --git a/src/uu/id/src/id.rs b/src/uu/id/src/id.rs index a26034f47..9aa6e2f31 100644 --- a/src/uu/id/src/id.rs +++ b/src/uu/id/src/id.rs @@ -326,7 +326,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { if default_format { id_print(&mut state, &groups); } - print!("{}", line_ending); + print!("{line_ending}"); if i + 1 >= users.len() { break; @@ -468,11 +468,11 @@ fn pretty(possible_pw: Option) { let rid = getuid(); if let Ok(p) = Passwd::locate(rid) { if login == p.name { - println!("login\t{}", login); + println!("login\t{login}"); } println!("uid\t{}", p.name); } else { - println!("uid\t{}", rid); + println!("uid\t{rid}"); } let eid = getegid(); @@ -480,7 +480,7 @@ fn pretty(possible_pw: Option) { if let Ok(p) = Passwd::locate(eid) { println!("euid\t{}", p.name); } else { - println!("euid\t{}", eid); + println!("euid\t{eid}"); } } @@ -489,7 +489,7 @@ fn pretty(possible_pw: Option) { if let Ok(g) = Group::locate(rid) { println!("euid\t{}", g.name); } else { - println!("euid\t{}", rid); + println!("euid\t{rid}"); } } diff --git a/src/uu/install/src/install.rs b/src/uu/install/src/install.rs index db9fe7d3c..597eacc67 100644 --- a/src/uu/install/src/install.rs +++ b/src/uu/install/src/install.rs @@ -87,7 +87,7 @@ impl Error for InstallError {} impl Display for InstallError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Self::Unimplemented(opt) => write!(f, "Unimplemented feature: {}", opt), + Self::Unimplemented(opt) => write!(f, "Unimplemented feature: {opt}"), Self::DirNeedsArg() => { write!( f, @@ -115,7 +115,7 @@ impl Display for InstallError { &uio_error!(e, "cannot install {} to {}", from.quote(), to.quote()), f, ), - Self::StripProgramFailed(msg) => write!(f, "strip program failed: {}", msg), + Self::StripProgramFailed(msg) => write!(f, "strip program failed: {msg}"), Self::MetadataFailed(e) => Display::fmt(&uio_error!(e, ""), f), Self::NoSuchUser(user) => write!(f, "no such user: {}", user.maybe_quote()), Self::NoSuchGroup(group) => write!(f, "no such group: {}", group.maybe_quote()), diff --git a/src/uu/join/src/join.rs b/src/uu/join/src/join.rs index 422344159..ffcf6fdcd 100644 --- a/src/uu/join/src/join.rs +++ b/src/uu/join/src/join.rs @@ -41,7 +41,7 @@ impl Error for JoinError {} impl Display for JoinError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Self::IOError(e) => write!(f, "io error: {}", e), + Self::IOError(e) => write!(f, "io error: {e}"), Self::UnorderedInput(e) => f.write_str(e), } } @@ -692,7 +692,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { match exec(file1, file2, settings) { Ok(_) => Ok(()), - Err(e) => Err(USimpleError::new(1, format!("{}", e))), + Err(e) => Err(USimpleError::new(1, format!("{e}"))), } } diff --git a/src/uu/kill/src/kill.rs b/src/uu/kill/src/kill.rs index 3e55f8166..c14023e82 100644 --- a/src/uu/kill/src/kill.rs +++ b/src/uu/kill/src/kill.rs @@ -146,11 +146,11 @@ fn table() { fn print_signal(signal_name_or_value: &str) -> UResult<()> { for (value, &signal) in ALL_SIGNALS.iter().enumerate() { - if signal == signal_name_or_value || (format!("SIG{}", signal)) == signal_name_or_value { - println!("{}", value); + if signal == signal_name_or_value || (format!("SIG{signal}")) == signal_name_or_value { + println!("{value}"); return Ok(()); } else if signal_name_or_value == value.to_string() { - println!("{}", signal); + println!("{signal}"); return Ok(()); } } @@ -165,7 +165,7 @@ fn print_signals() { if idx > 0 { print!(" "); } - print!("{}", signal); + print!("{signal}"); } println!(); } @@ -205,7 +205,7 @@ fn kill(sig: Signal, pids: &[i32]) { for &pid in pids { if let Err(e) = signal::kill(Pid::from_raw(pid), sig) { show!(Error::from_raw_os_error(e as i32) - .map_err_context(|| format!("sending signal to {} failed", pid))); + .map_err_context(|| format!("sending signal to {pid} failed"))); } } } diff --git a/src/uu/ln/src/ln.rs b/src/uu/ln/src/ln.rs index 6ba8a98e8..55bc34f8a 100644 --- a/src/uu/ln/src/ln.rs +++ b/src/uu/ln/src/ln.rs @@ -466,7 +466,7 @@ fn simple_backup_path(path: &Path, suffix: &str) -> PathBuf { fn numbered_backup_path(path: &Path) -> PathBuf { let mut i: u64 = 1; loop { - let new_path = simple_backup_path(path, &format!(".~{}~", i)); + let new_path = simple_backup_path(path, &format!(".~{i}~")); if !new_path.exists() { return new_path; } diff --git a/src/uu/logname/src/logname.rs b/src/uu/logname/src/logname.rs index ef6eb2940..fd5ab904e 100644 --- a/src/uu/logname/src/logname.rs +++ b/src/uu/logname/src/logname.rs @@ -38,7 +38,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let _ = uu_app().try_get_matches_from(args)?; match get_userlogin() { - Some(userlogin) => println!("{}", userlogin), + Some(userlogin) => println!("{userlogin}"), None => show_error!("no login name"), } diff --git a/src/uu/ls/src/ls.rs b/src/uu/ls/src/ls.rs index fdf368e4b..965248495 100644 --- a/src/uu/ls/src/ls.rs +++ b/src/uu/ls/src/ls.rs @@ -197,7 +197,7 @@ impl Display for LsError { ) } Self::InvalidLineWidth(s) => write!(f, "invalid line width: {}", s.quote()), - Self::IOError(e) => write!(f, "general io error: {}", e), + Self::IOError(e) => write!(f, "general io error: {e}"), Self::IOErrorContext(e, p, _) => { let error_kind = e.kind(); let errno = e.raw_os_error().unwrap_or(1i32); @@ -2067,11 +2067,11 @@ fn display_dir_entry_size( } fn pad_left(string: &str, count: usize) -> String { - format!("{:>width$}", string, width = count) + format!("{string:>count$}") } fn pad_right(string: &str, count: usize) -> String { - format!("{:) -> UResult<()> { @@ -2118,7 +2118,7 @@ fn display_additional_leading_info( }; // extra space is insert to align the sizes, as needed for all formats, except for the comma format. if config.format == Format::Commas { - write!(result, "{} ", s).unwrap(); + write!(result, "{s} ").unwrap(); } else { write!(result, "{} ", pad_left(&s, padding.block_size)).unwrap(); }; @@ -2139,13 +2139,13 @@ fn display_items(items: &[PathData], config: &Config, out: &mut BufWriter { - write!(out, "{}", output)?; + write!(out, "{output}")?; } // Width is too small for the grid, so we fit it in one column None => { @@ -2440,7 +2440,7 @@ fn display_item_long( write!( out, "{}{} {}", - format_args!("{}?????????", leading_char), + format_args!("{leading_char}?????????"), if item.security_context.len() > 1 { // GNU `ls` uses a "." character to indicate a file with a security context, // but not other alternate access method. @@ -2875,7 +2875,7 @@ fn display_file_name( } else { path.security_context.to_owned() }; - name = format!("{} {}", security_context, name); + name = format!("{security_context} {name}"); width += security_context.len() + 1; } } diff --git a/src/uu/mkdir/src/mkdir.rs b/src/uu/mkdir/src/mkdir.rs index 038d688f9..046091b34 100644 --- a/src/uu/mkdir/src/mkdir.rs +++ b/src/uu/mkdir/src/mkdir.rs @@ -55,7 +55,7 @@ fn get_mode(matches: &ArgMatches, mode_had_minus_prefix: bool) -> Result UResult<()> { let mode = match matches.get_one::(options::MODE) { Some(m) => match usize::from_str_radix(m, 8) { Ok(m) => m, - Err(e) => return Err(USimpleError::new(1, format!("invalid mode: {}", e))), + Err(e) => return Err(USimpleError::new(1, format!("invalid mode: {e}"))), }, None => 0o666, }; diff --git a/src/uu/mknod/src/mknod.rs b/src/uu/mknod/src/mknod.rs index 2a1290d41..f4c6f5732 100644 --- a/src/uu/mknod/src/mknod.rs +++ b/src/uu/mknod/src/mknod.rs @@ -184,7 +184,7 @@ fn get_mode(matches: &ArgMatches) -> Result { match matches.get_one::("mode") { None => Ok(MODE_RW_UGO), Some(str_mode) => uucore::mode::parse_mode(str_mode) - .map_err(|e| format!("invalid mode ({})", e)) + .map_err(|e| format!("invalid mode ({e})")) .and_then(|mode| { if mode > 0o777 { Err("mode must specify only file permission bits".to_string()) diff --git a/src/uu/mktemp/src/mktemp.rs b/src/uu/mktemp/src/mktemp.rs index 740644c95..d8056ffce 100644 --- a/src/uu/mktemp/src/mktemp.rs +++ b/src/uu/mktemp/src/mktemp.rs @@ -313,7 +313,7 @@ impl Params { // the template is "XXXabc", then `suffix` is "abc.txt". let suffix_from_option = options.suffix.unwrap_or_default(); let suffix_from_template = &options.template[j..]; - let suffix = format!("{}{}", suffix_from_template, suffix_from_option); + let suffix = format!("{suffix_from_template}{suffix_from_option}"); if suffix.contains(MAIN_SEPARATOR) { return Err(MkTempError::SuffixContainsDirSeparator(suffix)); } diff --git a/src/uu/more/src/more.rs b/src/uu/more/src/more.rs index a58e108ae..0309ad33e 100644 --- a/src/uu/more/src/more.rs +++ b/src/uu/more/src/more.rs @@ -383,9 +383,7 @@ impl<'a> Pager<'a> { .take(self.content_rows.into()); for line in displayed_lines { - stdout - .write_all(format!("\r{}\n", line).as_bytes()) - .unwrap(); + stdout.write_all(format!("\r{line}\n").as_bytes()).unwrap(); } } @@ -399,15 +397,14 @@ impl<'a> Pager<'a> { ) }; - let status = format!("--More--({})", status_inner); + let status = format!("--More--({status_inner})"); let banner = match (self.silent, wrong_key) { (true, Some(key)) => format!( - "{} [Unknown key: '{}'. Press 'h' for instructions. (unimplemented)]", - status, key + "{status} [Unknown key: '{key}'. Press 'h' for instructions. (unimplemented)]" ), - (true, None) => format!("{}[Press space to continue, 'q' to quit.]", status), - (false, Some(_)) => format!("{}{}", status, BELL), + (true, None) => format!("{status}[Press space to continue, 'q' to quit.]"), + (false, Some(_)) => format!("{status}{BELL}"), (false, None) => status, }; diff --git a/src/uu/mv/src/error.rs b/src/uu/mv/src/error.rs index 77f777836..103c1116a 100644 --- a/src/uu/mv/src/error.rs +++ b/src/uu/mv/src/error.rs @@ -22,22 +22,19 @@ impl UError for MvError {} impl Display for MvError { fn fmt(&self, f: &mut Formatter) -> Result { match self { - Self::NoSuchFile(s) => write!(f, "cannot stat {}: No such file or directory", s), - Self::SameFile(s, t) => write!(f, "{} and {} are the same file", s, t), + Self::NoSuchFile(s) => write!(f, "cannot stat {s}: No such file or directory"), + Self::SameFile(s, t) => write!(f, "{s} and {t} are the same file"), Self::SelfSubdirectory(s) => write!( f, - "cannot move '{s}' to a subdirectory of itself, '{s}/{s}'", - s = s + "cannot move '{s}' to a subdirectory of itself, '{s}/{s}'" ), Self::DirectoryToNonDirectory(t) => { - write!(f, "cannot overwrite directory {} with non-directory", t) + write!(f, "cannot overwrite directory {t} with non-directory") } - Self::NonDirectoryToDirectory(s, t) => write!( - f, - "cannot overwrite non-directory {} with directory {}", - t, s - ), - Self::NotADirectory(t) => write!(f, "target {} is not a directory", t), + Self::NonDirectoryToDirectory(s, t) => { + write!(f, "cannot overwrite non-directory {t} with directory {s}") + } + Self::NotADirectory(t) => write!(f, "target {t} is not a directory"), } } } diff --git a/src/uu/mv/src/mv.rs b/src/uu/mv/src/mv.rs index 66b31a977..0a1394594 100644 --- a/src/uu/mv/src/mv.rs +++ b/src/uu/mv/src/mv.rs @@ -91,8 +91,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { app.error( ErrorKind::TooFewValues, format!( - "The argument '<{}>...' requires at least 2 values, but only 1 was provided", - ARG_FILES + "The argument '<{ARG_FILES}>...' requires at least 2 values, but only 1 was provided" ), ) .exit(); @@ -310,7 +309,7 @@ fn exec(files: &[OsString], b: &Behavior) -> UResult<()> { ) .into()) } else { - rename(source, target, b, None).map_err(|e| USimpleError::new(1, format!("{}", e))) + rename(source, target, b, None).map_err(|e| USimpleError::new(1, format!("{e}"))) } } _ => { @@ -473,9 +472,9 @@ fn rename( match multi_progress { Some(pb) => pb.suspend(|| { - println!("{}", message); + println!("{message}"); }), - None => println!("{}", message), + None => println!("{message}"), }; } Ok(()) @@ -547,7 +546,7 @@ fn rename_with_fallback( io::ErrorKind::PermissionDenied, "Permission denied", )), - _ => Err(io::Error::new(io::ErrorKind::Other, format!("{:?}", err))), + _ => Err(io::Error::new(io::ErrorKind::Other, format!("{err:?}"))), }; } } else { diff --git a/src/uu/nice/src/nice.rs b/src/uu/nice/src/nice.rs index e6efb5140..a059e13b7 100644 --- a/src/uu/nice/src/nice.rs +++ b/src/uu/nice/src/nice.rs @@ -137,14 +137,14 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { Err(e) => { return Err(USimpleError::new( 125, - format!("\"{}\" is not a valid number: {}", nstr, e), + format!("\"{nstr}\" is not a valid number: {e}"), )) } } } None => { if !matches.contains_id(options::COMMAND) { - println!("{}", niceness); + println!("{niceness}"); return Ok(()); } 10_i32 diff --git a/src/uu/nl/src/nl.rs b/src/uu/nl/src/nl.rs index a93dc12ef..6243bef8d 100644 --- a/src/uu/nl/src/nl.rs +++ b/src/uu/nl/src/nl.rs @@ -349,7 +349,7 @@ fn nl(reader: &mut BufReader, settings: &Settings) -> UResult<()> { // want to print one in the first place, or it is a blank // line but we are still collecting more blank lines via // the option --join-blank-lines. - println!("{}", line); + println!("{line}"); continue; } // If we make it here, then either we are printing a non-empty diff --git a/src/uu/nohup/src/nohup.rs b/src/uu/nohup/src/nohup.rs index 1dc1cbdd0..789888ea4 100644 --- a/src/uu/nohup/src/nohup.rs +++ b/src/uu/nohup/src/nohup.rs @@ -65,7 +65,7 @@ impl Display for NohupError { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { match self { Self::CannotDetach => write!(f, "Cannot detach from console"), - Self::CannotReplace(s, e) => write!(f, "Cannot replace {}: {}", s, e), + Self::CannotReplace(s, e) => write!(f, "Cannot replace {s}: {e}"), Self::OpenFailed(_, e) => { write!(f, "failed to open {}: {}", NOHUP_OUT.quote(), e) } diff --git a/src/uu/nproc/src/nproc.rs b/src/uu/nproc/src/nproc.rs index e74303dd8..960957df6 100644 --- a/src/uu/nproc/src/nproc.rs +++ b/src/uu/nproc/src/nproc.rs @@ -92,7 +92,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { } else { cores -= ignore; } - println!("{}", cores); + println!("{cores}"); Ok(()) } diff --git a/src/uu/numfmt/src/errors.rs b/src/uu/numfmt/src/errors.rs index c9f63f921..22c6962d6 100644 --- a/src/uu/numfmt/src/errors.rs +++ b/src/uu/numfmt/src/errors.rs @@ -32,7 +32,7 @@ impl Display for NumfmtError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::IoError(s) | Self::IllegalArgument(s) | Self::FormattingError(s) => { - write!(f, "{}", s) + write!(f, "{s}") } } } diff --git a/src/uu/numfmt/src/format.rs b/src/uu/numfmt/src/format.rs index b97993f21..3e20d00ee 100644 --- a/src/uu/numfmt/src/format.rs +++ b/src/uu/numfmt/src/format.rs @@ -135,13 +135,11 @@ fn remove_suffix(i: f64, s: Option, u: &Unit) -> Result { RawSuffix::Z => Ok(i * IEC_BASES[7]), RawSuffix::Y => Ok(i * IEC_BASES[8]), }, - (None, &Unit::Iec(true)) => Err(format!( - "missing 'i' suffix in input: '{}' (e.g Ki/Mi/Gi)", - i - )), + (None, &Unit::Iec(true)) => { + Err(format!("missing 'i' suffix in input: '{i}' (e.g Ki/Mi/Gi)")) + } (Some((raw_suffix, false)), &Unit::Iec(true)) => Err(format!( - "missing 'i' suffix in input: '{}{:?}' (e.g Ki/Mi/Gi)", - i, raw_suffix + "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)", @@ -320,7 +318,7 @@ fn format_string( // bring back the suffix before applying padding let number_with_suffix = match &options.suffix { - Some(suffix) => format!("{}{}", number, suffix), + Some(suffix) => format!("{number}{suffix}"), None => number, }; @@ -362,14 +360,14 @@ fn format_and_print_delimited(s: &str, options: &NumfmtOptions) -> Result<()> { // print delimiter before second and subsequent fields if n > 1 { - print!("{}", delimiter); + print!("{delimiter}"); } if field_selected { print!("{}", format_string(field.trim_start(), options, None)?); } else { // print unselected field without conversion - print!("{}", field); + print!("{field}"); } } @@ -402,7 +400,7 @@ fn format_and_print_whitespace(s: &str, options: &NumfmtOptions) -> Result<()> { print!("{}", format_string(field, options, implicit_padding)?); } else { // print unselected field without conversion - print!("{}{}", prefix, field); + print!("{prefix}{field}"); } } diff --git a/src/uu/numfmt/src/numfmt.rs b/src/uu/numfmt/src/numfmt.rs index 80b604e6d..8730c9f8d 100644 --- a/src/uu/numfmt/src/numfmt.rs +++ b/src/uu/numfmt/src/numfmt.rs @@ -46,7 +46,7 @@ where for (idx, line) in lines.by_ref().enumerate() { match line { Ok(l) if idx < options.header => { - println!("{}", l); + println!("{l}"); Ok(()) } Ok(l) => match format_and_print(&l, options) { @@ -403,8 +403,8 @@ mod tests { let mock_buffer = MockBuffer {}; let result = handle_buffer(BufReader::new(mock_buffer), &get_valid_options()) .expect_err("returned Ok after receiving IO error"); - let result_debug = format!("{:?}", result); - let result_display = format!("{}", result); + let result_debug = format!("{result:?}"); + let result_display = format!("{result}"); assert_eq!(result_debug, "IoError(\"broken pipe\")"); assert_eq!(result_display, "broken pipe"); assert_eq!(result.code(), 1); @@ -415,8 +415,8 @@ mod tests { let input_value = b"135\nhello"; let result = handle_buffer(BufReader::new(&input_value[..]), &get_valid_options()) .expect_err("returned Ok after receiving improperly formatted input"); - let result_debug = format!("{:?}", result); - let result_display = format!("{}", result); + let result_debug = format!("{result:?}"); + let result_display = format!("{result}"); assert_eq!( result_debug, "FormattingError(\"invalid suffix in input: 'hello'\")" diff --git a/src/uu/numfmt/src/options.rs b/src/uu/numfmt/src/options.rs index dc2b73925..79d7461ae 100644 --- a/src/uu/numfmt/src/options.rs +++ b/src/uu/numfmt/src/options.rs @@ -128,9 +128,9 @@ impl FromStr for FormatOptions { if iter.peek().is_none() { return if options.prefix == s { - Err(format!("format '{}' has no % directive", s)) + Err(format!("format '{s}' has no % directive")) } else { - Err(format!("format '{}' ends in %", s)) + Err(format!("format '{s}' ends in %")) }; } @@ -151,8 +151,7 @@ impl FromStr for FormatOptions { Some(c) if c.is_ascii_digit() => padding.push('-'), _ => { return Err(format!( - "invalid format '{}', directive must be %[0]['][-][N][.][N]f", - s + "invalid format '{s}', directive must be %[0]['][-][N][.][N]f" )) } } @@ -171,7 +170,7 @@ impl FromStr for FormatOptions { if let Ok(p) = padding.parse() { options.padding = Some(p); } else { - return Err(format!("invalid format '{}' (width overflow)", s)); + return Err(format!("invalid format '{s}' (width overflow)")); } } @@ -179,7 +178,7 @@ impl FromStr for FormatOptions { iter.next(); if matches!(iter.peek(), Some(' ' | '+' | '-')) { - return Err(format!("invalid precision in format '{}'", s)); + return Err(format!("invalid precision in format '{s}'")); } while let Some(c) = iter.peek() { @@ -195,7 +194,7 @@ impl FromStr for FormatOptions { if let Ok(p) = precision.parse() { options.precision = Some(p); } else { - return Err(format!("invalid precision in format '{}'", s)); + return Err(format!("invalid precision in format '{s}'")); } } else { options.precision = Some(0); @@ -206,8 +205,7 @@ impl FromStr for FormatOptions { iter.next(); } else { return Err(format!( - "invalid format '{}', directive must be %[0]['][-][N][.][N]f", - s + "invalid format '{s}', directive must be %[0]['][-][N][.][N]f" )); } @@ -222,7 +220,7 @@ impl FromStr for FormatOptions { } iter.next(); } else { - return Err(format!("format '{}' has too many % directives", s)); + return Err(format!("format '{s}' has too many % directives")); } } diff --git a/src/uu/od/src/formatteriteminfo.rs b/src/uu/od/src/formatteriteminfo.rs index 6d51fa3a3..00ee2ee20 100644 --- a/src/uu/od/src/formatteriteminfo.rs +++ b/src/uu/od/src/formatteriteminfo.rs @@ -22,9 +22,9 @@ impl PartialEq for FormatWriter { use crate::formatteriteminfo::FormatWriter::*; match (self, other) { - (&IntWriter(ref a), &IntWriter(ref b)) => a == b, - (&FloatWriter(ref a), &FloatWriter(ref b)) => a == b, - (&MultibyteWriter(ref a), &MultibyteWriter(ref b)) => *a as usize == *b as usize, + (IntWriter(a), IntWriter(b)) => a == b, + (FloatWriter(a), FloatWriter(b)) => a == b, + (MultibyteWriter(a), MultibyteWriter(b)) => *a as usize == *b as usize, _ => false, } } diff --git a/src/uu/od/src/inputdecoder.rs b/src/uu/od/src/inputdecoder.rs index c347ccc10..31e833698 100644 --- a/src/uu/od/src/inputdecoder.rs +++ b/src/uu/od/src/inputdecoder.rs @@ -136,7 +136,7 @@ impl<'a> MemoryDecoder<'a> { 2 => u64::from(self.byte_order.read_u16(&self.data[start..start + 2])), 4 => u64::from(self.byte_order.read_u32(&self.data[start..start + 4])), 8 => self.byte_order.read_u64(&self.data[start..start + 8]), - _ => panic!("Invalid byte_size: {}", byte_size), + _ => panic!("Invalid byte_size: {byte_size}"), } } @@ -148,7 +148,7 @@ impl<'a> MemoryDecoder<'a> { )), 4 => f64::from(self.byte_order.read_f32(&self.data[start..start + 4])), 8 => self.byte_order.read_f64(&self.data[start..start + 8]), - _ => panic!("Invalid byte_size: {}", byte_size), + _ => panic!("Invalid byte_size: {byte_size}"), } } } diff --git a/src/uu/od/src/inputoffset.rs b/src/uu/od/src/inputoffset.rs index 8aadf969d..ddaf747f1 100644 --- a/src/uu/od/src/inputoffset.rs +++ b/src/uu/od/src/inputoffset.rs @@ -50,7 +50,7 @@ impl InputOffset { (Radix::Octal, None) => format!("{:07o}", self.byte_pos), (Radix::Octal, Some(l)) => format!("{:07o} ({:07o})", self.byte_pos, l), (Radix::NoPrefix, None) => String::new(), - (Radix::NoPrefix, Some(l)) => format!("({:07o})", l), + (Radix::NoPrefix, Some(l)) => format!("({l:07o})"), } } diff --git a/src/uu/od/src/od.rs b/src/uu/od/src/od.rs index 63641d671..77480cb38 100644 --- a/src/uu/od/src/od.rs +++ b/src/uu/od/src/od.rs @@ -131,7 +131,7 @@ impl OdOptions { _ => { return Err(USimpleError::new( 1, - format!("Invalid argument --endian={}", s), + format!("Invalid argument --endian={s}"), )) } } @@ -155,7 +155,7 @@ impl OdOptions { let mut label: Option = None; let parsed_input = parse_inputs(matches) - .map_err(|e| USimpleError::new(1, format!("Invalid inputs: {}", e)))?; + .map_err(|e| USimpleError::new(1, format!("Invalid inputs: {e}")))?; let input_strings = match parsed_input { CommandLineInputs::FileNames(v) => v, CommandLineInputs::FileAndOffset((f, s, l)) => { @@ -173,7 +173,7 @@ impl OdOptions { if matches.value_source(options::WIDTH) == Some(ValueSource::CommandLine) { match parse_number_of_bytes(s) { Ok(n) => usize::try_from(n) - .map_err(|_| USimpleError::new(1, format!("‘{}‘ is too large", s)))?, + .map_err(|_| USimpleError::new(1, format!("‘{s}‘ is too large")))?, Err(e) => { return Err(USimpleError::new( 1, @@ -625,15 +625,15 @@ fn print_bytes(prefix: &str, input_decoder: &MemoryDecoder, output_info: &Output } if first { - print!("{}", prefix); // print offset - // if printing in multiple formats offset is printed only once + print!("{prefix}"); // print offset + // if printing in multiple formats offset is printed only once first = false; } else { // this takes the space of the file offset on subsequent // lines of multi-format rasters. print!("{:>width$}", "", width = prefix.chars().count()); } - println!("{}", output_text); + println!("{output_text}"); } } diff --git a/src/uu/od/src/prn_char.rs b/src/uu/od/src/prn_char.rs index 742229dd7..495b8eace 100644 --- a/src/uu/od/src/prn_char.rs +++ b/src/uu/od/src/prn_char.rs @@ -48,8 +48,8 @@ fn format_item_c(bytes: &[u8]) -> String { if b & 0x80 == 0x00 { match C_CHARS.get(b as usize) { - Some(s) => format!("{:>4}", s), - None => format!("{:>4}", b), + Some(s) => format!("{s:>4}"), + None => format!("{b:>4}"), } } else if (b & 0xc0) == 0x80 { // second or subsequent octet of an utf-8 sequence @@ -57,24 +57,24 @@ fn format_item_c(bytes: &[u8]) -> String { } else if ((b & 0xe0) == 0xc0) && (bytes.len() >= 2) { // start of a 2 octet utf-8 sequence match from_utf8(&bytes[0..2]) { - Ok(s) => format!("{:>4}", s), - Err(_) => format!(" {:03o}", b), + Ok(s) => format!("{s:>4}"), + Err(_) => format!(" {b:03o}"), } } else if ((b & 0xf0) == 0xe0) && (bytes.len() >= 3) { // start of a 3 octet utf-8 sequence match from_utf8(&bytes[0..3]) { - Ok(s) => format!("{:>4}", s), - Err(_) => format!(" {:03o}", b), + Ok(s) => format!("{s:>4}"), + Err(_) => format!(" {b:03o}"), } } else if ((b & 0xf8) == 0xf0) && (bytes.len() >= 4) { // start of a 4 octet utf-8 sequence match from_utf8(&bytes[0..4]) { - Ok(s) => format!("{:>4}", s), - Err(_) => format!(" {:03o}", b), + Ok(s) => format!("{s:>4}"), + Err(_) => format!(" {b:03o}"), } } else { // invalid utf-8 - format!(" {:03o}", b) + format!(" {b:03o}") } } diff --git a/src/uu/od/src/prn_float.rs b/src/uu/od/src/prn_float.rs index c92b1f75f..be1463163 100644 --- a/src/uu/od/src/prn_float.rs +++ b/src/uu/od/src/prn_float.rs @@ -47,7 +47,7 @@ fn format_flo32(f: f32) -> String { if f.classify() == FpCategory::Subnormal { // subnormal numbers will be normal as f64, so will print with a wrong precision - format!("{:width$e}", f) // subnormal numbers + format!("{f:width$e}") // subnormal numbers } else { format_float(f64::from(f), width, precision) } @@ -63,9 +63,9 @@ fn format_float(f: f64, width: usize, precision: usize) -> String { return format!("{:>width$}", "-0"); } if f == 0.0 || !f.is_finite() { - return format!("{:width$}", f); + return format!("{f:width$}"); } - return format!("{:width$e}", f); // subnormal numbers + return format!("{f:width$e}"); // subnormal numbers } let mut l = f.abs().log10().floor() as i32; @@ -79,7 +79,7 @@ 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) } else if l == -1 { - format!("{:width$.dec$}", f, dec = precision) + format!("{f:width$.precision$}") } else { format!("{:width$.dec$e}", f, dec = precision - 1) } diff --git a/src/uu/pathchk/src/pathchk.rs b/src/uu/pathchk/src/pathchk.rs index 626596ab0..6dad9f79d 100644 --- a/src/uu/pathchk/src/pathchk.rs +++ b/src/uu/pathchk/src/pathchk.rs @@ -132,10 +132,7 @@ fn check_basic(path: &[String]) -> bool { if total_len > POSIX_PATH_MAX { writeln!( std::io::stderr(), - "limit {} exceeded by length {} of file name {}", - POSIX_PATH_MAX, - total_len, - joined_path + "limit {POSIX_PATH_MAX} exceeded by length {total_len} of file name {joined_path}" ); return false; } else if total_len == 0 { @@ -226,7 +223,7 @@ fn check_searchable(path: &str) -> bool { if e.kind() == ErrorKind::NotFound { true } else { - writeln!(std::io::stderr(), "{}", e); + writeln!(std::io::stderr(), "{e}"); false } } diff --git a/src/uu/pinky/src/pinky.rs b/src/uu/pinky/src/pinky.rs index c4e68705e..8060565e4 100644 --- a/src/uu/pinky/src/pinky.rs +++ b/src/uu/pinky/src/pinky.rs @@ -241,11 +241,11 @@ fn idle_string(when: i64) -> String { // less than 1day let hours = duration / (60 * 60); let minutes = (duration % (60 * 60)) / 60; - format!("{:02}:{:02}", hours, minutes) + format!("{hours:02}:{minutes:02}") } else { // more than 1day let days = duration / (24 * 3600); - format!("{}d", days) + format!("{days}d") } }) } @@ -303,7 +303,7 @@ impl Pinky { None }; if let Some(fullname) = fullname { - print!(" {:<19.19}", fullname); + print!(" {fullname:<19.19}"); } else { print!(" {:19}", " ???"); } @@ -324,7 +324,7 @@ impl Pinky { let mut s = ut.host(); if self.include_where && !s.is_empty() { s = ut.canon_host()?; - print!(" {}", s); + print!(" {s}"); } println!(); @@ -363,15 +363,15 @@ impl Pinky { fn long_pinky(&self) { for u in &self.names { - print!("Login name: {:<28}In real life: ", u); + print!("Login name: {u:<28}In real life: "); if let Ok(pw) = Passwd::locate(u.as_str()) { let fullname = gecos_to_fullname(&pw).unwrap_or_default(); let user_dir = pw.user_dir.unwrap_or_default(); let user_shell = pw.user_shell.unwrap_or_default(); - println!(" {}", fullname); + println!(" {fullname}"); if self.include_home_and_shell { - print!("Directory: {:<29}", user_dir); - println!("Shell: {}", user_shell); + print!("Directory: {user_dir:<29}"); + println!("Shell: {user_shell}"); } if self.include_project { let mut p = PathBuf::from(&user_dir); diff --git a/src/uu/pr/src/pr.rs b/src/uu/pr/src/pr.rs index 231e07766..9f1b64483 100644 --- a/src/uu/pr/src/pr.rs +++ b/src/uu/pr/src/pr.rs @@ -491,7 +491,7 @@ fn recreate_arguments(args: &[String]) -> Vec { fn print_error(matches: &ArgMatches, err: &PrError) { if !matches.get_flag(options::NO_FILE_WARNINGS) { - eprintln!("{}", err); + eprintln!("{err}"); } } @@ -505,7 +505,7 @@ fn parse_usize(matches: &ArgMatches, opt: &str) -> Option }; matches .get_one::(opt) - .map(|i| (i.to_string(), format!("-{}", opt))) + .map(|i| (i.to_string(), format!("-{opt}"))) .map(from_parse_error_to_pr_error) } @@ -668,8 +668,7 @@ fn build_options( if let Some(end_page) = end_page { if start_page > end_page { return Err(PrError::EncounteredErrors(format!( - "invalid --pages argument '{}:{}'", - start_page, end_page + "invalid --pages argument '{start_page}:{end_page}'" ))); } } @@ -1203,7 +1202,7 @@ fn get_formatted_line_number(opts: &OutputOptions, line_number: usize, index: us separator ) } else { - format!("{:>width$}{}", line_str, separator) + format!("{line_str:>width$}{separator}") } } else { String::new() diff --git a/src/uu/printenv/src/printenv.rs b/src/uu/printenv/src/printenv.rs index 3e7a7c5f9..dd58f4ee1 100644 --- a/src/uu/printenv/src/printenv.rs +++ b/src/uu/printenv/src/printenv.rs @@ -35,7 +35,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { if variables.is_empty() { for (env_var, value) in env::vars() { - print!("{}={}{}", env_var, value, separator); + print!("{env_var}={value}{separator}"); } return Ok(()); } @@ -48,7 +48,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { continue; } if let Ok(var) = env::var(env_var) { - print!("{}{}", var, separator); + print!("{var}{separator}"); } else { error_found = true; } diff --git a/src/uu/ptx/src/ptx.rs b/src/uu/ptx/src/ptx.rs index 5d8bc7314..3790c4e11 100644 --- a/src/uu/ptx/src/ptx.rs +++ b/src/uu/ptx/src/ptx.rs @@ -170,7 +170,7 @@ impl WordFilter { .unwrap() .into_iter() .map(|c| if REGEX_CHARCLASS.contains(c) { - format!("\\{}", c) + format!("\\{c}") } else { c.to_string() }) @@ -220,7 +220,7 @@ impl Display for PtxError { Self::DumbFormat => { write!(f, "There is no dumb format with GNU extensions disabled") } - Self::NotImplemented(s) => write!(f, "{} not implemented yet", s), + Self::NotImplemented(s) => write!(f, "{s} not implemented yet"), Self::ParseError(e) => e.fmt(f), } } @@ -553,8 +553,8 @@ fn get_output_chunks( fn tex_mapper(x: char) -> String { match x { '\\' => "\\backslash{}".to_owned(), - '$' | '%' | '#' | '&' | '_' => format!("\\{}", x), - '}' | '{' => format!("$\\{}$", x), + '$' | '%' | '#' | '&' | '_' => format!("\\{x}"), + '}' | '{' => format!("$\\{x}$"), _ => x.to_string(), } } @@ -696,7 +696,7 @@ fn write_traditional_output( return Err(PtxError::DumbFormat.into()); } }; - writeln!(writer, "{}", output_line).map_err_context(String::new)?; + writeln!(writer, "{output_line}").map_err_context(String::new)?; } Ok(()) } diff --git a/src/uu/readlink/src/readlink.rs b/src/uu/readlink/src/readlink.rs index a0be0d270..8afb184be 100644 --- a/src/uu/readlink/src/readlink.rs +++ b/src/uu/readlink/src/readlink.rs @@ -176,11 +176,11 @@ pub fn uu_app() -> Command { fn show(path: &Path, no_trailing_delimiter: bool, use_zero: bool) -> std::io::Result<()> { let path = path.to_str().unwrap(); if no_trailing_delimiter { - print!("{}", path); + print!("{path}"); } else if use_zero { - print!("{}\0", path); + print!("{path}\0"); } else { - println!("{}", path); + println!("{path}"); } stdout().flush() } diff --git a/src/uu/rm/src/rm.rs b/src/uu/rm/src/rm.rs index 08d7f0ac5..39b177bcf 100644 --- a/src/uu/rm/src/rm.rs +++ b/src/uu/rm/src/rm.rs @@ -117,7 +117,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { val => { return Err(USimpleError::new( 1, - format!("Invalid argument to interactive ({})", val), + format!("Invalid argument to interactive ({val})"), )) } } diff --git a/src/uu/runcon/src/errors.rs b/src/uu/runcon/src/errors.rs index 18f06deb9..b96cc8743 100644 --- a/src/uu/runcon/src/errors.rs +++ b/src/uu/runcon/src/errors.rs @@ -77,11 +77,11 @@ pub(crate) fn write_full_error(writer: &mut W, err: &dyn std::error::Error) - where W: Write, { - write!(writer, "{}", err)?; + write!(writer, "{err}")?; let mut err = err; while let Some(source) = err.source() { err = source; - write!(writer, ": {}", err)?; + write!(writer, ": {err}")?; } write!(writer, ".")?; Ok(()) diff --git a/src/uu/runcon/src/runcon.rs b/src/uu/runcon/src/runcon.rs index 101cd3bee..365038907 100644 --- a/src/uu/runcon/src/runcon.rs +++ b/src/uu/runcon/src/runcon.rs @@ -52,7 +52,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { match r.kind() { clap::error::ErrorKind::DisplayHelp | clap::error::ErrorKind::DisplayVersion => { - println!("{}", r); + println!("{r}"); return Ok(()); } _ => {} @@ -60,7 +60,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { } return Err(UUsageError::new( error_exit_status::ANOTHER_ERROR, - format!("{}", r), + format!("{r}"), )); } }; @@ -264,7 +264,7 @@ fn print_current_context() -> Result<()> { if let Some(context) = context { let context = context.as_ref().to_str()?; - println!("{}", context); + println!("{context}"); } else { println!(); } diff --git a/src/uu/seq/src/seq.rs b/src/uu/seq/src/seq.rs index e5784d771..40bac8449 100644 --- a/src/uu/seq/src/seq.rs +++ b/src/uu/seq/src/seq.rs @@ -214,7 +214,7 @@ fn write_value_float( } else { format!("{value:>0width$.precision$}") }; - write!(writer, "{}", value_as_str) + write!(writer, "{value_as_str}") } /// Write a big int formatted according to the given parameters. @@ -232,11 +232,11 @@ fn write_value_int( format!("{value:>0width$}") } } else if *value == ExtendedBigInt::MinusZero && is_first_iteration { - format!("-{}", value) + format!("-{value}") } else { - format!("{}", value) + format!("{value}") }; - write!(writer, "{}", value_as_str) + write!(writer, "{value_as_str}") } // TODO `print_seq()` and `print_seq_integers()` are nearly identical, @@ -260,7 +260,7 @@ fn print_seq( let mut is_first_iteration = true; while !done_printing(&value, &increment, &last) { if !is_first_iteration { - write!(stdout, "{}", separator)?; + write!(stdout, "{separator}")?; } // If there was an argument `-f FORMAT`, then use that format // template instead of the default formatting strategy. @@ -276,7 +276,7 @@ fn print_seq( // strings. match format { Some(f) => { - let s = format!("{}", value); + let s = format!("{value}"); if let Err(x) = printf(f, &[s]) { show!(x); exit(1); @@ -295,7 +295,7 @@ fn print_seq( is_first_iteration = false; } if !is_first_iteration { - write!(stdout, "{}", terminator)?; + write!(stdout, "{terminator}")?; } stdout.flush()?; Ok(()) @@ -330,7 +330,7 @@ fn print_seq_integers( let mut is_first_iteration = true; while !done_printing(&value, &increment, &last) { if !is_first_iteration { - write!(stdout, "{}", separator)?; + write!(stdout, "{separator}")?; } // If there was an argument `-f FORMAT`, then use that format // template instead of the default formatting strategy. @@ -341,7 +341,7 @@ fn print_seq_integers( // TODO See similar comment about formatting in `print_seq()`. match format { Some(f) => { - let s = format!("{}", value); + let s = format!("{value}"); if let Err(x) = printf(f, &[s]) { show!(x); exit(1); @@ -355,7 +355,7 @@ fn print_seq_integers( } if !is_first_iteration { - write!(stdout, "{}", terminator)?; + write!(stdout, "{terminator}")?; } Ok(()) } diff --git a/src/uu/shred/src/shred.rs b/src/uu/shred/src/shred.rs index de1af9e30..55a36bfe2 100644 --- a/src/uu/shred/src/shred.rs +++ b/src/uu/shred/src/shred.rs @@ -16,7 +16,6 @@ use std::fs; use std::fs::{File, OpenOptions}; use std::io; use std::io::prelude::*; -use std::io::SeekFrom; use std::path::{Path, PathBuf}; use uucore::display::Quotable; use uucore::error::{FromIo, UResult, USimpleError, UUsageError}; @@ -424,7 +423,7 @@ fn pass_name(pass_type: PassType) -> String { let mut s: String = String::new(); while s.len() < 6 { for b in bytes { - let readable: String = format!("{:x}", b); + let readable: String = format!("{b:x}"); s.push_str(&readable); } } @@ -560,7 +559,7 @@ fn do_pass<'a>( generator_type: PassType<'a>, given_file_size: Option, ) -> Result<(), io::Error> { - file.seek(SeekFrom::Start(0))?; + file.rewind()?; // Use the given size or the whole file if not specified let size: u64 = given_file_size.unwrap_or(get_file_size(path)?); diff --git a/src/uu/shuf/src/rand_read_adapter.rs b/src/uu/shuf/src/rand_read_adapter.rs index fd8998c10..9cf0ee8a4 100644 --- a/src/uu/shuf/src/rand_read_adapter.rs +++ b/src/uu/shuf/src/rand_read_adapter.rs @@ -54,10 +54,7 @@ impl RngCore for ReadRng { fn fill_bytes(&mut self, dest: &mut [u8]) { self.try_fill_bytes(dest).unwrap_or_else(|err| { - panic!( - "reading random bytes from Read implementation failed; error: {}", - err - ); + panic!("reading random bytes from Read implementation failed; error: {err}"); }); } diff --git a/src/uu/shuf/src/shuf.rs b/src/uu/shuf/src/shuf.rs index b9e296686..d0022f5f5 100644 --- a/src/uu/shuf/src/shuf.rs +++ b/src/uu/shuf/src/shuf.rs @@ -109,7 +109,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { shuf_bytes(&mut evec, options)?; } Mode::InputRange((b, e)) => { - let rvec = (b..e).map(|x| format!("{}", x)).collect::>(); + let rvec = (b..e).map(|x| format!("{x}")).collect::>(); let mut rvec = rvec.iter().map(String::as_bytes).collect::>(); shuf_bytes(&mut rvec, options)?; } diff --git a/src/uu/sort/src/ext_sort.rs b/src/uu/sort/src/ext_sort.rs index fbb9c16d7..45ddc7304 100644 --- a/src/uu/sort/src/ext_sort.rs +++ b/src/uu/sort/src/ext_sort.rs @@ -278,7 +278,7 @@ fn write( tmp_file.finished_writing() } -fn write_lines<'a, T: Write>(lines: &[Line<'a>], writer: &mut T, separator: u8) { +fn write_lines(lines: &[Line], writer: &mut T, separator: u8) { for s in lines { writer.write_all(s.line.as_bytes()).unwrap(); writer.write_all(&[separator]).unwrap(); diff --git a/src/uu/sort/src/sort.rs b/src/uu/sort/src/sort.rs index 99f824982..a681026f6 100644 --- a/src/uu/sort/src/sort.rs +++ b/src/uu/sort/src/sort.rs @@ -220,13 +220,13 @@ impl Display for SortError { write!(f, "failed to open temporary file: {}", strip_errno(error)) } Self::CompressProgExecutionFailed { code } => { - write!(f, "couldn't execute compress program: errno {}", code) + write!(f, "couldn't execute compress program: errno {code}") } Self::CompressProgTerminatedAbnormally { prog } => { write!(f, "{} terminated abnormally", prog.quote()) } Self::TmpDirCreationFailed => write!(f, "could not create temporary directory"), - Self::Uft8Error { error } => write!(f, "{}", error), + Self::Uft8Error { error } => write!(f, "{error}"), } } } @@ -351,10 +351,7 @@ impl GlobalSettings { .parse(input.trim())?; usize::try_from(size).map_err(|_| { - ParseSizeError::SizeTooBig(format!( - "Buffer size {} does not fit in address space", - size - )) + ParseSizeError::SizeTooBig(format!("Buffer size {size} does not fit in address space")) }) } @@ -563,7 +560,7 @@ impl<'a> Line<'a> { // optimizations here. let line = self.line.replace('\t', ">"); - writeln!(writer, "{}", line)?; + writeln!(writer, "{line}")?; let mut fields = vec![]; tokenize(self.line, settings.separator, &mut fields); @@ -866,7 +863,7 @@ impl FieldSelector { 'R' => key_settings.set_sort_mode(SortMode::Random)?, 'r' => key_settings.reverse = true, 'V' => key_settings.set_sort_mode(SortMode::Version)?, - c => return Err(format!("invalid option: '{}'", c)), + c => return Err(format!("invalid option: '{c}'")), } } Ok(ignore_blanks) @@ -942,7 +939,7 @@ impl FieldSelector { /// Look up the range in the line that corresponds to this selector. /// If needs_fields returned false, tokens must be None. - fn get_range<'a>(&self, line: &'a str, tokens: Option<&[Field]>) -> Range { + fn get_range(&self, line: &str, tokens: Option<&[Field]>) -> Range { enum Resolution { // The start index of the resolved character, inclusive StartOfChar(usize), diff --git a/src/uu/sort/src/tmp_dir.rs b/src/uu/sort/src/tmp_dir.rs index 0f6c76677..ff14442b5 100644 --- a/src/uu/sort/src/tmp_dir.rs +++ b/src/uu/sort/src/tmp_dir.rs @@ -56,7 +56,7 @@ impl TmpDirWrapper { } std::process::exit(2) }) - .map_err(|e| USimpleError::new(2, format!("failed to set up signal handler: {}", e))) + .map_err(|e| USimpleError::new(2, format!("failed to set up signal handler: {e}"))) } pub fn next_file(&mut self) -> UResult<(File, PathBuf)> { diff --git a/src/uu/split/src/number.rs b/src/uu/split/src/number.rs index 00a536af5..778e24f7c 100644 --- a/src/uu/split/src/number.rs +++ b/src/uu/split/src/number.rs @@ -245,7 +245,7 @@ impl Display for FixedWidthNumber { .iter() .map(|d| map_digit(self.radix, *d)) .collect(); - write!(f, "{}", digits) + write!(f, "{digits}") } } diff --git a/src/uu/split/src/platform/unix.rs b/src/uu/split/src/platform/unix.rs index 46f89eff5..fedd66dc8 100644 --- a/src/uu/split/src/platform/unix.rs +++ b/src/uu/split/src/platform/unix.rs @@ -121,7 +121,7 @@ pub fn instantiate_current_writer( .map_err(|_| { Error::new( ErrorKind::Other, - format!("unable to open '{}'; aborting", filename), + format!("unable to open '{filename}'; aborting"), ) })?, ) as Box)), diff --git a/src/uu/split/src/platform/windows.rs b/src/uu/split/src/platform/windows.rs index 4b0dfbdfc..a2711fd3a 100644 --- a/src/uu/split/src/platform/windows.rs +++ b/src/uu/split/src/platform/windows.rs @@ -21,7 +21,7 @@ pub fn instantiate_current_writer( .map_err(|_| { Error::new( ErrorKind::Other, - format!("'{}' would overwrite input; aborting", filename), + format!("'{filename}' would overwrite input; aborting"), ) })?, ) as Box)) diff --git a/src/uu/split/src/split.rs b/src/uu/split/src/split.rs index 36200b2bd..d737c8513 100644 --- a/src/uu/split/src/split.rs +++ b/src/uu/split/src/split.rs @@ -58,8 +58,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let matches = uu_app().try_get_matches_from(args)?; match Settings::from(&matches) { Ok(settings) => split(&settings), - Err(e) if e.requires_usage() => Err(UUsageError::new(1, format!("{}", e))), - Err(e) => Err(USimpleError::new(1, format!("{}", e))), + Err(e) if e.requires_usage() => Err(UUsageError::new(1, format!("{e}"))), + Err(e) => Err(USimpleError::new(1, format!("{e}"))), } } @@ -343,13 +343,13 @@ enum StrategyError { impl fmt::Display for StrategyError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - Self::Lines(e) => write!(f, "invalid number of lines: {}", e), - Self::Bytes(e) => write!(f, "invalid number of bytes: {}", e), + Self::Lines(e) => write!(f, "invalid number of lines: {e}"), + Self::Bytes(e) => write!(f, "invalid number of bytes: {e}"), Self::NumberType(NumberTypeError::NumberOfChunks(s)) => { - write!(f, "invalid number of chunks: {}", s) + write!(f, "invalid number of chunks: {s}") } Self::NumberType(NumberTypeError::ChunkNumber(s)) => { - write!(f, "invalid chunk number: {}", s) + write!(f, "invalid chunk number: {s}") } Self::MultipleWays => write!(f, "cannot split in more than one way"), } @@ -478,7 +478,7 @@ impl fmt::Display for SettingsError { match self { Self::Strategy(e) => e.fmt(f), Self::SuffixNotParsable(s) => write!(f, "invalid suffix length: {}", s.quote()), - Self::SuffixTooSmall(i) => write!(f, "the suffix length needs to be at least {}", i), + Self::SuffixTooSmall(i) => write!(f, "the suffix length needs to be at least {i}"), Self::SuffixContainsSeparator(s) => write!( f, "invalid suffix {}, contains directory separator", @@ -487,8 +487,7 @@ impl fmt::Display for SettingsError { #[cfg(windows)] Self::NotSupported => write!( f, - "{} is currently not supported in this platform", - OPT_FILTER + "{OPT_FILTER} is currently not supported in this platform" ), } } @@ -547,7 +546,7 @@ impl Settings { if platform::paths_refer_to_same_file(&self.input, filename) { return Err(io::Error::new( ErrorKind::Other, - format!("'{}' would overwrite input; aborting", filename), + format!("'{filename}' would overwrite input; aborting"), )); } @@ -1305,7 +1304,7 @@ fn split(settings: &Settings) -> UResult<()> { // allowable filenames, we use `ErrorKind::Other` to // indicate that. A special error message needs to be // printed in that case. - ErrorKind::Other => Err(USimpleError::new(1, format!("{}", e))), + ErrorKind::Other => Err(USimpleError::new(1, format!("{e}"))), ErrorKind::BrokenPipe => Ok(()), _ => Err(uio_error!(e, "input/output error")), }, @@ -1324,7 +1323,7 @@ fn split(settings: &Settings) -> UResult<()> { // allowable filenames, we use `ErrorKind::Other` to // indicate that. A special error message needs to be // printed in that case. - ErrorKind::Other => Err(USimpleError::new(1, format!("{}", e))), + ErrorKind::Other => Err(USimpleError::new(1, format!("{e}"))), ErrorKind::BrokenPipe => Ok(()), _ => Err(uio_error!(e, "input/output error")), }, @@ -1343,7 +1342,7 @@ fn split(settings: &Settings) -> UResult<()> { // allowable filenames, we use `ErrorKind::Other` to // indicate that. A special error message needs to be // printed in that case. - ErrorKind::Other => Err(USimpleError::new(1, format!("{}", e))), + ErrorKind::Other => Err(USimpleError::new(1, format!("{e}"))), ErrorKind::BrokenPipe => Ok(()), _ => Err(uio_error!(e, "input/output error")), }, diff --git a/src/uu/stat/src/stat.rs b/src/uu/stat/src/stat.rs index 8fd9fecfa..119c9c7fb 100644 --- a/src/uu/stat/src/stat.rs +++ b/src/uu/stat/src/stat.rs @@ -535,7 +535,7 @@ impl Stater { for t in tokens.iter() { match *t { - Token::Char(c) => print!("{}", c), + Token::Char(c) => print!("{c}"), Token::Directive { flag, width, @@ -588,7 +588,7 @@ impl Stater { let dst = match fs::read_link(&file) { Ok(path) => path, Err(e) => { - println!("{}", e); + println!("{e}"); return 1; } }; @@ -668,7 +668,7 @@ impl Stater { for t in tokens.iter() { match *t { - Token::Char(c) => print!("{}", c), + Token::Char(c) => print!("{c}"), Token::Directive { flag, width, diff --git a/src/uu/stdbuf/src/stdbuf.rs b/src/uu/stdbuf/src/stdbuf.rs index 97e06ad19..2bfb6f908 100644 --- a/src/uu/stdbuf/src/stdbuf.rs +++ b/src/uu/stdbuf/src/stdbuf.rs @@ -120,8 +120,7 @@ fn check_option(matches: &ArgMatches, name: &str) -> Result UResult<()> { if let ControlFlow::Break(false) = apply_setting(&mut termios, setting) { return Err(USimpleError::new( 1, - format!("invalid argument '{}'", setting), + format!("invalid argument '{setting}'"), )); } } @@ -195,7 +195,7 @@ fn print_terminal_size(termios: &Termios, opts: &Options) -> nix::Result<()> { target_os = "netbsd", target_os = "openbsd" ))] - print!("speed {} baud; ", speed); + print!("speed {speed} baud; "); // Other platforms need to use the baud rate enum, so printing the right value // becomes slightly more complicated. @@ -209,7 +209,7 @@ fn print_terminal_size(termios: &Termios, opts: &Options) -> nix::Result<()> { )))] for (text, baud_rate) in BAUD_RATES { if *baud_rate == speed { - print!("speed {} baud; ", text); + print!("speed {text} baud; "); break; } } @@ -226,7 +226,7 @@ fn print_terminal_size(termios: &Termios, opts: &Options) -> nix::Result<()> { // so we get the underlying libc::termios struct to get that information. let libc_termios: nix::libc::termios = termios.clone().into(); let line = libc_termios.c_line; - print!("line = {};", line); + print!("line = {line};"); } println!(); @@ -258,14 +258,14 @@ fn print_flags(termios: &Termios, opts: &Options, flags: &[Flag< let val = flag.is_in(termios, group); if group.is_some() { if val && (!sane || opts.all) { - print!("{} ", name); + print!("{name} "); printed = true; } } else if opts.all || val != sane { if !val { print!("-"); } - print!("{} ", name); + print!("{name} "); printed = true; } } diff --git a/src/uu/sum/src/sum.rs b/src/uu/sum/src/sum.rs index 54c254faa..1134f2444 100644 --- a/src/uu/sum/src/sum.rs +++ b/src/uu/sum/src/sum.rs @@ -134,9 +134,9 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { }; if print_names { - println!("{:0width$} {:width$} {}", sum, blocks, file); + println!("{sum:0width$} {blocks:width$} {file}"); } else { - println!("{:0width$} {:width$}", sum, blocks); + println!("{sum:0width$} {blocks:width$}"); } } Ok(()) diff --git a/src/uu/tac/src/error.rs b/src/uu/tac/src/error.rs index 52c668516..43b03b970 100644 --- a/src/uu/tac/src/error.rs +++ b/src/uu/tac/src/error.rs @@ -44,7 +44,7 @@ impl Error for TacError {} impl Display for TacError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Self::InvalidRegex(e) => write!(f, "invalid regular expression: {}", e), + Self::InvalidRegex(e) => write!(f, "invalid regular expression: {e}"), Self::InvalidArgument(s) => { write!(f, "{}: read error: Invalid argument", s.maybe_quote()) } @@ -53,8 +53,8 @@ impl Display for TacError { "failed to open {} for reading: No such file or directory", s.quote() ), - Self::ReadError(s, e) => write!(f, "failed to read from {}: {}", s, e), - Self::WriteError(e) => write!(f, "failed to write to stdout: {}", e), + Self::ReadError(s, e) => write!(f, "failed to read from {s}: {e}"), + Self::WriteError(e) => write!(f, "failed to write to stdout: {e}"), } } } diff --git a/src/uu/tail/src/args.rs b/src/uu/tail/src/args.rs index 6e972d25f..5f7ea1028 100644 --- a/src/uu/tail/src/args.rs +++ b/src/uu/tail/src/args.rs @@ -69,12 +69,7 @@ impl FilterMode { let mode = if let Some(arg) = matches.get_one::(options::BYTES) { match parse_num(arg) { Ok(signum) => Self::Bytes(signum), - Err(e) => { - return Err(UUsageError::new( - 1, - format!("invalid number of bytes: {}", e), - )) - } + Err(e) => return Err(UUsageError::new(1, format!("invalid number of bytes: {e}"))), } } else if let Some(arg) = matches.get_one::(options::LINES) { match parse_num(arg) { @@ -82,12 +77,7 @@ impl FilterMode { let delimiter = if zero_term { 0 } else { b'\n' }; Self::Lines(signum, delimiter) } - Err(e) => { - return Err(UUsageError::new( - 1, - format!("invalid number of lines: {}", e), - )) - } + Err(e) => return Err(UUsageError::new(1, format!("invalid number of lines: {e}"))), } } else if zero_term { Self::default_zero() diff --git a/src/uu/tail/src/chunks.rs b/src/uu/tail/src/chunks.rs index 7ad2e153b..4b934c1d7 100644 --- a/src/uu/tail/src/chunks.rs +++ b/src/uu/tail/src/chunks.rs @@ -48,7 +48,7 @@ pub struct ReverseChunks<'a> { impl<'a> ReverseChunks<'a> { pub fn new(file: &'a mut File) -> ReverseChunks<'a> { let current = if cfg!(unix) { - file.seek(SeekFrom::Current(0)).unwrap() + file.stream_position().unwrap() } else { 0 }; diff --git a/src/uu/tail/src/follow/watch.rs b/src/uu/tail/src/follow/watch.rs index 31a6d70cb..2c3cf10b8 100644 --- a/src/uu/tail/src/follow/watch.rs +++ b/src/uu/tail/src/follow/watch.rs @@ -566,11 +566,11 @@ pub fn follow(mut observer: Observer, settings: &Settings) -> UResult<()> { format!("{} resources exhausted", text::BACKEND), )) } - Ok(Err(e)) => return Err(USimpleError::new(1, format!("NotifyError: {}", e))), + Ok(Err(e)) => return Err(USimpleError::new(1, format!("NotifyError: {e}"))), Err(mpsc::RecvTimeoutError::Timeout) => { _timeout_counter += 1; } - Err(e) => return Err(USimpleError::new(1, format!("RecvTimeoutError: {}", e))), + Err(e) => return Err(USimpleError::new(1, format!("RecvTimeoutError: {e}"))), } if observer.use_polling && settings.follow.is_some() { diff --git a/src/uu/tail/src/parse.rs b/src/uu/tail/src/parse.rs index 7511f2405..2129d8e29 100644 --- a/src/uu/tail/src/parse.rs +++ b/src/uu/tail/src/parse.rs @@ -78,10 +78,10 @@ pub fn parse_obsolete(src: &str) -> Option Some(n) => n, None => return Some(Err(ParseError::Overflow)), }; - options.push(OsString::from(format!("{}", num))); + options.push(OsString::from(format!("{num}"))); } else { options.push(OsString::from("-n")); - options.push(OsString::from(format!("{}", num))); + options.push(OsString::from(format!("{num}"))); } Some(Ok(options.into_iter())) } diff --git a/src/uu/tail/src/paths.rs b/src/uu/tail/src/paths.rs index 03656d036..d8e6ece9a 100644 --- a/src/uu/tail/src/paths.rs +++ b/src/uu/tail/src/paths.rs @@ -132,7 +132,7 @@ impl FileExtTail for File { /// Test if File is seekable. /// Set the current position offset to `current_offset`. fn is_seekable(&mut self, current_offset: u64) -> bool { - self.seek(SeekFrom::Current(0)).is_ok() + self.stream_position().is_ok() && self.seek(SeekFrom::End(0)).is_ok() && self.seek(SeekFrom::Start(current_offset)).is_ok() } diff --git a/src/uu/tail/src/tail.rs b/src/uu/tail/src/tail.rs index 2a5a94352..9e3273638 100644 --- a/src/uu/tail/src/tail.rs +++ b/src/uu/tail/src/tail.rs @@ -198,7 +198,7 @@ fn tail_stdin( // Save the current seek position/offset of a stdin redirected file. // This is needed to pass "gnu/tests/tail-2/start-middle.sh" if let Ok(mut stdin_handle) = Handle::stdin() { - if let Ok(offset) = stdin_handle.as_file_mut().seek(SeekFrom::Current(0)) { + if let Ok(offset) = stdin_handle.as_file_mut().stream_position() { stdin_offset = offset; } } diff --git a/src/uu/test/src/parser.rs b/src/uu/test/src/parser.rs index 1177f49ea..b76333930 100644 --- a/src/uu/test/src/parser.rs +++ b/src/uu/test/src/parser.rs @@ -142,7 +142,7 @@ impl Parser { fn expect(&mut self, value: &str) { match self.next_token() { Symbol::Literal(s) if s == value => (), - _ => panic!("expected ‘{}’", value), + _ => panic!("expected ‘{value}’"), } } @@ -383,7 +383,7 @@ impl Parser { let op = self.next_token(); match self.next_token() { - Symbol::None => panic!("missing argument after {:?}", op), + Symbol::None => panic!("missing argument after {op:?}"), token => self.stack.push(token.into_literal()), } diff --git a/src/uu/test/src/test.rs b/src/uu/test/src/test.rs index bc274bc8b..8ce4564a3 100644 --- a/src/uu/test/src/test.rs +++ b/src/uu/test/src/test.rs @@ -186,7 +186,7 @@ fn eval(stack: &mut Vec) -> Result { return Ok(true); } _ => { - return Err(format!("missing argument after '{:?}'", op)); + return Err(format!("missing argument after '{op:?}'")); } }; diff --git a/src/uu/timeout/src/timeout.rs b/src/uu/timeout/src/timeout.rs index 246537a30..26235e0df 100644 --- a/src/uu/timeout/src/timeout.rs +++ b/src/uu/timeout/src/timeout.rs @@ -314,7 +314,7 @@ fn timeout( // FIXME: this may not be 100% correct... 126 }; - USimpleError::new(status_code, format!("failed to execute process: {}", err)) + USimpleError::new(status_code, format!("failed to execute process: {err}")) })?; unblock_sigchld(); // Wait for the child process for the specified time period. @@ -355,7 +355,7 @@ fn timeout( Ok(status) => Err(status.into()), Err(e) => Err(USimpleError::new( ExitStatus::TimeoutFailed.into(), - format!("{}", e), + format!("{e}"), )), } } @@ -365,9 +365,9 @@ fn timeout( // We're going to return ERR_EXIT_STATUS regardless of // whether `send_signal()` succeeds or fails, so just // ignore the return value. - process.send_signal(signal).map_err(|e| { - USimpleError::new(ExitStatus::TimeoutFailed.into(), format!("{}", e)) - })?; + process + .send_signal(signal) + .map_err(|e| USimpleError::new(ExitStatus::TimeoutFailed.into(), format!("{e}")))?; Err(ExitStatus::TimeoutFailed.into()) } } diff --git a/src/uu/touch/src/touch.rs b/src/uu/touch/src/touch.rs index a50a00303..a7d3557bd 100644 --- a/src/uu/touch/src/touch.rs +++ b/src/uu/touch/src/touch.rs @@ -46,7 +46,7 @@ fn to_local(tm: time::PrimitiveDateTime) -> time::OffsetDateTime { let offset = match time::OffsetDateTime::now_local() { Ok(lo) => lo.offset(), Err(e) => { - panic!("error: {}", e); + panic!("error: {e}"); } }; tm.assume_offset(offset) @@ -438,7 +438,7 @@ fn parse_date(s: &str) -> UResult { return Ok(local_dt_to_filetime(diff)); } - Err(USimpleError::new(1, format!("Unable to parse date: {}", s))) + Err(USimpleError::new(1, format!("Unable to parse date: {s}"))) } fn parse_timestamp(s: &str) -> UResult { @@ -558,7 +558,7 @@ fn pathbuf_from_stdout() -> UResult { ERROR_PATH_NOT_FOUND | ERROR_NOT_ENOUGH_MEMORY | ERROR_INVALID_PARAMETER => { return Err(USimpleError::new( 1, - format!("GetFinalPathNameByHandleW failed with code {}", ret), + format!("GetFinalPathNameByHandleW failed with code {ret}"), )) } e if e == 0 => { diff --git a/src/uu/tr/src/operation.rs b/src/uu/tr/src/operation.rs index 0bc8005fe..03cea92e7 100644 --- a/src/uu/tr/src/operation.rs +++ b/src/uu/tr/src/operation.rs @@ -48,7 +48,7 @@ impl Display for BadSequence { writeln!(f, "the [c*] repeat construct may not appear in string1") } Self::InvalidRepeatCount(count) => { - writeln!(f, "invalid repeat count '{}' in [c*n] construct", count) + writeln!(f, "invalid repeat count '{count}' in [c*n] construct") } Self::EmptySet2WhenNotTruncatingSet1 => { writeln!(f, "when not truncating set1, string2 must be non-empty") diff --git a/src/uu/truncate/src/truncate.rs b/src/uu/truncate/src/truncate.rs index 517d766e3..5a5ef0a97 100644 --- a/src/uu/truncate/src/truncate.rs +++ b/src/uu/truncate/src/truncate.rs @@ -231,7 +231,7 @@ fn truncate_reference_and_size( create: bool, ) -> UResult<()> { let mode = match parse_mode_and_size(size_string) { - Err(e) => return Err(USimpleError::new(1, format!("Invalid number: {}", e))), + Err(e) => return Err(USimpleError::new(1, format!("Invalid number: {e}"))), Ok(TruncateMode::Absolute(_)) => { return Err(USimpleError::new( 1, @@ -338,7 +338,7 @@ fn truncate_reference_file_only( /// If at least one file is a named pipe (also known as a fifo). fn truncate_size_only(size_string: &str, filenames: &[String], create: bool) -> UResult<()> { let mode = parse_mode_and_size(size_string) - .map_err(|e| USimpleError::new(1, format!("Invalid number: {}", e)))?; + .map_err(|e| USimpleError::new(1, format!("Invalid number: {e}")))?; if let TruncateMode::RoundDown(0) | TruncateMode::RoundUp(0) = mode { return Err(USimpleError::new(1, "division by zero")); } diff --git a/src/uu/tsort/src/tsort.rs b/src/uu/tsort/src/tsort.rs index 1ef853706..cb179699d 100644 --- a/src/uu/tsort/src/tsort.rs +++ b/src/uu/tsort/src/tsort.rs @@ -76,12 +76,12 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { if !g.is_acyclic() { return Err(USimpleError::new( 1, - format!("{}, input contains a loop:", input), + format!("{input}, input contains a loop:"), )); } for x in &g.result { - println!("{}", x); + println!("{x}"); } Ok(()) diff --git a/src/uu/unexpand/src/unexpand.rs b/src/uu/unexpand/src/unexpand.rs index 030e090fc..df2348a8c 100644 --- a/src/uu/unexpand/src/unexpand.rs +++ b/src/uu/unexpand/src/unexpand.rs @@ -142,7 +142,7 @@ fn expand_shortcuts(args: &[String]) -> Vec { arg[1..] .split(',') .filter(|s| !s.is_empty()) - .for_each(|s| processed_args.push(format!("--tabs={}", s))); + .for_each(|s| processed_args.push(format!("--tabs={s}"))); has_shortcuts = true; } else { processed_args.push(arg.to_string()); diff --git a/src/uu/uniq/src/uniq.rs b/src/uu/uniq/src/uniq.rs index a66393acb..cbbd988cb 100644 --- a/src/uu/uniq/src/uniq.rs +++ b/src/uu/uniq/src/uniq.rs @@ -212,7 +212,7 @@ impl Uniq { } if self.show_counts { - writer.write_all(format!("{:7} {}", count, line).as_bytes()) + writer.write_all(format!("{count:7} {line}").as_bytes()) } else { writer.write_all(line.as_bytes()) } @@ -225,7 +225,7 @@ impl Uniq { fn get_line_string(io_line: io::Result>) -> UResult { let line_bytes = io_line.map_err_context(|| "failed to split lines".to_string())?; String::from_utf8(line_bytes) - .map_err(|e| USimpleError::new(1, format!("failed to convert line to utf8: {}", e))) + .map_err(|e| USimpleError::new(1, format!("failed to convert line to utf8: {e}"))) } fn opt_parsed(opt_name: &str, matches: &ArgMatches) -> UResult> { diff --git a/src/uu/uptime/src/uptime.rs b/src/uu/uptime/src/uptime.rs index 0751cbe9d..d13445f60 100644 --- a/src/uu/uptime/src/uptime.rs +++ b/src/uu/uptime/src/uptime.rs @@ -133,7 +133,7 @@ fn process_utmpx() -> (Option, usize) { fn print_nusers(nusers: usize) { match nusers.cmp(&1) { std::cmp::Ordering::Equal => print!("1 user, "), - std::cmp::Ordering::Greater => print!("{} users, ", nusers), + std::cmp::Ordering::Greater => print!("{nusers} users, "), _ => {} }; } @@ -180,10 +180,10 @@ fn print_uptime(upsecs: i64) { let uphours = (upsecs - (updays * 86400)) / 3600; let upmins = (upsecs - (updays * 86400) - (uphours * 3600)) / 60; match updays.cmp(&1) { - std::cmp::Ordering::Equal => print!("up {:1} day, {:2}:{:02}, ", updays, uphours, upmins), + std::cmp::Ordering::Equal => print!("up {updays:1} day, {uphours:2}:{upmins:02}, "), std::cmp::Ordering::Greater => { - print!("up {:1} days, {:2}:{:02}, ", updays, uphours, upmins); + print!("up {updays:1} days, {uphours:2}:{upmins:02}, "); } - _ => print!("up {:2}:{:02}, ", uphours, upmins), + _ => print!("up {uphours:2}:{upmins:02}, "), }; } diff --git a/src/uu/wc/src/wc.rs b/src/uu/wc/src/wc.rs index 135575d71..4a4838350 100644 --- a/src/uu/wc/src/wc.rs +++ b/src/uu/wc/src/wc.rs @@ -185,7 +185,7 @@ impl Display for WcError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::FilesDisabled(message) | Self::StdinReprNotAllowed(message) => { - write!(f, "{}", message) + write!(f, "{message}") } } } @@ -613,7 +613,7 @@ fn wc(inputs: &[Input], settings: &Settings) -> UResult<()> { if let Err(err) = print_stats(settings, &total_result, number_width) { show!(USimpleError::new( 1, - format!("failed to print total: {}", err) + format!("failed to print total: {err}") )); } } diff --git a/src/uu/who/src/who.rs b/src/uu/who/src/who.rs index 85ad435e5..935319c31 100644 --- a/src/uu/who/src/who.rs +++ b/src/uu/who/src/who.rs @@ -392,7 +392,7 @@ impl Who { fn print_runlevel(&self, ut: &Utmpx) { let last = (ut.pid() / 256) as u8 as char; let curr = (ut.pid() % 256) as u8 as char; - let runlvline = format!("run-level {}", curr); + let runlvline = format!("run-level {curr}"); let comment = format!("last={}", if last == 'N' { 'S' } else { 'N' }); self.print_line( @@ -508,7 +508,7 @@ impl Who { } else { ut.host() }; - let hoststr = if s.is_empty() { s } else { format!("({})", s) }; + let hoststr = if s.is_empty() { s } else { format!("({s})") }; self.print_line( ut.user().as_ref(), @@ -539,24 +539,24 @@ impl Who { let mut buf = String::with_capacity(64); let msg = vec![' ', state].into_iter().collect::(); - write!(buf, "{:<8}", user).unwrap(); + write!(buf, "{user:<8}").unwrap(); if self.include_mesg { buf.push_str(&msg); } - write!(buf, " {:<12}", line).unwrap(); + write!(buf, " {line:<12}").unwrap(); // "%b %e %H:%M" (LC_ALL=C) let time_size = 3 + 2 + 2 + 1 + 2; - write!(buf, " {:<1$}", time, time_size).unwrap(); + write!(buf, " {time:10}", pid).unwrap(); + write!(buf, " {pid:>10}").unwrap(); } - write!(buf, " {:<8}", comment).unwrap(); + write!(buf, " {comment:<8}").unwrap(); if self.include_exit { - write!(buf, " {:<12}", exit).unwrap(); + write!(buf, " {exit:<12}").unwrap(); } println!("{}", buf.trim_end()); } diff --git a/src/uu/yes/src/yes.rs b/src/uu/yes/src/yes.rs index cc04d26bc..09d4e5955 100644 --- a/src/uu/yes/src/yes.rs +++ b/src/uu/yes/src/yes.rs @@ -43,7 +43,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { match exec(bytes) { Ok(()) => Ok(()), Err(err) if err.kind() == io::ErrorKind::BrokenPipe => Ok(()), - Err(err) => Err(USimpleError::new(1, format!("standard output: {}", err))), + Err(err) => Err(USimpleError::new(1, format!("standard output: {err}"))), } } diff --git a/src/uucore/src/lib/features/encoding.rs b/src/uucore/src/lib/features/encoding.rs index e99017070..db4c4c635 100644 --- a/src/uucore/src/lib/features/encoding.rs +++ b/src/uucore/src/lib/features/encoding.rs @@ -165,7 +165,7 @@ pub fn wrap_write(mut writer: W, line_wrap: usize, res: &str) -> io::R use std::cmp::min; if line_wrap == 0 { - return write!(writer, "{}", res); + return write!(writer, "{res}"); } let mut start = 0; diff --git a/src/uucore/src/lib/features/fs.rs b/src/uucore/src/lib/features/fs.rs index c135f4acc..43c21aa8d 100644 --- a/src/uucore/src/lib/features/fs.rs +++ b/src/uucore/src/lib/features/fs.rs @@ -441,9 +441,9 @@ pub fn display_permissions(metadata: &fs::Metadata, display_file_type: bool) -> '-' }; - format!("{0}r{1}xr{1}xr{1}x", file_type, write) + format!("{file_type}r{write}xr{write}xr{write}x") } else { - format!("r{0}xr{0}xr{0}x", write) + format!("r{write}xr{write}xr{write}x") } } diff --git a/src/uucore/src/lib/features/fsext.rs b/src/uucore/src/lib/features/fsext.rs index 43b1a6cb5..927ae0f7a 100644 --- a/src/uucore/src/lib/features/fsext.rs +++ b/src/uucore/src/lib/features/fsext.rs @@ -832,7 +832,7 @@ pub fn pretty_time(sec: i64, nsec: i64) -> String { let tm = match time::OffsetDateTime::from_unix_timestamp_nanos(ts_nanos) { Ok(tm) => tm, Err(e) => { - panic!("error: {}", e); + panic!("error: {e}"); } }; @@ -842,7 +842,7 @@ pub fn pretty_time(sec: i64, nsec: i64) -> String { let local_offset = match UtcOffset::local_offset_at(tm) { Ok(lo) => lo, Err(e) => { - panic!("error: {}", e); + panic!("error: {e}"); } }; @@ -997,7 +997,7 @@ pub fn pretty_fstype<'a>(fstype: i64) -> Cow<'a, str> { 0x5846_5342 => "xfs".into(), 0x012F_D16D => "xia".into(), 0x2FC1_2FC1 => "zfs".into(), - other => format!("UNKNOWN ({:#x})", other).into(), + other => format!("UNKNOWN ({other:#x})").into(), } // spell-checker:enable } diff --git a/src/uucore/src/lib/features/memo.rs b/src/uucore/src/lib/features/memo.rs index c61be8acf..517efc9e2 100644 --- a/src/uucore/src/lib/features/memo.rs +++ b/src/uucore/src/lib/features/memo.rs @@ -142,7 +142,7 @@ pub fn sprintf(format_string: &str, args: &[String]) -> UResult { Ok(s) => Ok(s), Err(e) => Err(USimpleError::new( 1, - format!("failed to parse formatted string as UTF-8: {}", e), + format!("failed to parse formatted string as UTF-8: {e}"), )), } } diff --git a/src/uucore/src/lib/features/mode.rs b/src/uucore/src/lib/features/mode.rs index c27464363..956981254 100644 --- a/src/uucore/src/lib/features/mode.rs +++ b/src/uucore/src/lib/features/mode.rs @@ -20,7 +20,7 @@ pub fn parse_numeric(fperm: u32, mut mode: &str, considering_dir: bool) -> Resul u32::from_str_radix(mode, 8).map_err(|e| e.to_string())? }; if change > 0o7777 { - Err(format!("mode is too large ({} > 7777", change)) + Err(format!("mode is too large ({change} > 7777")) } else { Ok(match op { Some('+') => fperm | change, @@ -42,7 +42,7 @@ pub fn parse_symbolic( ) -> Result { let (mask, pos) = parse_levels(mode); if pos == mode.len() { - return Err(format!("invalid mode ({})", mode)); + return Err(format!("invalid mode ({mode})")); } let respect_umask = pos == 0; mode = &mode[pos..]; @@ -97,8 +97,7 @@ fn parse_op(mode: &str) -> Result<(char, usize), String> { match ch { '+' | '-' | '=' => Ok((ch, 1)), _ => Err(format!( - "invalid operator (expected +, -, or =, but found {})", - ch + "invalid operator (expected +, -, or =, but found {ch})" )), } } diff --git a/src/uucore/src/lib/features/signals.rs b/src/uucore/src/lib/features/signals.rs index 55f9b4b79..b92ecf764 100644 --- a/src/uucore/src/lib/features/signals.rs +++ b/src/uucore/src/lib/features/signals.rs @@ -215,7 +215,7 @@ fn signal_by_short_name() { fn signal_by_long_name() { for (value, signal) in ALL_SIGNALS.iter().enumerate() { assert_eq!( - signal_by_name_or_value(&format!("SIG{}", signal)), + signal_by_name_or_value(&format!("SIG{signal}")), Some(value) ); } diff --git a/src/uucore/src/lib/features/tokenize/num_format/formatters/cninetyninehexfloatf.rs b/src/uucore/src/lib/features/tokenize/num_format/formatters/cninetyninehexfloatf.rs index 85396a2aa..a5c51153e 100644 --- a/src/uucore/src/lib/features/tokenize/num_format/formatters/cninetyninehexfloatf.rs +++ b/src/uucore/src/lib/features/tokenize/num_format/formatters/cninetyninehexfloatf.rs @@ -81,9 +81,9 @@ fn get_primitive_hex( let suffix = Some({ let ind = if capitalized { "P" } else { "p" }; if mantissa >= 0 { - format!("{}+{}", ind, mantissa) + format!("{ind}+{mantissa}") } else { - format!("{}{}", ind, mantissa) + format!("{ind}{mantissa}") } }); FormatPrimitive { diff --git a/src/uucore/src/lib/features/tokenize/num_format/formatters/float_common.rs b/src/uucore/src/lib/features/tokenize/num_format/formatters/float_common.rs index aa9e497bd..c277e60a6 100644 --- a/src/uucore/src/lib/features/tokenize/num_format/formatters/float_common.rs +++ b/src/uucore/src/lib/features/tokenize/num_format/formatters/float_common.rs @@ -304,11 +304,11 @@ pub fn get_primitive_dec( mantissa += 1; } f.suffix = Some(if mantissa >= 0 { - format!("{}+{:02}", si_ind, mantissa) + format!("{si_ind}+{mantissa:02}") } else { // negative sign is considered in format!s // leading zeroes - format!("{}{:03}", si_ind, mantissa) + format!("{si_ind}{mantissa:03}") }); f.pre_decimal = Some(pre_dec_draft); } else if dec_place_chg { diff --git a/src/uucore/src/lib/features/tokenize/num_format/formatters/intf.rs b/src/uucore/src/lib/features/tokenize/num_format/formatters/intf.rs index 4364fd351..e0eb0ffd3 100644 --- a/src/uucore/src/lib/features/tokenize/num_format/formatters/intf.rs +++ b/src/uucore/src/lib/features/tokenize/num_format/formatters/intf.rs @@ -164,7 +164,7 @@ impl Intf { if sign == -1 { fmt_prim.prefix = Some(String::from("-")); } - fmt_prim.pre_decimal = Some(format!("{}", i)); + fmt_prim.pre_decimal = Some(format!("{i}")); fmt_prim } Err(_) => Self::get_max(field_char, sign), @@ -174,10 +174,10 @@ impl Intf { let mut fmt_prim = FormatPrimitive::default(); let u_f = if sign == -1 { u64::MAX - (u - 1) } else { u }; fmt_prim.pre_decimal = Some(match field_char { - 'X' => format!("{:X}", u_f), - 'x' => format!("{:x}", u_f), - 'o' => format!("{:o}", u_f), - _ => format!("{}", u_f), + 'X' => format!("{u_f:X}"), + 'x' => format!("{u_f:x}"), + 'o' => format!("{u_f:o}"), + _ => format!("{u_f}"), }); fmt_prim } diff --git a/src/uucore/src/lib/features/tokenize/num_format/num_format.rs b/src/uucore/src/lib/features/tokenize/num_format/num_format.rs index dd3655200..9aa97f811 100644 --- a/src/uucore/src/lib/features/tokenize/num_format/num_format.rs +++ b/src/uucore/src/lib/features/tokenize/num_format/num_format.rs @@ -222,18 +222,18 @@ pub fn num_format(field: &FormatField, in_str_opt: Option<&String>) -> Option { tmp.pre_decimal = Some( - format!("{}", provided_num)); + format!("{provided_num}")); }, 'x' | 'X' => { tmp.pre_decimal = Some( - format!("{:x}", provided_num)); + format!("{provided_num:x}")); }, 'o' => { tmp.pre_decimal = Some( - format!("{:o}", provided_num)); + format!("{provided_num:o}")); }, 'e' | 'E' | 'g' | 'G' => { - let as_str = format!("{}", provided_num); + let as_str = format!("{provided_num}"); let initial_prefix = get_initial_prefix( &as_str, field.field_type @@ -243,7 +243,7 @@ pub fn num_format(field: &FormatField, in_str_opt: Option<&String>) -> Option { tmp.pre_decimal = Some( - format!("{}", provided_num)); + format!("{provided_num}")); tmp.post_decimal = Some(String::from("0")); } } diff --git a/src/uucore/src/lib/features/tokenize/sub.rs b/src/uucore/src/lib/features/tokenize/sub.rs index 00fd51efd..9312040e3 100644 --- a/src/uucore/src/lib/features/tokenize/sub.rs +++ b/src/uucore/src/lib/features/tokenize/sub.rs @@ -31,7 +31,7 @@ pub enum SubError { impl Display for SubError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { match self { - Self::InvalidSpec(s) => write!(f, "%{}: invalid conversion specification", s), + Self::InvalidSpec(s) => write!(f, "%{s}: invalid conversion specification"), } } } diff --git a/src/uucore/src/lib/features/tokenize/unescaped_text.rs b/src/uucore/src/lib/features/tokenize/unescaped_text.rs index 59624f143..e659b11b5 100644 --- a/src/uucore/src/lib/features/tokenize/unescaped_text.rs +++ b/src/uucore/src/lib/features/tokenize/unescaped_text.rs @@ -88,12 +88,9 @@ impl UnescapedText { } else { 4 }; - let err_msg = format!( - "invalid universal character name {0}{1:02$x}", - preface, val, leading_zeros - ); + let err_msg = format!("invalid universal character name {preface}{val:0leading_zeros$x}"); if (val < 159 && (val != 36 && val != 64 && val != 96)) || (val > 55296 && val < 57343) { - println!("{}", err_msg); //todo stderr + println!("{err_msg}"); //todo stderr exit(EXIT_ERR); } } diff --git a/src/uucore/src/lib/features/utmpx.rs b/src/uucore/src/lib/features/utmpx.rs index b31aadc25..ee8744721 100644 --- a/src/uucore/src/lib/features/utmpx.rs +++ b/src/uucore/src/lib/features/utmpx.rs @@ -249,7 +249,7 @@ impl Utmpx { return Ok(if display.is_empty() { ai_canonname } else { - format!("{}:{}", ai_canonname, display) + format!("{ai_canonname}:{display}") }); } } diff --git a/src/uucore/src/lib/mods/error.rs b/src/uucore/src/lib/mods/error.rs index 5f6f21b77..8f1b2f3ec 100644 --- a/src/uucore/src/lib/mods/error.rs +++ b/src/uucore/src/lib/mods/error.rs @@ -439,9 +439,9 @@ impl Display for UIoError { &message }; if let Some(ctx) = &self.context { - write!(f, "{}: {}", ctx, message) + write!(f, "{ctx}: {message}") } else { - write!(f, "{}", message) + write!(f, "{message}") } } } diff --git a/src/uucore/src/lib/mods/quoting_style.rs b/src/uucore/src/lib/mods/quoting_style.rs index b07154139..3c8bf686a 100644 --- a/src/uucore/src/lib/mods/quoting_style.rs +++ b/src/uucore/src/lib/mods/quoting_style.rs @@ -276,8 +276,8 @@ pub fn escape_name(name: &OsStr, style: &QuotingStyle) -> String { .collect(); match quotes { - Quotes::Single => format!("'{}'", escaped_str), - Quotes::Double => format!("\"{}\"", escaped_str), + Quotes::Single => format!("'{escaped_str}'"), + Quotes::Double => format!("\"{escaped_str}\""), Quotes::None => escaped_str, } } @@ -304,8 +304,8 @@ pub fn escape_name(name: &OsStr, style: &QuotingStyle) -> String { }; match (must_quote | contains_quote_chars, quotes) { - (true, Quotes::Single) => format!("'{}'", escaped_str), - (true, Quotes::Double) => format!("\"{}\"", escaped_str), + (true, Quotes::Single) => format!("'{escaped_str}'"), + (true, Quotes::Double) => format!("\"{escaped_str}\""), _ => escaped_str, } } diff --git a/src/uucore/src/lib/parser/parse_size.rs b/src/uucore/src/lib/parser/parse_size.rs index 9b59053f0..d1e571e06 100644 --- a/src/uucore/src/lib/parser/parse_size.rs +++ b/src/uucore/src/lib/parser/parse_size.rs @@ -196,7 +196,7 @@ impl fmt::Display for ParseSizeError { let s = match self { Self::InvalidSuffix(s) | Self::ParseFailure(s) | Self::SizeTooBig(s) => s, }; - write!(f, "{}", s) + write!(f, "{s}") } } @@ -292,21 +292,21 @@ mod tests { ]; for &(c, exp) in &suffixes { - let s = format!("2{}B", c); // KB + let s = format!("2{c}B"); // KB assert_eq!(Ok((2 * (1000_u128).pow(exp)) as u64), parse_size(&s)); - let s = format!("2{}", c); // K + let s = format!("2{c}"); // K assert_eq!(Ok((2 * (1024_u128).pow(exp)) as u64), parse_size(&s)); - let s = format!("2{}iB", c); // KiB + let s = format!("2{c}iB"); // KiB assert_eq!(Ok((2 * (1024_u128).pow(exp)) as u64), parse_size(&s)); let s = format!("2{}iB", c.to_lowercase()); // kiB assert_eq!(Ok((2 * (1024_u128).pow(exp)) as u64), parse_size(&s)); // suffix only - let s = format!("{}B", c); // KB + let s = format!("{c}B"); // KB assert_eq!(Ok(((1000_u128).pow(exp)) as u64), parse_size(&s)); - let s = format!("{}", c); // K + let s = format!("{c}"); // K assert_eq!(Ok(((1024_u128).pow(exp)) as u64), parse_size(&s)); - let s = format!("{}iB", c); // KiB + let s = format!("{c}iB"); // KiB assert_eq!(Ok(((1024_u128).pow(exp)) as u64), parse_size(&s)); let s = format!("{}iB", c.to_lowercase()); // kiB assert_eq!(Ok(((1024_u128).pow(exp)) as u64), parse_size(&s)); @@ -421,9 +421,9 @@ mod tests { assert_eq!(Ok(1024), parser.parse("1")); assert_eq!(Ok(2 * 1024), parser.parse("2")); - assert_eq!(Ok(1 * 1000 * 1000), parser.parse("1MB")); - assert_eq!(Ok(1 * 1024 * 1024), parser.parse("1M")); - assert_eq!(Ok(1 * 1024 * 1024 * 1024), parser.parse("1G")); + assert_eq!(Ok(1000 * 1000), parser.parse("1MB")); + assert_eq!(Ok(1024 * 1024), parser.parse("1M")); + assert_eq!(Ok(1024 * 1024 * 1024), parser.parse("1G")); assert!(parser.parse("1T").is_err()); assert!(parser.parse("1P").is_err()); @@ -438,9 +438,9 @@ mod tests { assert_eq!(Ok(1024), parser.parse("1")); assert_eq!(Ok(2 * 1024), parser.parse("2")); - assert_eq!(Ok(1 * 1000 * 1000), parser.parse("1MB")); - assert_eq!(Ok(1 * 1024 * 1024), parser.parse("1M")); - assert_eq!(Ok(1 * 1024 * 1024 * 1024), parser.parse("1G")); + assert_eq!(Ok(1000 * 1000), parser.parse("1MB")); + assert_eq!(Ok(1024 * 1024), parser.parse("1M")); + assert_eq!(Ok(1024 * 1024 * 1024), parser.parse("1G")); assert_eq!(Ok(1), parser.parse("1b")); assert_eq!(Ok(1024), parser.parse("1024b")); diff --git a/src/uucore_procs/src/lib.rs b/src/uucore_procs/src/lib.rs index 89ac1a749..1a452254a 100644 --- a/src/uucore_procs/src/lib.rs +++ b/src/uucore_procs/src/lib.rs @@ -107,8 +107,8 @@ fn get_argument(input: &[TokenTree], index: usize, name: &str) -> String { // Multiply by two to ignore the `','` in between the arguments let string = match &input.get(index * 2) { Some(TokenTree::Literal(lit)) => lit.to_string(), - Some(_) => panic!("Argument {} should be a string literal.", index), - None => panic!("Missing argument at index {} for {}", index, name), + Some(_) => panic!("Argument {index} should be a string literal."), + None => panic!("Missing argument at index {index} for {name}"), }; string @@ -152,8 +152,7 @@ fn parse_help_section(section: &str, content: &str) -> String { // a nice error message. if content.lines().all(|l| !is_section_header(l, section)) { panic!( - "The section '{}' could not be found in the help file. Maybe it is spelled wrong?", - section + "The section '{section}' could not be found in the help file. Maybe it is spelled wrong?" ) } @@ -183,7 +182,7 @@ fn parse_usage(content: &str) -> String { // Replace the util name (assumed to be the first word) with "{}" // to be replaced with the runtime value later. if let Some((_util, args)) = l.split_once(' ') { - format!("{{}} {}\n", args) + format!("{{}} {args}\n") } else { "{}\n".to_string() } diff --git a/tests/by-util/test_chgrp.rs b/tests/by-util/test_chgrp.rs index 844563e46..352ecb513 100644 --- a/tests/by-util/test_chgrp.rs +++ b/tests/by-util/test_chgrp.rs @@ -118,7 +118,7 @@ fn test_preserve_root_symlink() { at.symlink_file("///dev", file); ucmd.arg("--preserve-root") .arg("-HR") - .arg("bin").arg(format!(".//{}/..//..//../../", file)) + .arg("bin").arg(format!(".//{file}/..//..//../../")) .fails() .stderr_is("chgrp: it is dangerous to operate recursively on '/'\nchgrp: use --no-preserve-root to override this failsafe\n"); diff --git a/tests/by-util/test_chmod.rs b/tests/by-util/test_chmod.rs index 15025c700..5dfd1a714 100644 --- a/tests/by-util/test_chmod.rs +++ b/tests/by-util/test_chmod.rs @@ -414,10 +414,9 @@ fn test_chmod_symlink_non_existing_file() { let non_existing = "test_chmod_symlink_non_existing_file"; let test_symlink = "test_chmod_symlink_non_existing_file_symlink"; let expected_stdout = &format!( - "failed to change mode of '{}' from 0000 (---------) to 0000 (---------)", - test_symlink + "failed to change mode of '{test_symlink}' from 0000 (---------) to 0000 (---------)" ); - let expected_stderr = &format!("cannot operate on dangling symlink '{}'", test_symlink); + let expected_stderr = &format!("cannot operate on dangling symlink '{test_symlink}'"); at.symlink_file(non_existing, test_symlink); @@ -455,10 +454,7 @@ fn test_chmod_symlink_non_existing_file_recursive() { let test_directory = "test_chmod_symlink_non_existing_file_directory"; at.mkdir(test_directory); - at.symlink_file( - non_existing, - &format!("{}/{}", test_directory, test_symlink), - ); + at.symlink_file(non_existing, &format!("{test_directory}/{test_symlink}")); // this should succeed scene @@ -472,8 +468,7 @@ fn test_chmod_symlink_non_existing_file_recursive() { let expected_stdout = &format!( // spell-checker:disable-next-line - "mode of '{}' retained as 0755 (rwxr-xr-x)", - test_directory + "mode of '{test_directory}' retained as 0755 (rwxr-xr-x)" ); // '-v': this should succeed without stderr diff --git a/tests/by-util/test_chown.rs b/tests/by-util/test_chown.rs index 716e7f48f..5237a7cf7 100644 --- a/tests/by-util/test_chown.rs +++ b/tests/by-util/test_chown.rs @@ -138,7 +138,7 @@ fn test_chown_only_owner_colon() { scene .ucmd() - .arg(format!("{}:", user_name)) + .arg(format!("{user_name}:")) .arg("--verbose") .arg(file1) .succeeds() @@ -146,7 +146,7 @@ fn test_chown_only_owner_colon() { scene .ucmd() - .arg(format!("{}.", user_name)) + .arg(format!("{user_name}.")) .arg("--verbose") .arg(file1) .succeeds() @@ -244,7 +244,7 @@ fn test_chown_owner_group() { let result = scene .ucmd() - .arg(format!("{}:{}", user_name, group_name)) + .arg(format!("{user_name}:{group_name}")) .arg("--verbose") .arg(file1) .run(); @@ -309,7 +309,7 @@ fn test_chown_various_input() { let result = scene .ucmd() - .arg(format!("{}:{}", user_name, group_name)) + .arg(format!("{user_name}:{group_name}")) .arg("--verbose") .arg(file1) .run(); @@ -321,7 +321,7 @@ fn test_chown_various_input() { // check that username.groupname is understood let result = scene .ucmd() - .arg(format!("{}.{}", user_name, group_name)) + .arg(format!("{user_name}.{group_name}")) .arg("--verbose") .arg(file1) .run(); @@ -365,7 +365,7 @@ fn test_chown_only_group() { let result = scene .ucmd() - .arg(format!(":{}", user_name)) + .arg(format!(":{user_name}")) .arg("--verbose") .arg(file1) .run(); @@ -442,14 +442,14 @@ fn test_chown_fail_id() { scene .ucmd() - .arg(format!("{}:", user_id)) + .arg(format!("{user_id}:")) .arg(file1) .fails() .stderr_contains("invalid spec"); scene .ucmd() - .arg(format!("{}.", user_id)) + .arg(format!("{user_id}.")) .arg(file1) .fails() .stderr_contains("invalid spec"); @@ -499,7 +499,7 @@ fn test_chown_only_group_id() { let result = scene .ucmd() - .arg(format!(":{}", group_id)) + .arg(format!(":{group_id}")) .arg("--verbose") .arg(file1) .run(); @@ -570,7 +570,7 @@ fn test_chown_owner_group_id() { let result = scene .ucmd() - .arg(format!("{}:{}", user_id, group_id)) + .arg(format!("{user_id}:{group_id}")) .arg("--verbose") .arg(file1) .run(); @@ -583,7 +583,7 @@ fn test_chown_owner_group_id() { let result = scene .ucmd() - .arg(format!("{}.{}", user_id, group_id)) + .arg(format!("{user_id}.{group_id}")) .arg("--verbose") .arg(file1) .run(); @@ -631,7 +631,7 @@ fn test_chown_owner_group_mix() { let result = scene .ucmd() - .arg(format!("{}:{}", user_id, group_name)) + .arg(format!("{user_id}:{group_name}")) .arg("--verbose") .arg(file1) .run(); diff --git a/tests/by-util/test_chroot.rs b/tests/by-util/test_chroot.rs index 23ea08657..c7e786f93 100644 --- a/tests/by-util/test_chroot.rs +++ b/tests/by-util/test_chroot.rs @@ -94,7 +94,7 @@ fn test_preference_of_userspec() { .arg("fake") .arg("-G") .arg("ABC,DEF") - .arg(format!("--userspec={}:{}", username, group_name)) + .arg(format!("--userspec={username}:{group_name}")) .fails(); result.code_is(125); @@ -113,10 +113,7 @@ fn test_default_shell() { at.mkdir(dir); let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string()); - let expected = format!( - "chroot: failed to run command '{}': No such file or directory", - shell - ); + let expected = format!("chroot: failed to run command '{shell}': No such file or directory"); if let Ok(result) = run_ucmd_as_root(&ts, &[dir]) { result.stderr_contains(expected); diff --git a/tests/by-util/test_cp.rs b/tests/by-util/test_cp.rs index af3422546..e6e8a6ba2 100644 --- a/tests/by-util/test_cp.rs +++ b/tests/by-util/test_cp.rs @@ -91,7 +91,7 @@ fn test_cp_existing_target() { assert_eq!(at.read(TEST_EXISTING_FILE), "Hello, World!\n"); // No backup should have been created - assert!(!at.file_exists(&format!("{}~", TEST_EXISTING_FILE))); + assert!(!at.file_exists(&format!("{TEST_EXISTING_FILE}~"))); } #[test] @@ -211,7 +211,7 @@ fn test_cp_target_directory_is_file() { .arg(TEST_HOW_ARE_YOU_SOURCE) .arg(TEST_HELLO_WORLD_SOURCE) .fails() - .stderr_contains(format!("'{}' is not a directory", TEST_HOW_ARE_YOU_SOURCE)); + .stderr_contains(format!("'{TEST_HOW_ARE_YOU_SOURCE}' is not a directory")); } #[test] @@ -374,7 +374,7 @@ fn test_cp_arg_backup() { assert_eq!(at.read(TEST_HOW_ARE_YOU_SOURCE), "Hello, World!\n"); assert_eq!( - at.read(&format!("{}~", TEST_HOW_ARE_YOU_SOURCE)), + at.read(&format!("{TEST_HOW_ARE_YOU_SOURCE}~")), "How are you?\n" ); } @@ -390,7 +390,7 @@ fn test_cp_arg_backup_with_other_args() { assert_eq!(at.read(TEST_HOW_ARE_YOU_SOURCE), "Hello, World!\n"); assert_eq!( - at.read(&format!("{}~", TEST_HOW_ARE_YOU_SOURCE)), + at.read(&format!("{TEST_HOW_ARE_YOU_SOURCE}~")), "How are you?\n" ); } @@ -406,7 +406,7 @@ fn test_cp_arg_backup_arg_first() { assert_eq!(at.read(TEST_HOW_ARE_YOU_SOURCE), "Hello, World!\n"); assert_eq!( - at.read(&format!("{}~", TEST_HOW_ARE_YOU_SOURCE)), + at.read(&format!("{TEST_HOW_ARE_YOU_SOURCE}~")), "How are you?\n" ); } @@ -424,7 +424,7 @@ fn test_cp_arg_suffix() { assert_eq!(at.read(TEST_HOW_ARE_YOU_SOURCE), "Hello, World!\n"); assert_eq!( - at.read(&format!("{}.bak", TEST_HOW_ARE_YOU_SOURCE)), + at.read(&format!("{TEST_HOW_ARE_YOU_SOURCE}.bak")), "How are you?\n" ); } @@ -442,7 +442,7 @@ fn test_cp_arg_suffix_hyphen_value() { assert_eq!(at.read(TEST_HOW_ARE_YOU_SOURCE), "Hello, World!\n"); assert_eq!( - at.read(&format!("{}-v", TEST_HOW_ARE_YOU_SOURCE)), + at.read(&format!("{TEST_HOW_ARE_YOU_SOURCE}-v")), "How are you?\n" ); } @@ -461,7 +461,7 @@ fn test_cp_custom_backup_suffix_via_env() { assert_eq!(at.read(TEST_HOW_ARE_YOU_SOURCE), "Hello, World!\n"); assert_eq!( - at.read(&format!("{}{}", TEST_HOW_ARE_YOU_SOURCE, suffix)), + at.read(&format!("{TEST_HOW_ARE_YOU_SOURCE}{suffix}")), "How are you?\n" ); } @@ -478,7 +478,7 @@ fn test_cp_backup_numbered_with_t() { assert_eq!(at.read(TEST_HOW_ARE_YOU_SOURCE), "Hello, World!\n"); assert_eq!( - at.read(&format!("{}.~1~", TEST_HOW_ARE_YOU_SOURCE)), + at.read(&format!("{TEST_HOW_ARE_YOU_SOURCE}.~1~")), "How are you?\n" ); } @@ -495,7 +495,7 @@ fn test_cp_backup_numbered() { assert_eq!(at.read(TEST_HOW_ARE_YOU_SOURCE), "Hello, World!\n"); assert_eq!( - at.read(&format!("{}.~1~", TEST_HOW_ARE_YOU_SOURCE)), + at.read(&format!("{TEST_HOW_ARE_YOU_SOURCE}.~1~")), "How are you?\n" ); } @@ -512,7 +512,7 @@ fn test_cp_backup_existing() { assert_eq!(at.read(TEST_HOW_ARE_YOU_SOURCE), "Hello, World!\n"); assert_eq!( - at.read(&format!("{}~", TEST_HOW_ARE_YOU_SOURCE)), + at.read(&format!("{TEST_HOW_ARE_YOU_SOURCE}~")), "How are you?\n" ); } @@ -529,7 +529,7 @@ fn test_cp_backup_nil() { assert_eq!(at.read(TEST_HOW_ARE_YOU_SOURCE), "Hello, World!\n"); assert_eq!( - at.read(&format!("{}~", TEST_HOW_ARE_YOU_SOURCE)), + at.read(&format!("{TEST_HOW_ARE_YOU_SOURCE}~")), "How are you?\n" ); } @@ -537,7 +537,7 @@ fn test_cp_backup_nil() { #[test] fn test_cp_numbered_if_existing_backup_existing() { let (at, mut ucmd) = at_and_ucmd!(); - let existing_backup = &format!("{}.~1~", TEST_HOW_ARE_YOU_SOURCE); + let existing_backup = &format!("{TEST_HOW_ARE_YOU_SOURCE}.~1~"); at.touch(existing_backup); ucmd.arg("--backup=existing") @@ -549,7 +549,7 @@ fn test_cp_numbered_if_existing_backup_existing() { assert!(at.file_exists(TEST_HOW_ARE_YOU_SOURCE)); assert!(at.file_exists(existing_backup)); assert_eq!( - at.read(&format!("{}.~2~", TEST_HOW_ARE_YOU_SOURCE)), + at.read(&format!("{TEST_HOW_ARE_YOU_SOURCE}.~2~")), "How are you?\n" ); } @@ -557,7 +557,7 @@ fn test_cp_numbered_if_existing_backup_existing() { #[test] fn test_cp_numbered_if_existing_backup_nil() { let (at, mut ucmd) = at_and_ucmd!(); - let existing_backup = &format!("{}.~1~", TEST_HOW_ARE_YOU_SOURCE); + let existing_backup = &format!("{TEST_HOW_ARE_YOU_SOURCE}.~1~"); at.touch(existing_backup); ucmd.arg("--backup=nil") @@ -569,7 +569,7 @@ fn test_cp_numbered_if_existing_backup_nil() { assert!(at.file_exists(TEST_HOW_ARE_YOU_SOURCE)); assert!(at.file_exists(existing_backup)); assert_eq!( - at.read(&format!("{}.~2~", TEST_HOW_ARE_YOU_SOURCE)), + at.read(&format!("{TEST_HOW_ARE_YOU_SOURCE}.~2~")), "How are you?\n" ); } @@ -586,7 +586,7 @@ fn test_cp_backup_simple() { assert_eq!(at.read(TEST_HOW_ARE_YOU_SOURCE), "Hello, World!\n"); assert_eq!( - at.read(&format!("{}~", TEST_HOW_ARE_YOU_SOURCE)), + at.read(&format!("{TEST_HOW_ARE_YOU_SOURCE}~")), "How are you?\n" ); } @@ -594,15 +594,14 @@ fn test_cp_backup_simple() { #[test] fn test_cp_backup_simple_protect_source() { let (at, mut ucmd) = at_and_ucmd!(); - let source = format!("{}~", TEST_HELLO_WORLD_SOURCE); + let source = format!("{TEST_HELLO_WORLD_SOURCE}~"); at.touch(&source); ucmd.arg("--backup=simple") .arg(&source) .arg(TEST_HELLO_WORLD_SOURCE) .fails() .stderr_only(format!( - "cp: backing up '{}' might destroy source; '{}' not copied\n", - TEST_HELLO_WORLD_SOURCE, source, + "cp: backing up '{TEST_HELLO_WORLD_SOURCE}' might destroy source; '{source}' not copied\n", )); assert_eq!(at.read(TEST_HELLO_WORLD_SOURCE), "Hello, World!\n"); @@ -621,7 +620,7 @@ fn test_cp_backup_never() { assert_eq!(at.read(TEST_HOW_ARE_YOU_SOURCE), "Hello, World!\n"); assert_eq!( - at.read(&format!("{}~", TEST_HOW_ARE_YOU_SOURCE)), + at.read(&format!("{TEST_HOW_ARE_YOU_SOURCE}~")), "How are you?\n" ); } @@ -637,7 +636,7 @@ fn test_cp_backup_none() { .no_stderr(); assert_eq!(at.read(TEST_HOW_ARE_YOU_SOURCE), "Hello, World!\n"); - assert!(!at.file_exists(&format!("{}~", TEST_HOW_ARE_YOU_SOURCE))); + assert!(!at.file_exists(&format!("{TEST_HOW_ARE_YOU_SOURCE}~"))); } #[test] @@ -651,7 +650,7 @@ fn test_cp_backup_off() { .no_stderr(); assert_eq!(at.read(TEST_HOW_ARE_YOU_SOURCE), "Hello, World!\n"); - assert!(!at.file_exists(&format!("{}~", TEST_HOW_ARE_YOU_SOURCE))); + assert!(!at.file_exists(&format!("{TEST_HOW_ARE_YOU_SOURCE}~"))); } #[test] @@ -801,7 +800,7 @@ fn test_cp_strip_trailing_slashes() { //using --strip-trailing-slashes option ucmd.arg("--strip-trailing-slashes") - .arg(format!("{}/", TEST_HELLO_WORLD_SOURCE)) + .arg(format!("{TEST_HELLO_WORLD_SOURCE}/")) .arg(TEST_HELLO_WORLD_DEST) .succeeds(); @@ -820,8 +819,7 @@ fn test_cp_parents() { assert_eq!( at.read(&format!( - "{}/{}", - TEST_COPY_TO_FOLDER, TEST_COPY_FROM_FOLDER_FILE + "{TEST_COPY_TO_FOLDER}/{TEST_COPY_FROM_FOLDER_FILE}" )), "Hello, World!\n" ); @@ -839,16 +837,12 @@ fn test_cp_parents_multiple_files() { assert_eq!( at.read(&format!( - "{}/{}", - TEST_COPY_TO_FOLDER, TEST_COPY_FROM_FOLDER_FILE + "{TEST_COPY_TO_FOLDER}/{TEST_COPY_FROM_FOLDER_FILE}" )), "Hello, World!\n" ); assert_eq!( - at.read(&format!( - "{}/{}", - TEST_COPY_TO_FOLDER, TEST_HOW_ARE_YOU_SOURCE - )), + at.read(&format!("{TEST_COPY_TO_FOLDER}/{TEST_HOW_ARE_YOU_SOURCE}")), "How are you?\n" ); } @@ -1350,7 +1344,7 @@ fn test_cp_no_preserve_timestamps() { let result = scene2.cmd("ls").arg("-al").arg(at.subdir).run(); println!("ls dest {}", result.stdout_str()); - println!("creation {:?} / {:?}", creation, creation2); + println!("creation {creation:?} / {creation2:?}"); assert_ne!(creation, creation2); let res = creation.elapsed().unwrap() - creation2.elapsed().unwrap(); diff --git a/tests/by-util/test_csplit.rs b/tests/by-util/test_csplit.rs index 018ea0eee..771cd5f81 100644 --- a/tests/by-util/test_csplit.rs +++ b/tests/by-util/test_csplit.rs @@ -4,7 +4,7 @@ use glob::glob; /// Returns a string of numbers with the given range, each on a new line. /// The upper bound is not included. fn generate(from: u32, to: u32) -> String { - (from..to).fold(String::new(), |acc, v| format!("{}{}\n", acc, v)) + (from..to).fold(String::new(), |acc, v| format!("{acc}{v}\n")) } #[test] diff --git a/tests/by-util/test_date.rs b/tests/by-util/test_date.rs index 6aa0031ca..4442f2df4 100644 --- a/tests/by-util/test_date.rs +++ b/tests/by-util/test_date.rs @@ -31,13 +31,13 @@ fn test_date_rfc_3339() { for param in ["--rfc-3339", "--rfc-3"] { scene .ucmd() - .arg(format!("{}=ns", param)) + .arg(format!("{param}=ns")) .succeeds() .stdout_matches(&re); scene .ucmd() - .arg(format!("{}=seconds", param)) + .arg(format!("{param}=seconds")) .succeeds() .stdout_matches(&re); } @@ -46,14 +46,14 @@ fn test_date_rfc_3339() { #[test] fn test_date_rfc_8601() { for param in ["--iso-8601", "--i"] { - new_ucmd!().arg(format!("{}=ns", param)).succeeds(); + new_ucmd!().arg(format!("{param}=ns")).succeeds(); } } #[test] fn test_date_rfc_8601_second() { for param in ["--iso-8601", "--i"] { - new_ucmd!().arg(format!("{}=second", param)).succeeds(); + new_ucmd!().arg(format!("{param}=second")).succeeds(); } } diff --git a/tests/by-util/test_dd.rs b/tests/by-util/test_dd.rs index cc129680f..19050965c 100644 --- a/tests/by-util/test_dd.rs +++ b/tests/by-util/test_dd.rs @@ -211,35 +211,35 @@ fn test_x_multiplier() { fn test_zero_multiplier_warning() { for arg in ["count", "seek", "skip"] { new_ucmd!() - .args(&[format!("{}=0", arg).as_str(), "status=none"]) + .args(&[format!("{arg}=0").as_str(), "status=none"]) .pipe_in("") .succeeds() .no_stdout() .no_stderr(); new_ucmd!() - .args(&[format!("{}=00x1", arg).as_str(), "status=none"]) + .args(&[format!("{arg}=00x1").as_str(), "status=none"]) .pipe_in("") .succeeds() .no_stdout() .no_stderr(); new_ucmd!() - .args(&[format!("{}=0x1", arg).as_str(), "status=none"]) + .args(&[format!("{arg}=0x1").as_str(), "status=none"]) .pipe_in("") .succeeds() .no_stdout() .stderr_contains("warning: '0x' is a zero multiplier; use '00x' if that is intended"); new_ucmd!() - .args(&[format!("{}=0x0x1", arg).as_str(), "status=none"]) + .args(&[format!("{arg}=0x0x1").as_str(), "status=none"]) .pipe_in("") .succeeds() .no_stdout() .stderr_is("dd: warning: '0x' is a zero multiplier; use '00x' if that is intended\ndd: warning: '0x' is a zero multiplier; use '00x' if that is intended\n"); new_ucmd!() - .args(&[format!("{}=1x0x1", arg).as_str(), "status=none"]) + .args(&[format!("{arg}=1x0x1").as_str(), "status=none"]) .pipe_in("") .succeeds() .no_stdout() @@ -496,7 +496,7 @@ fn test_ascii_10k_to_stdout() { #[test] fn test_zeros_to_file() { let tname = "zero-256k"; - let test_fn = format!("{}.txt", tname); + let test_fn = format!("{tname}.txt"); let tmp_fn = format!("TESTFILE-{}.tmp", &tname); assert_fixture_exists!(test_fn); @@ -516,7 +516,7 @@ fn test_zeros_to_file() { #[test] fn test_to_file_with_ibs_obs() { let tname = "zero-256k"; - let test_fn = format!("{}.txt", tname); + let test_fn = format!("{tname}.txt"); let tmp_fn = format!("TESTFILE-{}.tmp", &tname); assert_fixture_exists!(test_fn); @@ -608,7 +608,7 @@ fn test_self_transfer() { #[test] fn test_unicode_filenames() { let tname = "😎💚🦊"; - let test_fn = format!("{}.txt", tname); + let test_fn = format!("{tname}.txt"); let tmp_fn = format!("TESTFILE-{}.tmp", &tname); assert_fixture_exists!(test_fn); @@ -1284,12 +1284,12 @@ fn test_invalid_number_arg_gnu_compatibility() { for command in commands { new_ucmd!() - .args(&[format!("{}=", command)]) + .args(&[format!("{command}=")]) .fails() .stderr_is("dd: invalid number: ‘’\n"); new_ucmd!() - .args(&[format!("{}=29d", command)]) + .args(&[format!("{command}=29d")]) .fails() .stderr_is("dd: invalid number: ‘29d’\n"); } @@ -1301,12 +1301,12 @@ fn test_invalid_flag_arg_gnu_compatibility() { for command in commands { new_ucmd!() - .args(&[format!("{}=", command)]) + .args(&[format!("{command}=")]) .fails() .usage_error("invalid input flag: ‘’"); new_ucmd!() - .args(&[format!("{}=29d", command)]) + .args(&[format!("{command}=29d")]) .fails() .usage_error("invalid input flag: ‘29d’"); } diff --git a/tests/by-util/test_df.rs b/tests/by-util/test_df.rs index d93e71da1..0cf27c205 100644 --- a/tests/by-util/test_df.rs +++ b/tests/by-util/test_df.rs @@ -519,7 +519,7 @@ fn test_default_block_size_in_posix_portability_mode() { fn test_block_size_1024() { fn get_header(block_size: u64) -> String { let output = new_ucmd!() - .args(&["-B", &format!("{}", block_size), "--output=size"]) + .args(&["-B", &format!("{block_size}"), "--output=size"]) .succeeds() .stdout_move_str(); output.lines().next().unwrap().trim().to_string() @@ -693,9 +693,9 @@ fn test_ignore_block_size_from_env_in_posix_portability_mode() { fn test_too_large_block_size() { fn run_command(size: &str) { new_ucmd!() - .arg(format!("--block-size={}", size)) + .arg(format!("--block-size={size}")) .fails() - .stderr_contains(format!("--block-size argument '{}' too large", size)); + .stderr_contains(format!("--block-size argument '{size}' too large")); } let too_large_sizes = vec!["1Y", "1Z"]; diff --git a/tests/by-util/test_dircolors.rs b/tests/by-util/test_dircolors.rs index 80b9711a2..aaff02d30 100644 --- a/tests/by-util/test_dircolors.rs +++ b/tests/by-util/test_dircolors.rs @@ -210,14 +210,14 @@ fn test_helper(file_name: &str, term: &str) { new_ucmd!() .env("TERM", term) .arg("-c") - .arg(format!("{}.txt", file_name)) + .arg(format!("{file_name}.txt")) .run() - .stdout_is_fixture(format!("{}.csh.expected", file_name)); + .stdout_is_fixture(format!("{file_name}.csh.expected")); new_ucmd!() .env("TERM", term) .arg("-b") - .arg(format!("{}.txt", file_name)) + .arg(format!("{file_name}.txt")) .run() - .stdout_is_fixture(format!("{}.sh.expected", file_name)); + .stdout_is_fixture(format!("{file_name}.sh.expected")); } diff --git a/tests/by-util/test_du.rs b/tests/by-util/test_du.rs index fe85db02d..1232beda9 100644 --- a/tests/by-util/test_du.rs +++ b/tests/by-util/test_du.rs @@ -95,24 +95,24 @@ fn test_du_invalid_size() { let ts = TestScenario::new(util_name!()); for s in args { ts.ucmd() - .arg(format!("--{}=1fb4t", s)) + .arg(format!("--{s}=1fb4t")) .arg("/tmp") .fails() .code_is(1) - .stderr_only(format!("du: invalid suffix in --{} argument '1fb4t'\n", s)); + .stderr_only(format!("du: invalid suffix in --{s} argument '1fb4t'\n")); ts.ucmd() - .arg(format!("--{}=x", s)) + .arg(format!("--{s}=x")) .arg("/tmp") .fails() .code_is(1) - .stderr_only(format!("du: invalid --{} argument 'x'\n", s)); + .stderr_only(format!("du: invalid --{s} argument 'x'\n")); #[cfg(not(target_pointer_width = "128"))] ts.ucmd() - .arg(format!("--{}=1Y", s)) + .arg(format!("--{s}=1Y")) .arg("/tmp") .fails() .code_is(1) - .stderr_only(format!("du: --{} argument '1Y' too large\n", s)); + .stderr_only(format!("du: --{s} argument '1Y' too large\n")); } } @@ -511,13 +511,13 @@ fn test_du_threshold() { let threshold = if cfg!(windows) { "7K" } else { "10K" }; ts.ucmd() - .arg(format!("--threshold={}", threshold)) + .arg(format!("--threshold={threshold}")) .succeeds() .stdout_contains("links") .stdout_does_not_contain("deeper_dir"); ts.ucmd() - .arg(format!("--threshold=-{}", threshold)) + .arg(format!("--threshold=-{threshold}")) .succeeds() .stdout_does_not_contain("links") .stdout_contains("deeper_dir"); diff --git a/tests/by-util/test_echo.rs b/tests/by-util/test_echo.rs index 401e16706..f28bc1bb4 100644 --- a/tests/by-util/test_echo.rs +++ b/tests/by-util/test_echo.rs @@ -176,7 +176,7 @@ fn test_disable_escapes() { .arg("-E") .arg(input_str) .succeeds() - .stdout_only(format!("{}\n", input_str)); + .stdout_only(format!("{input_str}\n")); } #[test] diff --git a/tests/by-util/test_factor.rs b/tests/by-util/test_factor.rs index 6a17c00ff..7a4d54fb5 100644 --- a/tests/by-util/test_factor.rs +++ b/tests/by-util/test_factor.rs @@ -41,7 +41,7 @@ fn test_parallel() { let n_integers = 100_000; let mut input_string = String::new(); for i in 0..=n_integers { - input_string.push_str(&(format!("{} ", i))[..]); + input_string.push_str(&(format!("{i} "))[..]); } let tmp_dir = TempDir::new().unwrap(); @@ -87,10 +87,10 @@ fn test_first_1000_integers() { let n_integers = 1000; let mut input_string = String::new(); for i in 0..=n_integers { - input_string.push_str(&(format!("{} ", i))[..]); + input_string.push_str(&(format!("{i} "))[..]); } - println!("STDIN='{}'", input_string); + println!("STDIN='{input_string}'"); let result = new_ucmd!().pipe_in(input_string.as_bytes()).succeeds(); // `seq 0 1000 | factor | sha1sum` => "c734327bd18b90fca5762f671672b5eda19f7dca" @@ -126,7 +126,7 @@ fn test_random() { .duration_since(SystemTime::UNIX_EPOCH) .unwrap() .as_secs(); - println!("rng_seed={:?}", rng_seed); + println!("rng_seed={rng_seed:?}"); let mut rng = SmallRng::seed_from_u64(rng_seed); let mut rand_gt = move |min: u64| { @@ -162,11 +162,11 @@ fn test_random() { let mut output_string = String::new(); for _ in 0..NUM_TESTS { let (product, factors) = rand_gt(1 << 63); - input_string.push_str(&(format!("{} ", product))[..]); + input_string.push_str(&(format!("{product} "))[..]); - output_string.push_str(&(format!("{}:", product))[..]); + output_string.push_str(&(format!("{product}:"))[..]); for factor in factors { - output_string.push_str(&(format!(" {}", factor))[..]); + output_string.push_str(&(format!(" {factor}"))[..]); } output_string.push('\n'); } @@ -180,7 +180,7 @@ fn test_random_big() { .duration_since(SystemTime::UNIX_EPOCH) .unwrap() .as_secs(); - println!("rng_seed={:?}", rng_seed); + println!("rng_seed={rng_seed:?}"); let mut rng = SmallRng::seed_from_u64(rng_seed); let bit_range_1 = Uniform::new(14_usize, 51); @@ -244,11 +244,11 @@ fn test_random_big() { let mut output_string = String::new(); for _ in 0..NUM_TESTS { let (product, factors) = rand_64(); - input_string.push_str(&(format!("{} ", product))[..]); + input_string.push_str(&(format!("{product} "))[..]); - output_string.push_str(&(format!("{}:", product))[..]); + output_string.push_str(&(format!("{product}:"))[..]); for factor in factors { - output_string.push_str(&(format!(" {}", factor))[..]); + output_string.push_str(&(format!(" {factor}"))[..]); } output_string.push('\n'); } @@ -261,8 +261,8 @@ fn test_big_primes() { let mut input_string = String::new(); let mut output_string = String::new(); for prime in PRIMES64 { - input_string.push_str(&(format!("{} ", prime))[..]); - output_string.push_str(&(format!("{0}: {0}\n", prime))[..]); + input_string.push_str(&(format!("{prime} "))[..]); + output_string.push_str(&(format!("{prime}: {prime}\n"))[..]); } run(input_string.as_bytes(), output_string.as_bytes()); diff --git a/tests/by-util/test_install.rs b/tests/by-util/test_install.rs index 4d2ead83b..1e6cd7606 100644 --- a/tests/by-util/test_install.rs +++ b/tests/by-util/test_install.rs @@ -28,8 +28,8 @@ fn test_install_basic() { assert!(at.file_exists(file1)); assert!(at.file_exists(file2)); - assert!(at.file_exists(&format!("{}/{}", dir, file1))); - assert!(at.file_exists(&format!("{}/{}", dir, file2))); + assert!(at.file_exists(&format!("{dir}/{file1}"))); + assert!(at.file_exists(&format!("{dir}/{file2}"))); } #[test] @@ -76,7 +76,7 @@ fn test_install_unimplemented_arg() { .fails() .stderr_contains("Unimplemented"); - assert!(!at.file_exists(&format!("{}/{}", dir, file))); + assert!(!at.file_exists(&format!("{dir}/{file}"))); } #[test] @@ -181,7 +181,7 @@ fn test_install_mode_numeric() { .succeeds() .no_stderr(); - let dest_file = &format!("{}/{}", dir, file); + let dest_file = &format!("{dir}/{file}"); assert!(at.file_exists(file)); assert!(at.file_exists(dest_file)); let permissions = at.metadata(dest_file).permissions(); @@ -192,7 +192,7 @@ fn test_install_mode_numeric() { scene.ucmd().arg(mode_arg).arg(file).arg(dir2).succeeds(); - let dest_file = &format!("{}/{}", dir2, file); + let dest_file = &format!("{dir2}/{file}"); assert!(at.file_exists(file)); assert!(at.file_exists(dest_file)); let permissions = at.metadata(dest_file).permissions(); @@ -210,7 +210,7 @@ fn test_install_mode_symbolic() { at.mkdir(dir); ucmd.arg(file).arg(dir).arg(mode_arg).succeeds().no_stderr(); - let dest_file = &format!("{}/{}", dir, file); + let dest_file = &format!("{dir}/{file}"); assert!(at.file_exists(file)); assert!(at.file_exists(dest_file)); let permissions = at.metadata(dest_file).permissions(); @@ -232,7 +232,7 @@ fn test_install_mode_failing() { .fails() .stderr_contains("Invalid mode string: invalid digit found in string"); - let dest_file = &format!("{}/{}", dir, file); + let dest_file = &format!("{dir}/{file}"); assert!(at.file_exists(file)); assert!(!at.file_exists(dest_file)); } @@ -278,12 +278,12 @@ fn test_install_target_new_file() { at.touch(file); at.mkdir(dir); ucmd.arg(file) - .arg(format!("{}/{}", dir, file)) + .arg(format!("{dir}/{file}")) .succeeds() .no_stderr(); assert!(at.file_exists(file)); - assert!(at.file_exists(&format!("{}/{}", dir, file))); + assert!(at.file_exists(&format!("{dir}/{file}"))); } #[test] @@ -299,7 +299,7 @@ fn test_install_target_new_file_with_group() { .arg(file) .arg("--group") .arg(gid.to_string()) - .arg(format!("{}/{}", dir, file)) + .arg(format!("{dir}/{file}")) .run(); if is_ci() && result.stderr_str().contains("no such group:") { @@ -310,7 +310,7 @@ fn test_install_target_new_file_with_group() { result.success(); assert!(at.file_exists(file)); - assert!(at.file_exists(&format!("{}/{}", dir, file))); + assert!(at.file_exists(&format!("{dir}/{file}"))); } #[test] @@ -326,7 +326,7 @@ fn test_install_target_new_file_with_owner() { .arg(file) .arg("--owner") .arg(uid.to_string()) - .arg(format!("{}/{}", dir, file)) + .arg(format!("{dir}/{file}")) .run(); if is_ci() && result.stderr_str().contains("no such user:") { @@ -337,7 +337,7 @@ fn test_install_target_new_file_with_owner() { result.success(); assert!(at.file_exists(file)); - assert!(at.file_exists(&format!("{}/{}", dir, file))); + assert!(at.file_exists(&format!("{dir}/{file}"))); } #[test] @@ -350,7 +350,7 @@ fn test_install_target_new_file_failing_nonexistent_parent() { at.touch(file1); ucmd.arg(file1) - .arg(format!("{}/{}", dir, file2)) + .arg(format!("{dir}/{file2}")) .fails() .stderr_contains("No such file or directory"); } @@ -416,13 +416,13 @@ fn test_install_nested_paths_copy_file() { at.mkdir(dir1); at.mkdir(dir2); - at.touch(&format!("{}/{}", dir1, file1)); + at.touch(&format!("{dir1}/{file1}")); - ucmd.arg(format!("{}/{}", dir1, file1)) + ucmd.arg(format!("{dir1}/{file1}")) .arg(dir2) .succeeds() .no_stderr(); - assert!(at.file_exists(&format!("{}/{}", dir2, file1))); + assert!(at.file_exists(&format!("{dir2}/{file1}"))); } #[test] @@ -456,7 +456,7 @@ fn test_install_failing_omitting_directory() { .fails() .code_is(1) .stderr_contains("omitting directory"); - assert!(at.file_exists(&format!("{}/{}", dir3, file1))); + assert!(at.file_exists(&format!("{dir3}/{file1}"))); // install also fails, when only one source param is given scene @@ -826,14 +826,14 @@ fn test_install_dir() { at.mkdir(dir); ucmd.arg(file1) .arg(file2) - .arg(&format!("--target-directory={}", dir)) + .arg(&format!("--target-directory={dir}")) .succeeds() .no_stderr(); assert!(at.file_exists(file1)); assert!(at.file_exists(file2)); - assert!(at.file_exists(&format!("{}/{}", dir, file1))); - assert!(at.file_exists(&format!("{}/{}", dir, file2))); + assert!(at.file_exists(&format!("{dir}/{file1}"))); + assert!(at.file_exists(&format!("{dir}/{file2}"))); } // // test backup functionality @@ -857,7 +857,7 @@ fn test_install_backup_short_no_args_files() { assert!(at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(at.file_exists(&format!("{}~", file_b))); + assert!(at.file_exists(&format!("{file_b}~"))); } #[test] @@ -867,7 +867,7 @@ fn test_install_backup_short_no_args_file_to_dir() { let file = "test_install_simple_backup_file_a"; let dest_dir = "test_install_dest/"; - let expect = format!("{}{}", dest_dir, file); + let expect = format!("{dest_dir}{file}"); at.touch(file); at.mkdir(dest_dir); @@ -882,7 +882,7 @@ fn test_install_backup_short_no_args_file_to_dir() { assert!(at.file_exists(file)); assert!(at.file_exists(&expect)); - assert!(at.file_exists(&format!("{}~", expect))); + assert!(at.file_exists(&format!("{expect}~"))); } // Long --backup option is tested separately as it requires a slightly different @@ -907,7 +907,7 @@ fn test_install_backup_long_no_args_files() { assert!(at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(at.file_exists(&format!("{}~", file_b))); + assert!(at.file_exists(&format!("{file_b}~"))); } #[test] @@ -917,7 +917,7 @@ fn test_install_backup_long_no_args_file_to_dir() { let file = "test_install_simple_backup_file_a"; let dest_dir = "test_install_dest/"; - let expect = format!("{}{}", dest_dir, file); + let expect = format!("{dest_dir}{file}"); at.touch(file); at.mkdir(dest_dir); @@ -932,7 +932,7 @@ fn test_install_backup_long_no_args_file_to_dir() { assert!(at.file_exists(file)); assert!(at.file_exists(&expect)); - assert!(at.file_exists(&format!("{}~", expect))); + assert!(at.file_exists(&format!("{expect}~"))); } #[test] @@ -949,7 +949,7 @@ fn test_install_backup_short_custom_suffix() { scene .ucmd() .arg("-b") - .arg(format!("--suffix={}", suffix)) + .arg(format!("--suffix={suffix}")) .arg(file_a) .arg(file_b) .succeeds() @@ -957,7 +957,7 @@ fn test_install_backup_short_custom_suffix() { assert!(at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(at.file_exists(&format!("{}{}", file_b, suffix))); + assert!(at.file_exists(&format!("{file_b}{suffix}"))); } #[test] @@ -974,7 +974,7 @@ fn test_install_backup_short_custom_suffix_hyphen_value() { scene .ucmd() .arg("-b") - .arg(format!("--suffix={}", suffix)) + .arg(format!("--suffix={suffix}")) .arg(file_a) .arg(file_b) .succeeds() @@ -982,7 +982,7 @@ fn test_install_backup_short_custom_suffix_hyphen_value() { assert!(at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(at.file_exists(&format!("{}{}", file_b, suffix))); + assert!(at.file_exists(&format!("{file_b}{suffix}"))); } #[test] @@ -1007,7 +1007,7 @@ fn test_install_backup_custom_suffix_via_env() { assert!(at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(at.file_exists(&format!("{}{}", file_b, suffix))); + assert!(at.file_exists(&format!("{file_b}{suffix}"))); } #[test] @@ -1030,7 +1030,7 @@ fn test_install_backup_numbered_with_t() { assert!(at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(at.file_exists(&format!("{}.~1~", file_b))); + assert!(at.file_exists(&format!("{file_b}.~1~"))); } #[test] @@ -1053,7 +1053,7 @@ fn test_install_backup_numbered_with_numbered() { assert!(at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(at.file_exists(&format!("{}.~1~", file_b))); + assert!(at.file_exists(&format!("{file_b}.~1~"))); } #[test] @@ -1076,7 +1076,7 @@ fn test_install_backup_existing() { assert!(at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(at.file_exists(&format!("{}~", file_b))); + assert!(at.file_exists(&format!("{file_b}~"))); } #[test] @@ -1099,7 +1099,7 @@ fn test_install_backup_nil() { assert!(at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(at.file_exists(&format!("{}~", file_b))); + assert!(at.file_exists(&format!("{file_b}~"))); } #[test] @@ -1125,7 +1125,7 @@ fn test_install_backup_numbered_if_existing_backup_existing() { assert!(at.file_exists(file_a)); assert!(at.file_exists(file_b)); assert!(at.file_exists(file_b_backup)); - assert!(at.file_exists(&format!("{}.~2~", file_b))); + assert!(at.file_exists(&format!("{file_b}.~2~"))); } #[test] @@ -1151,7 +1151,7 @@ fn test_install_backup_numbered_if_existing_backup_nil() { assert!(at.file_exists(file_a)); assert!(at.file_exists(file_b)); assert!(at.file_exists(file_b_backup)); - assert!(at.file_exists(&format!("{}.~2~", file_b))); + assert!(at.file_exists(&format!("{file_b}.~2~"))); } #[test] @@ -1174,7 +1174,7 @@ fn test_install_backup_simple() { assert!(at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(at.file_exists(&format!("{}~", file_b))); + assert!(at.file_exists(&format!("{file_b}~"))); } #[test] @@ -1197,7 +1197,7 @@ fn test_install_backup_never() { assert!(at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(at.file_exists(&format!("{}~", file_b))); + assert!(at.file_exists(&format!("{file_b}~"))); } #[test] @@ -1220,7 +1220,7 @@ fn test_install_backup_none() { assert!(at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(!at.file_exists(&format!("{}~", file_b))); + assert!(!at.file_exists(&format!("{file_b}~"))); } #[test] @@ -1243,7 +1243,7 @@ fn test_install_backup_off() { assert!(at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(!at.file_exists(&format!("{}~", file_b))); + assert!(!at.file_exists(&format!("{file_b}~"))); } #[test] @@ -1262,7 +1262,7 @@ fn test_install_missing_arguments() { scene .ucmd() .arg("-D") - .arg(format!("-t {}", no_target_dir)) + .arg(format!("-t {no_target_dir}")) .fails() .usage_error("missing file operand"); assert!(!at.dir_exists(no_target_dir)); @@ -1280,17 +1280,19 @@ fn test_install_missing_destination() { at.mkdir(dir_1); // will fail and also print some info on correct usage - scene.ucmd().arg(file_1).fails().usage_error(format!( - "missing destination file operand after '{}'", - file_1 - )); + scene + .ucmd() + .arg(file_1) + .fails() + .usage_error(format!("missing destination file operand after '{file_1}'")); // GNU's install will check for correct num of arguments and then fail // and it does not recognize, that the source is not a file but a directory. - scene.ucmd().arg(dir_1).fails().usage_error(format!( - "missing destination file operand after '{}'", - dir_1 - )); + scene + .ucmd() + .arg(dir_1) + .fails() + .usage_error(format!("missing destination file operand after '{dir_1}'")); } #[test] @@ -1378,7 +1380,7 @@ fn test_install_compare_option() { .ucmd() .args(&["-Cv", first, second]) .succeeds() - .stdout_contains(format!("'{}' -> '{}'", first, second)); + .stdout_contains(format!("'{first}' -> '{second}'")); scene .ucmd() .args(&["-Cv", first, second]) @@ -1388,12 +1390,12 @@ fn test_install_compare_option() { .ucmd() .args(&["-Cv", "-m0644", first, second]) .succeeds() - .stdout_contains(format!("removed '{}'\n'{}' -> '{}'", second, first, second)); + .stdout_contains(format!("removed '{second}'\n'{first}' -> '{second}'")); scene .ucmd() .args(&["-Cv", first, second]) .succeeds() - .stdout_contains(format!("removed '{}'\n'{}' -> '{}'", second, first, second)); + .stdout_contains(format!("removed '{second}'\n'{first}' -> '{second}'")); scene .ucmd() .args(&["-C", "--preserve-timestamps", first, second]) diff --git a/tests/by-util/test_ln.rs b/tests/by-util/test_ln.rs index e1dbdf7a9..bc51fc107 100644 --- a/tests/by-util/test_ln.rs +++ b/tests/by-util/test_ln.rs @@ -153,7 +153,7 @@ fn test_symlink_simple_backup() { assert!(at.is_symlink(link)); assert_eq!(at.resolve_link(link), file); - let backup = &format!("{}~", link); + let backup = &format!("{link}~"); assert!(at.is_symlink(backup)); assert_eq!(at.resolve_link(backup), file); } @@ -171,7 +171,7 @@ fn test_symlink_custom_backup_suffix() { assert!(at.is_symlink(link)); assert_eq!(at.resolve_link(link), file); - let arg = &format!("--suffix={}", suffix); + let arg = &format!("--suffix={suffix}"); ucmd.args(&["-b", arg, "-s", file, link]) .succeeds() .no_stderr(); @@ -180,7 +180,7 @@ fn test_symlink_custom_backup_suffix() { assert!(at.is_symlink(link)); assert_eq!(at.resolve_link(link), file); - let backup = &format!("{}{}", link, suffix); + let backup = &format!("{link}{suffix}"); assert!(at.is_symlink(backup)); assert_eq!(at.resolve_link(backup), file); } @@ -198,7 +198,7 @@ fn test_symlink_custom_backup_suffix_hyphen_value() { assert!(at.is_symlink(link)); assert_eq!(at.resolve_link(link), file); - let arg = &format!("--suffix={}", suffix); + let arg = &format!("--suffix={suffix}"); ucmd.args(&["-b", arg, "-s", file, link]) .succeeds() .no_stderr(); @@ -207,7 +207,7 @@ fn test_symlink_custom_backup_suffix_hyphen_value() { assert!(at.is_symlink(link)); assert_eq!(at.resolve_link(link), file); - let backup = &format!("{}{}", link, suffix); + let backup = &format!("{link}{suffix}"); assert!(at.is_symlink(backup)); assert_eq!(at.resolve_link(backup), file); } @@ -232,7 +232,7 @@ fn test_symlink_backup_numbering() { assert!(at.is_symlink(link)); assert_eq!(at.resolve_link(link), file); - let backup = &format!("{}.~1~", link); + let backup = &format!("{link}.~1~"); assert!(at.is_symlink(backup)); assert_eq!(at.resolve_link(backup), file); } @@ -285,11 +285,11 @@ fn test_symlink_target_dir() { .succeeds() .no_stderr(); - let file_a_link = &format!("{}/{}", dir, file_a); + let file_a_link = &format!("{dir}/{file_a}"); assert!(at.is_symlink(file_a_link)); assert_eq!(at.resolve_link(file_a_link), file_a); - let file_b_link = &format!("{}/{}", dir, file_b); + let file_b_link = &format!("{dir}/{file_b}"); assert!(at.is_symlink(file_b_link)); assert_eq!(at.resolve_link(file_b_link), file_b); } @@ -301,8 +301,8 @@ fn test_symlink_target_dir_from_dir() { let from_dir = "test_ln_target_dir_from_dir"; let filename_a = "test_ln_target_dir_file_a"; let filename_b = "test_ln_target_dir_file_b"; - let file_a = &format!("{}/{}", from_dir, filename_a); - let file_b = &format!("{}/{}", from_dir, filename_b); + let file_a = &format!("{from_dir}/{filename_a}"); + let file_b = &format!("{from_dir}/{filename_b}"); at.mkdir(from_dir); at.touch(file_a); @@ -313,11 +313,11 @@ fn test_symlink_target_dir_from_dir() { .succeeds() .no_stderr(); - let file_a_link = &format!("{}/{}", dir, filename_a); + let file_a_link = &format!("{dir}/{filename_a}"); assert!(at.is_symlink(file_a_link)); assert_eq!(&at.resolve_link(file_a_link), file_a); - let file_b_link = &format!("{}/{}", dir, filename_b); + let file_b_link = &format!("{dir}/{filename_b}"); assert!(at.is_symlink(file_b_link)); assert_eq!(&at.resolve_link(file_b_link), file_b); } @@ -367,7 +367,7 @@ fn test_symlink_verbose() { .ucmd() .args(&["-s", "-v", file_a, file_b]) .succeeds() - .stdout_only(format!("'{}' -> '{}'\n", file_b, file_a)); + .stdout_only(format!("'{file_b}' -> '{file_a}'\n")); at.touch(file_b); @@ -375,10 +375,7 @@ fn test_symlink_verbose() { .ucmd() .args(&["-s", "-v", "-b", file_a, file_b]) .succeeds() - .stdout_only(format!( - "'{}' -> '{}' (backup: '{}~')\n", - file_b, file_a, file_b - )); + .stdout_only(format!("'{file_b}' -> '{file_a}' (backup: '{file_b}~')\n")); } #[test] @@ -421,7 +418,7 @@ fn test_symlink_to_dir_2args() { let filename = "test_symlink_to_dir_2args_file"; let from_file = &format!("{}/{}", at.as_string(), filename); let to_dir = "test_symlink_to_dir_2args_to_dir"; - let to_file = &format!("{}/{}", to_dir, filename); + let to_file = &format!("{to_dir}/{filename}"); at.mkdir(to_dir); at.touch(from_file); @@ -441,8 +438,7 @@ fn test_symlink_missing_destination() { at.touch(file); ucmd.args(&["-s", "-T", file]).fails().stderr_is(format!( - "ln: missing destination file operand after '{}'\n", - file + "ln: missing destination file operand after '{file}'\n" )); } @@ -475,7 +471,7 @@ fn test_symlink_relative_path() { // Thanks to -r, all the ../ should be resolved to a single file ucmd.args(&["-r", "-s", "-v", &p.to_string_lossy(), link]) .succeeds() - .stdout_only(format!("'{}' -> '{}'\n", link, file_a)); + .stdout_only(format!("'{link}' -> '{file_a}'\n")); assert!(at.is_symlink(link)); assert_eq!(at.resolve_link(link), file_a); diff --git a/tests/by-util/test_logname.rs b/tests/by-util/test_logname.rs index 43fce6851..3d2081641 100644 --- a/tests/by-util/test_logname.rs +++ b/tests/by-util/test_logname.rs @@ -12,7 +12,7 @@ fn test_normal() { println!("env::var(CI).is_ok() = {}", env::var("CI").is_ok()); for (key, value) in env::vars() { - println!("{}: {}", key, value); + println!("{key}: {value}"); } if (is_ci() || uucore::os::is_wsl_1()) && result.stderr_str().contains("no login name") { // ToDO: investigate WSL failure diff --git a/tests/by-util/test_ls.rs b/tests/by-util/test_ls.rs index 59db55bb9..f1ab3eea4 100644 --- a/tests/by-util/test_ls.rs +++ b/tests/by-util/test_ls.rs @@ -435,44 +435,43 @@ fn test_ls_io_errors() { // on the mac and in certain Linux containers bad fds are typed as dirs, // however sometimes bad fds are typed as links and directory entry on links won't fail - if PathBuf::from(format!("/dev/fd/{fd}", fd = fd2)).is_dir() { + if PathBuf::from(format!("/dev/fd/{fd2}")).is_dir() { scene .ucmd() .arg("-alR") - .arg(format!("/dev/fd/{fd}", fd = fd2)) + .arg(format!("/dev/fd/{fd2}")) .fails() .stderr_contains(format!( - "cannot open directory '/dev/fd/{fd}': Bad file descriptor", - fd = fd2 + "cannot open directory '/dev/fd/{fd2}': Bad file descriptor" )) - .stdout_does_not_contain(format!("{fd}:\n", fd = fd2)); + .stdout_does_not_contain(format!("{fd2}:\n")); scene .ucmd() .arg("-RiL") - .arg(format!("/dev/fd/{fd}", fd = fd2)) + .arg(format!("/dev/fd/{fd2}")) .fails() - .stderr_contains(format!("cannot open directory '/dev/fd/{fd}': Bad file descriptor", fd = fd2)) + .stderr_contains(format!("cannot open directory '/dev/fd/{fd2}': Bad file descriptor")) // don't double print bad fd errors - .stderr_does_not_contain(format!("ls: cannot open directory '/dev/fd/{fd}': Bad file descriptor\nls: cannot open directory '/dev/fd/{fd}': Bad file descriptor", fd = fd2)); + .stderr_does_not_contain(format!("ls: cannot open directory '/dev/fd/{fd2}': Bad file descriptor\nls: cannot open directory '/dev/fd/{fd2}': Bad file descriptor")); } else { scene .ucmd() .arg("-alR") - .arg(format!("/dev/fd/{fd}", fd = fd2)) + .arg(format!("/dev/fd/{fd2}")) .succeeds(); scene .ucmd() .arg("-RiL") - .arg(format!("/dev/fd/{fd}", fd = fd2)) + .arg(format!("/dev/fd/{fd2}")) .succeeds(); } scene .ucmd() .arg("-alL") - .arg(format!("/dev/fd/{fd}", fd = fd2)) + .arg(format!("/dev/fd/{fd2}")) .succeeds(); let _ = close(fd2); @@ -1932,10 +1931,7 @@ fn test_ls_color() { .arg("-w=15") .arg("-C") .succeeds() - .stdout_only(format!( - "{} test-color\nb {}\n", - a_with_colors, z_with_colors - )); + .stdout_only(format!("{a_with_colors} test-color\nb {z_with_colors}\n")); } #[cfg(unix)] @@ -2041,7 +2037,7 @@ fn test_ls_indicator_style() { // Verify that classify and file-type both contain indicators for symlinks. scene .ucmd() - .arg(format!("--indicator-style={}", opt)) + .arg(format!("--indicator-style={opt}")) .succeeds() .stdout_contains("@") .stdout_contains("|"); @@ -2091,7 +2087,7 @@ fn test_ls_indicator_style() { // Verify that classify and file-type both contain indicators for symlinks. scene .ucmd() - .arg(format!("--indicator-style={}", opt)) + .arg(format!("--indicator-style={opt}")) .succeeds() .stdout_contains("/"); } @@ -2108,7 +2104,7 @@ fn test_ls_indicator_style() { // Verify that classify and file-type both contain indicators for symlinks. scene .ucmd() - .arg(format!("--indicator-style={}", opt)) + .arg(format!("--indicator-style={opt}")) .succeeds() .stdout_contains("@"); } @@ -2389,7 +2385,7 @@ fn test_ls_quoting_style() { .arg(arg) .arg("one\ntwo") .succeeds() - .stdout_only(format!("{}\n", correct)); + .stdout_only(format!("{correct}\n")); } for (arg, correct) in [ @@ -2405,7 +2401,7 @@ fn test_ls_quoting_style() { .arg("--show-control-chars") .arg("one\ntwo") .succeeds() - .stdout_only(format!("{}\n", correct)); + .stdout_only(format!("{correct}\n")); } for (arg, correct) in [ @@ -2427,7 +2423,7 @@ fn test_ls_quoting_style() { .arg(arg) .arg("one\\two") .succeeds() - .stdout_only(format!("{}\n", correct)); + .stdout_only(format!("{correct}\n")); } // Tests for a character that forces quotation in shell-style escaping @@ -2443,7 +2439,7 @@ fn test_ls_quoting_style() { .arg(arg) .arg("one\n&two") .succeeds() - .stdout_only(format!("{}\n", correct)); + .stdout_only(format!("{correct}\n")); } } @@ -2474,7 +2470,7 @@ fn test_ls_quoting_style() { .arg(arg) .arg("one two") .succeeds() - .stdout_only(format!("{}\n", correct)); + .stdout_only(format!("{correct}\n")); } scene.ucmd().arg("one").succeeds().stdout_only("one\n"); @@ -2498,7 +2494,7 @@ fn test_ls_quoting_style() { .arg(arg) .arg("one") .succeeds() - .stdout_only(format!("{}\n", correct)); + .stdout_only(format!("{correct}\n")); } } @@ -3028,31 +3024,31 @@ fn test_ls_path() { let file1 = "file1"; let file2 = "file2"; let dir = "dir"; - let path = &format!("{}/{}", dir, file2); + let path = &format!("{dir}/{file2}"); at.mkdir(dir); at.touch(file1); at.touch(path); - let expected_stdout = &format!("{}\n", path); + let expected_stdout = &format!("{path}\n"); scene.ucmd().arg(path).run().stdout_is(expected_stdout); - let expected_stdout = &format!("./{}\n", path); + let expected_stdout = &format!("./{path}\n"); scene .ucmd() - .arg(format!("./{}", path)) + .arg(format!("./{path}")) .run() .stdout_is(expected_stdout); let abs_path = format!("{}/{}", at.as_string(), path); let expected_stdout = if cfg!(windows) { - format!("\'{}\'\n", abs_path) + format!("\'{abs_path}\'\n") } else { - format!("{}\n", abs_path) + format!("{abs_path}\n") }; scene.ucmd().arg(&abs_path).run().stdout_is(expected_stdout); - let expected_stdout = format!("{}\n{}\n", path, file1); + let expected_stdout = format!("{path}\n{file1}\n"); scene .ucmd() .arg(file1) diff --git a/tests/by-util/test_mktemp.rs b/tests/by-util/test_mktemp.rs index 4650eb2fd..d6926c41b 100644 --- a/tests/by-util/test_mktemp.rs +++ b/tests/by-util/test_mktemp.rs @@ -473,8 +473,7 @@ fn test_tmpdir_absolute_path() { .args(&["--tmpdir=a", path]) .fails() .stderr_only(format!( - "mktemp: invalid template, '{}'; with --tmpdir, it may not be absolute\n", - path + "mktemp: invalid template, '{path}'; with --tmpdir, it may not be absolute\n" )); } @@ -691,7 +690,7 @@ fn test_tmpdir_env_var() { let filename = result.no_stderr().stdout_str().trim_end(); #[cfg(not(windows))] { - let template = format!(".{}tmp.XXXXXXXXXX", MAIN_SEPARATOR); + let template = format!(".{MAIN_SEPARATOR}tmp.XXXXXXXXXX"); assert_matches_template!(&template, filename); } // On Windows, `env::temp_dir()` seems to give an absolute path @@ -720,7 +719,7 @@ fn test_tmpdir_env_var() { let filename = result.no_stderr().stdout_str().trim_end(); #[cfg(not(windows))] { - let template = format!(".{}XXX", MAIN_SEPARATOR); + let template = format!(".{MAIN_SEPARATOR}XXX"); assert_matches_template!(&template, filename); } #[cfg(windows)] diff --git a/tests/by-util/test_mv.rs b/tests/by-util/test_mv.rs index 54c87da58..93693279b 100644 --- a/tests/by-util/test_mv.rs +++ b/tests/by-util/test_mv.rs @@ -55,7 +55,7 @@ fn test_mv_move_file_into_dir() { ucmd.arg(file).arg(dir).succeeds().no_stderr(); - assert!(at.file_exists(&format!("{}/{}", dir, file))); + assert!(at.file_exists(&format!("{dir}/{file}"))); } #[test] @@ -67,17 +67,17 @@ fn test_mv_move_file_between_dirs() { at.mkdir(dir1); at.mkdir(dir2); - at.touch(&format!("{}/{}", dir1, file)); + at.touch(&format!("{dir1}/{file}")); - assert!(at.file_exists(&format!("{}/{}", dir1, file))); + assert!(at.file_exists(&format!("{dir1}/{file}"))); - ucmd.arg(&format!("{}/{}", dir1, file)) + ucmd.arg(&format!("{dir1}/{file}")) .arg(dir2) .succeeds() .no_stderr(); - assert!(!at.file_exists(&format!("{}/{}", dir1, file))); - assert!(at.file_exists(&format!("{}/{}", dir2, file))); + assert!(!at.file_exists(&format!("{dir1}/{file}"))); + assert!(at.file_exists(&format!("{dir2}/{file}"))); } #[test] @@ -94,7 +94,7 @@ fn test_mv_strip_slashes() { scene.ucmd().arg(&source).arg(dir).fails(); - assert!(!at.file_exists(&format!("{}/{}", dir, file))); + assert!(!at.file_exists(&format!("{dir}/{file}"))); scene .ucmd() @@ -104,7 +104,7 @@ fn test_mv_strip_slashes() { .succeeds() .no_stderr(); - assert!(at.file_exists(&format!("{}/{}", dir, file))); + assert!(at.file_exists(&format!("{dir}/{file}"))); } #[test] @@ -124,8 +124,8 @@ fn test_mv_multiple_files() { .succeeds() .no_stderr(); - assert!(at.file_exists(&format!("{}/{}", target_dir, file_a))); - assert!(at.file_exists(&format!("{}/{}", target_dir, file_b))); + assert!(at.file_exists(&format!("{target_dir}/{file_a}"))); + assert!(at.file_exists(&format!("{target_dir}/{file_b}"))); } #[test] @@ -145,8 +145,8 @@ fn test_mv_multiple_folders() { .succeeds() .no_stderr(); - assert!(at.dir_exists(&format!("{}/{}", target_dir, dir_a))); - assert!(at.dir_exists(&format!("{}/{}", target_dir, dir_b))); + assert!(at.dir_exists(&format!("{target_dir}/{dir_a}"))); + assert!(at.dir_exists(&format!("{target_dir}/{dir_b}"))); } #[test] @@ -262,10 +262,10 @@ fn test_mv_same_file() { let file_a = "test_mv_same_file_a"; at.touch(file_a); - ucmd.arg(file_a).arg(file_a).fails().stderr_is(format!( - "mv: '{f}' and '{f}' are the same file\n", - f = file_a, - )); + ucmd.arg(file_a) + .arg(file_a) + .fails() + .stderr_is(format!("mv: '{file_a}' and '{file_a}' are the same file\n",)); } #[test] @@ -275,8 +275,7 @@ fn test_mv_same_file_not_dot_dir() { at.mkdir(dir); ucmd.arg(dir).arg(dir).fails().stderr_is(format!( - "mv: cannot move '{d}' to a subdirectory of itself, '{d}/{d}'\n", - d = dir, + "mv: cannot move '{dir}' to a subdirectory of itself, '{dir}/{dir}'\n", )); } @@ -306,7 +305,7 @@ fn test_mv_simple_backup() { assert!(!at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(at.file_exists(&format!("{}~", file_b))); + assert!(at.file_exists(&format!("{file_b}~"))); } #[test] @@ -325,7 +324,7 @@ fn test_mv_simple_backup_with_file_extension() { assert!(!at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(at.file_exists(&format!("{}~", file_b))); + assert!(at.file_exists(&format!("{file_b}~"))); } #[test] @@ -340,7 +339,7 @@ fn test_mv_arg_backup_arg_first() { assert!(!at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(at.file_exists(&format!("{}~", file_b))); + assert!(at.file_exists(&format!("{file_b}~"))); } #[test] @@ -353,7 +352,7 @@ fn test_mv_custom_backup_suffix() { at.touch(file_a); at.touch(file_b); ucmd.arg("-b") - .arg(format!("--suffix={}", suffix)) + .arg(format!("--suffix={suffix}")) .arg(file_a) .arg(file_b) .succeeds() @@ -361,7 +360,7 @@ fn test_mv_custom_backup_suffix() { assert!(!at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(at.file_exists(&format!("{}{}", file_b, suffix))); + assert!(at.file_exists(&format!("{file_b}{suffix}"))); } #[test] @@ -374,7 +373,7 @@ fn test_mv_custom_backup_suffix_hyphen_value() { at.touch(file_a); at.touch(file_b); ucmd.arg("-b") - .arg(format!("--suffix={}", suffix)) + .arg(format!("--suffix={suffix}")) .arg(file_a) .arg(file_b) .succeeds() @@ -382,7 +381,7 @@ fn test_mv_custom_backup_suffix_hyphen_value() { assert!(!at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(at.file_exists(&format!("{}{}", file_b, suffix))); + assert!(at.file_exists(&format!("{file_b}{suffix}"))); } #[test] @@ -402,7 +401,7 @@ fn test_mv_custom_backup_suffix_via_env() { assert!(!at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(at.file_exists(&format!("{}{}", file_b, suffix))); + assert!(at.file_exists(&format!("{file_b}{suffix}"))); } #[test] @@ -421,7 +420,7 @@ fn test_mv_backup_numbered_with_t() { assert!(!at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(at.file_exists(&format!("{}.~1~", file_b))); + assert!(at.file_exists(&format!("{file_b}.~1~"))); } #[test] @@ -440,7 +439,7 @@ fn test_mv_backup_numbered() { assert!(!at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(at.file_exists(&format!("{}.~1~", file_b))); + assert!(at.file_exists(&format!("{file_b}.~1~"))); } #[test] @@ -459,7 +458,7 @@ fn test_mv_backup_existing() { assert!(!at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(at.file_exists(&format!("{}~", file_b))); + assert!(at.file_exists(&format!("{file_b}~"))); } #[test] @@ -478,7 +477,7 @@ fn test_mv_backup_nil() { assert!(!at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(at.file_exists(&format!("{}~", file_b))); + assert!(at.file_exists(&format!("{file_b}~"))); } #[test] @@ -499,7 +498,7 @@ fn test_mv_numbered_if_existing_backup_existing() { assert!(at.file_exists(file_b)); assert!(at.file_exists(file_b_backup)); - assert!(at.file_exists(&format!("{}.~2~", file_b))); + assert!(at.file_exists(&format!("{file_b}.~2~"))); } #[test] @@ -520,7 +519,7 @@ fn test_mv_numbered_if_existing_backup_nil() { assert!(at.file_exists(file_b)); assert!(at.file_exists(file_b_backup)); - assert!(at.file_exists(&format!("{}.~2~", file_b))); + assert!(at.file_exists(&format!("{file_b}.~2~"))); } #[test] @@ -539,7 +538,7 @@ fn test_mv_backup_simple() { assert!(!at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(at.file_exists(&format!("{}~", file_b))); + assert!(at.file_exists(&format!("{file_b}~"))); } #[test] @@ -558,7 +557,7 @@ fn test_mv_backup_never() { assert!(!at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(at.file_exists(&format!("{}~", file_b))); + assert!(at.file_exists(&format!("{file_b}~"))); } #[test] @@ -577,7 +576,7 @@ fn test_mv_backup_none() { assert!(!at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(!at.file_exists(&format!("{}~", file_b))); + assert!(!at.file_exists(&format!("{file_b}~"))); } #[test] @@ -596,7 +595,7 @@ fn test_mv_backup_off() { assert!(!at.file_exists(file_a)); assert!(at.file_exists(file_b)); - assert!(!at.file_exists(&format!("{}~", file_b))); + assert!(!at.file_exists(&format!("{file_b}~"))); } #[test] @@ -661,8 +660,8 @@ fn test_mv_target_dir() { assert!(!at.file_exists(file_a)); assert!(!at.file_exists(file_b)); - assert!(at.file_exists(&format!("{}/{}", dir, file_a))); - assert!(at.file_exists(&format!("{}/{}", dir, file_b))); + assert!(at.file_exists(&format!("{dir}/{file_a}"))); + assert!(at.file_exists(&format!("{dir}/{file_b}"))); } #[test] @@ -676,7 +675,7 @@ fn test_mv_target_dir_single_source() { ucmd.arg("-t").arg(dir).arg(file).succeeds().no_stderr(); assert!(!at.file_exists(file)); - assert!(at.file_exists(&format!("{}/{}", dir, file))); + assert!(at.file_exists(&format!("{dir}/{file}"))); } #[test] @@ -729,14 +728,11 @@ fn test_mv_backup_dir() { .arg(dir_a) .arg(dir_b) .succeeds() - .stdout_only(format!( - "'{}' -> '{}' (backup: '{}~')\n", - dir_a, dir_b, dir_b - )); + .stdout_only(format!("'{dir_a}' -> '{dir_b}' (backup: '{dir_b}~')\n")); assert!(!at.dir_exists(dir_a)); assert!(at.dir_exists(dir_b)); - assert!(at.dir_exists(&format!("{}~", dir_b))); + assert!(at.dir_exists(&format!("{dir_b}~"))); } #[test] @@ -772,8 +768,7 @@ fn test_mv_errors() { .arg(dir) .fails() .stderr_is(format!( - "mv: cannot overwrite directory '{}' with non-directory\n", - dir + "mv: cannot overwrite directory '{dir}' with non-directory\n" )); // $ at.mkdir dir && at.touch file @@ -805,7 +800,7 @@ fn test_mv_verbose() { .arg(file_a) .arg(file_b) .succeeds() - .stdout_only(format!("'{}' -> '{}'\n", file_a, file_b)); + .stdout_only(format!("'{file_a}' -> '{file_b}'\n")); at.touch(file_a); scene @@ -814,10 +809,7 @@ fn test_mv_verbose() { .arg(file_a) .arg(file_b) .succeeds() - .stdout_only(format!( - "'{}' -> '{}' (backup: '{}~')\n", - file_a, file_b, file_b - )); + .stdout_only(format!("'{file_a}' -> '{file_b}' (backup: '{file_b}~')\n")); } #[test] diff --git a/tests/by-util/test_numfmt.rs b/tests/by-util/test_numfmt.rs index ca7f8ea48..e162196f2 100644 --- a/tests/by-util/test_numfmt.rs +++ b/tests/by-util/test_numfmt.rs @@ -60,8 +60,7 @@ fn test_from_iec_i_requires_suffix() { .fails() .code_is(2) .stderr_is(format!( - "numfmt: missing 'i' suffix in input: '{}' (e.g Ki/Mi/Gi)\n", - number + "numfmt: missing 'i' suffix in input: '{number}' (e.g Ki/Mi/Gi)\n" )); } } @@ -687,11 +686,11 @@ fn test_invalid_padding_value() { for padding_value in padding_values { new_ucmd!() - .arg(format!("--padding={}", padding_value)) + .arg(format!("--padding={padding_value}")) .arg("5") .fails() .code_is(1) - .stderr_contains(format!("invalid padding value '{}'", padding_value)); + .stderr_contains(format!("invalid padding value '{padding_value}'")); } } @@ -719,10 +718,10 @@ fn test_invalid_unit_size() { for command in commands { for invalid_size in &invalid_sizes { new_ucmd!() - .arg(format!("--{}-unit={}", command, invalid_size)) + .arg(format!("--{command}-unit={invalid_size}")) .fails() .code_is(1) - .stderr_contains(format!("invalid unit size: '{}'", invalid_size)); + .stderr_contains(format!("invalid unit size: '{invalid_size}'")); } } } @@ -737,8 +736,7 @@ fn test_valid_but_forbidden_suffix() { .fails() .code_is(2) .stderr_contains(format!( - "rejecting suffix in input: '{}' (consider using --from)", - number + "rejecting suffix in input: '{number}' (consider using --from)" )); } } @@ -805,7 +803,7 @@ fn test_format_with_zero_padding() { for format in formats { new_ucmd!() - .args(&[format!("--format={}", format), String::from("1234")]) + .args(&[format!("--format={format}"), String::from("1234")]) .succeeds() .stdout_is("001234\n"); } @@ -851,7 +849,7 @@ fn test_format_with_precision() { new_ucmd!() .args(&["--format=%.1f", input]) .succeeds() - .stdout_is(format!("{}\n", expected)); + .stdout_is(format!("{expected}\n")); } let values = vec![("0.99", "0.99"), ("1", "1.00"), ("1.01", "1.01")]; @@ -860,7 +858,7 @@ fn test_format_with_precision() { new_ucmd!() .args(&["--format=%.2f", input]) .succeeds() - .stdout_is(format!("{}\n", expected)); + .stdout_is(format!("{expected}\n")); } } @@ -872,7 +870,7 @@ fn test_format_with_precision_and_down_rounding() { new_ucmd!() .args(&["--format=%.1f", input, "--round=down"]) .succeeds() - .stdout_is(format!("{}\n", expected)); + .stdout_is(format!("{expected}\n")); } } @@ -883,12 +881,12 @@ fn test_format_with_precision_and_to_arg() { for (format, expected) in values { new_ucmd!() .args(&[ - format!("--format={}", format), + format!("--format={format}"), "9991239123".to_string(), "--to=si".to_string(), ]) .succeeds() - .stdout_is(format!("{}\n", expected)); + .stdout_is(format!("{expected}\n")); } } @@ -900,7 +898,7 @@ fn test_format_preserve_trailing_zeros_if_no_precision_is_specified() { new_ucmd!() .args(&["--format=%f", value]) .succeeds() - .stdout_is(format!("{}\n", value)); + .stdout_is(format!("{value}\n")); } } @@ -910,10 +908,10 @@ fn test_format_without_percentage_directive() { for invalid_format in invalid_formats { new_ucmd!() - .arg(format!("--format={}", invalid_format)) + .arg(format!("--format={invalid_format}")) .fails() .code_is(1) - .stderr_contains(format!("format '{}' has no % directive", invalid_format)); + .stderr_contains(format!("format '{invalid_format}' has no % directive")); } } @@ -922,10 +920,10 @@ fn test_format_with_percentage_directive_at_end() { let invalid_format = "hello%"; new_ucmd!() - .arg(format!("--format={}", invalid_format)) + .arg(format!("--format={invalid_format}")) .fails() .code_is(1) - .stderr_contains(format!("format '{}' ends in %", invalid_format)); + .stderr_contains(format!("format '{invalid_format}' ends in %")); } #[test] @@ -933,12 +931,11 @@ fn test_format_with_too_many_percentage_directives() { let invalid_format = "%f %f"; new_ucmd!() - .arg(format!("--format={}", invalid_format)) + .arg(format!("--format={invalid_format}")) .fails() .code_is(1) .stderr_contains(format!( - "format '{}' has too many % directives", - invalid_format + "format '{invalid_format}' has too many % directives" )); } @@ -948,12 +945,11 @@ fn test_format_with_invalid_format() { for invalid_format in invalid_formats { new_ucmd!() - .arg(format!("--format={}", invalid_format)) + .arg(format!("--format={invalid_format}")) .fails() .code_is(1) .stderr_contains(format!( - "invalid format '{}', directive must be %[0]['][-][N][.][N]f", - invalid_format + "invalid format '{invalid_format}', directive must be %[0]['][-][N][.][N]f" )); } } @@ -962,12 +958,11 @@ fn test_format_with_invalid_format() { fn test_format_with_width_overflow() { let invalid_format = "%18446744073709551616f"; new_ucmd!() - .arg(format!("--format={}", invalid_format)) + .arg(format!("--format={invalid_format}")) .fails() .code_is(1) .stderr_contains(format!( - "invalid format '{}' (width overflow)", - invalid_format + "invalid format '{invalid_format}' (width overflow)" )); } @@ -977,10 +972,10 @@ fn test_format_with_invalid_precision() { for invalid_format in invalid_formats { new_ucmd!() - .arg(format!("--format={}", invalid_format)) + .arg(format!("--format={invalid_format}")) .fails() .code_is(1) - .stderr_contains(format!("invalid precision in format '{}'", invalid_format)); + .stderr_contains(format!("invalid precision in format '{invalid_format}'")); } } diff --git a/tests/by-util/test_od.rs b/tests/by-util/test_od.rs index e298ef432..c1857f3bc 100644 --- a/tests/by-util/test_od.rs +++ b/tests/by-util/test_od.rs @@ -76,7 +76,7 @@ fn test_2files() { let file2 = tmpdir.join("test2"); for (n, a) in [(1, "a"), (2, "b")] { - println!("number: {} letter:{}", n, a); + println!("number: {n} letter:{a}"); } // spell-checker:disable-next-line @@ -849,34 +849,27 @@ fn test_od_invalid_bytes() { ]; for option in &options { new_ucmd!() - .arg(format!("{}={}", option, INVALID_SIZE)) + .arg(format!("{option}={INVALID_SIZE}")) .arg("file") .fails() .code_is(1) - .stderr_only(format!( - "od: invalid {} argument '{}'\n", - option, INVALID_SIZE - )); + .stderr_only(format!("od: invalid {option} argument '{INVALID_SIZE}'\n")); new_ucmd!() - .arg(format!("{}={}", option, INVALID_SUFFIX)) + .arg(format!("{option}={INVALID_SUFFIX}")) .arg("file") .fails() .code_is(1) .stderr_only(format!( - "od: invalid suffix in {} argument '{}'\n", - option, INVALID_SUFFIX + "od: invalid suffix in {option} argument '{INVALID_SUFFIX}'\n" )); #[cfg(not(target_pointer_width = "128"))] new_ucmd!() - .arg(format!("{}={}", option, BIG_SIZE)) + .arg(format!("{option}={BIG_SIZE}")) .arg("file") .fails() .code_is(1) - .stderr_only(format!( - "od: {} argument '{}' too large\n", - option, BIG_SIZE - )); + .stderr_only(format!("od: {option} argument '{BIG_SIZE}' too large\n")); } } diff --git a/tests/by-util/test_paste.rs b/tests/by-util/test_paste.rs index 088a27eae..977645bee 100644 --- a/tests/by-util/test_paste.rs +++ b/tests/by-util/test_paste.rs @@ -162,7 +162,7 @@ fn test_data() { let (at, mut ucmd) = at_and_ucmd!(); let mut ins = vec![]; for (i, _in) in example.ins.iter().enumerate() { - let file = format!("in{}", i); + let file = format!("in{i}"); at.write(&file, _in); ins.push(file); } diff --git a/tests/by-util/test_pinky.rs b/tests/by-util/test_pinky.rs index 6dd85b6be..da4aab605 100644 --- a/tests/by-util/test_pinky.rs +++ b/tests/by-util/test_pinky.rs @@ -35,8 +35,7 @@ fn test_long_format() { let real_name = user_info.replace('&', &pw.name.capitalize()); let ts = TestScenario::new(util_name!()); ts.ucmd().arg("-l").arg(login).succeeds().stdout_is(format!( - "Login name: {:<28}In real life: {}\nDirectory: {:<29}Shell: {}\n\n", - login, real_name, user_dir, user_shell + "Login name: {login:<28}In real life: {real_name}\nDirectory: {user_dir:<29}Shell: {user_shell}\n\n" )); ts.ucmd() @@ -44,8 +43,7 @@ fn test_long_format() { .arg(login) .succeeds() .stdout_is(format!( - "Login name: {:<28}In real life: {1}\n\n", - login, real_name + "Login name: {login:<28}In real life: {real_name}\n\n" )); } diff --git a/tests/by-util/test_readlink.rs b/tests/by-util/test_readlink.rs index 2bc983b02..4441aebd9 100644 --- a/tests/by-util/test_readlink.rs +++ b/tests/by-util/test_readlink.rs @@ -29,8 +29,8 @@ fn test_canonicalize() { let (at, mut ucmd) = at_and_ucmd!(); let actual = ucmd.arg("-f").arg(".").run().stdout_move_str(); let expect = at.root_dir_resolved() + "\n"; - println!("actual: {:?}", actual); - println!("expect: {:?}", expect); + println!("actual: {actual:?}"); + println!("expect: {expect:?}"); assert_eq!(actual, expect); } @@ -39,8 +39,8 @@ fn test_canonicalize_existing() { let (at, mut ucmd) = at_and_ucmd!(); let actual = ucmd.arg("-e").arg(".").run().stdout_move_str(); let expect = at.root_dir_resolved() + "\n"; - println!("actual: {:?}", actual); - println!("expect: {:?}", expect); + println!("actual: {actual:?}"); + println!("expect: {expect:?}"); assert_eq!(actual, expect); } @@ -49,8 +49,8 @@ fn test_canonicalize_missing() { let (at, mut ucmd) = at_and_ucmd!(); let actual = ucmd.arg("-m").arg(GIBBERISH).run().stdout_move_str(); let expect = path_concat!(at.root_dir_resolved(), GIBBERISH) + "\n"; - println!("actual: {:?}", actual); - println!("expect: {:?}", expect); + println!("actual: {actual:?}"); + println!("expect: {expect:?}"); assert_eq!(actual, expect); } @@ -61,8 +61,8 @@ fn test_long_redirection_to_current_dir() { let dir = path_concat!(".", ..128); let actual = ucmd.arg("-n").arg("-m").arg(dir).run().stdout_move_str(); let expect = at.root_dir_resolved(); - println!("actual: {:?}", actual); - println!("expect: {:?}", expect); + println!("actual: {actual:?}"); + println!("expect: {expect:?}"); assert_eq!(actual, expect); } @@ -77,8 +77,8 @@ fn test_long_redirection_to_root() { .run() .stdout_move_str(); let expect = get_root_path(); - println!("actual: {:?}", actual); - println!("expect: {:?}", expect); + println!("actual: {actual:?}"); + println!("expect: {expect:?}"); assert_eq!(actual, expect); } @@ -214,21 +214,21 @@ fn test_canonicalize_trailing_slash_regfile() { .stdout_contains("regfile"); scene .ucmd() - .args(&["-fv", &format!("./{}/", name)]) + .args(&["-fv", &format!("./{name}/")]) .fails() .code_is(1) .stderr_contains(NOT_A_DIRECTORY) .no_stdout(); scene .ucmd() - .args(&["-fv", &format!("{}/more", name)]) + .args(&["-fv", &format!("{name}/more")]) .fails() .code_is(1) .stderr_contains(NOT_A_DIRECTORY) .no_stdout(); scene .ucmd() - .args(&["-fv", &format!("./{}/more/", name)]) + .args(&["-fv", &format!("./{name}/more/")]) .fails() .code_is(1) .stderr_contains(NOT_A_DIRECTORY) @@ -250,28 +250,28 @@ fn test_canonicalize_trailing_slash_subdir() { .stdout_contains("subdir"); scene .ucmd() - .args(&["-f", &format!("./{}/", name)]) + .args(&["-f", &format!("./{name}/")]) .succeeds() .stdout_contains("subdir"); scene .ucmd() - .args(&["-f", &format!("{}/more", name)]) + .args(&["-f", &format!("{name}/more")]) .succeeds() .stdout_contains(path_concat!("subdir", "more")); scene .ucmd() - .args(&["-f", &format!("./{}/more/", name)]) + .args(&["-f", &format!("./{name}/more/")]) .succeeds() .stdout_contains(path_concat!("subdir", "more")); scene .ucmd() - .args(&["-f", &format!("{}/more/more2", name)]) + .args(&["-f", &format!("{name}/more/more2")]) .fails() .code_is(1) .no_stdout(); scene .ucmd() - .args(&["-f", &format!("./{}/more/more2/", name)]) + .args(&["-f", &format!("./{name}/more/more2/")]) .fails() .code_is(1) .no_stdout(); @@ -291,18 +291,18 @@ fn test_canonicalize_trailing_slash_missing() { .stdout_contains("missing"); scene .ucmd() - .args(&["-f", &format!("./{}/", name)]) + .args(&["-f", &format!("./{name}/")]) .succeeds() .stdout_contains("missing"); scene .ucmd() - .args(&["-f", &format!("{}/more", name)]) + .args(&["-f", &format!("{name}/more")]) .fails() .code_is(1) .no_stdout(); scene .ucmd() - .args(&["-f", &format!("./{}/more/", name)]) + .args(&["-f", &format!("./{name}/more/")]) .fails() .code_is(1) .no_stdout(); diff --git a/tests/by-util/test_realpath.rs b/tests/by-util/test_realpath.rs index 63eb7a57c..5ff98c78d 100644 --- a/tests/by-util/test_realpath.rs +++ b/tests/by-util/test_realpath.rs @@ -255,8 +255,8 @@ fn test_realpath_when_symlink_part_is_missing() { at.relative_symlink_file("../dir2/baz", "dir1/foo3"); at.symlink_file("dir3/bar", "dir1/foo4"); - let expect1 = format!("dir2{}bar", MAIN_SEPARATOR); - let expect2 = format!("dir2{}baz", MAIN_SEPARATOR); + let expect1 = format!("dir2{MAIN_SEPARATOR}bar"); + let expect2 = format!("dir2{MAIN_SEPARATOR}baz"); ucmd.args(&["dir1/foo1", "dir1/foo2", "dir1/foo3", "dir1/foo4"]) .run() diff --git a/tests/by-util/test_relpath.rs b/tests/by-util/test_relpath.rs index 52b829fdf..753b5d755 100644 --- a/tests/by-util/test_relpath.rs +++ b/tests/by-util/test_relpath.rs @@ -87,7 +87,7 @@ fn test_relpath_with_from_no_d() { .arg(to) .arg(from) .succeeds() - .stdout_only(&format!("{}\n", expected)); + .stdout_only(&format!("{expected}\n")); } } @@ -108,7 +108,7 @@ fn test_relpath_with_from_with_d() { .ucmd() .arg(to) .arg(from) - .arg(&format!("-d{}", pwd)) + .arg(&format!("-d{pwd}")) .succeeds() .stdout_move_str(); // relax rules for windows test environment @@ -138,10 +138,10 @@ fn test_relpath_no_from_no_d() { let _result_stdout = scene.ucmd().arg(to).succeeds().stdout_move_str(); #[cfg(not(windows))] - assert_eq!(_result_stdout, format!("{}\n", to)); + assert_eq!(_result_stdout, format!("{to}\n")); // relax rules for windows test environment #[cfg(windows)] - assert!(_result_stdout.ends_with(&format!("{}\n", to))); + assert!(_result_stdout.ends_with(&format!("{to}\n"))); } } @@ -159,7 +159,7 @@ fn test_relpath_no_from_with_d() { let _result_stdout = scene .ucmd() .arg(to) - .arg(&format!("-d{}", pwd)) + .arg(&format!("-d{pwd}")) .succeeds() .stdout_move_str(); // relax rules for windows test environment diff --git a/tests/by-util/test_rm.rs b/tests/by-util/test_rm.rs index 4e5261d25..ce534af8d 100644 --- a/tests/by-util/test_rm.rs +++ b/tests/by-util/test_rm.rs @@ -25,8 +25,7 @@ fn test_rm_failed() { let file = "test_rm_one_file"; // Doesn't exist ucmd.arg(file).fails().stderr_contains(&format!( - "cannot remove '{}': No such file or directory", - file + "cannot remove '{file}': No such file or directory" )); } @@ -136,7 +135,7 @@ fn test_rm_empty_directory_verbose() { .arg("-v") .arg(dir) .succeeds() - .stdout_only(format!("removed directory '{}'\n", dir)); + .stdout_only(format!("removed directory '{dir}'\n")); assert!(!at.dir_exists(dir)); } @@ -145,7 +144,7 @@ fn test_rm_empty_directory_verbose() { fn test_rm_non_empty_directory() { let (at, mut ucmd) = at_and_ucmd!(); let dir = "test_rm_non_empty_dir"; - let file_a = &format!("{}/test_rm_non_empty_file_a", dir); + let file_a = &format!("{dir}/test_rm_non_empty_file_a"); at.mkdir(dir); at.touch(file_a); @@ -153,7 +152,7 @@ fn test_rm_non_empty_directory() { ucmd.arg("-d") .arg(dir) .fails() - .stderr_contains(&format!("cannot remove '{}': Directory not empty", dir)); + .stderr_contains(&format!("cannot remove '{dir}': Directory not empty")); assert!(at.file_exists(file_a)); assert!(at.dir_exists(dir)); } @@ -208,7 +207,7 @@ fn test_rm_directory_without_flag() { ucmd.arg(dir) .fails() - .stderr_contains(&format!("cannot remove '{}': Is a directory", dir)); + .stderr_contains(&format!("cannot remove '{dir}': Is a directory")); } #[test] @@ -224,7 +223,7 @@ fn test_rm_verbose() { .arg(file_a) .arg(file_b) .succeeds() - .stdout_only(format!("removed '{}'\nremoved '{}'\n", file_a, file_b)); + .stdout_only(format!("removed '{file_a}'\nremoved '{file_b}'\n")); } #[test] @@ -259,7 +258,7 @@ fn test_rm_symlink_dir() { .ucmd() .arg(link) .fails() - .stderr_contains(&format!("cannot remove '{}': Is a directory", link)); + .stderr_contains(&format!("cannot remove '{link}': Is a directory")); assert!(at.dir_exists(link)); @@ -293,7 +292,7 @@ fn test_rm_no_operand() { fn test_rm_verbose_slash() { let (at, mut ucmd) = at_and_ucmd!(); let dir = "test_rm_verbose_slash_directory"; - let file_a = &format!("{}/test_rm_verbose_slash_file_a", dir); + let file_a = &format!("{dir}/test_rm_verbose_slash_file_a"); at.mkdir(dir); at.touch(file_a); @@ -307,11 +306,10 @@ fn test_rm_verbose_slash() { ucmd.arg("-r") .arg("-f") .arg("-v") - .arg(&format!("{}///", dir)) + .arg(&format!("{dir}///")) .succeeds() .stdout_only(format!( - "removed '{}'\nremoved directory '{}'\n", - file_a_normalized, dir + "removed '{file_a_normalized}'\nremoved directory '{dir}'\n" )); assert!(!at.dir_exists(dir)); @@ -359,7 +357,7 @@ fn test_rm_descend_directory() { // Needed for talking with stdin on platforms where CRLF or LF matters const END_OF_LINE: &str = if cfg!(windows) { "\r\n" } else { "\n" }; - let yes = format!("y{}", END_OF_LINE); + let yes = format!("y{END_OF_LINE}"); let scene = TestScenario::new(util_name!()); let at = &scene.fixtures; @@ -414,7 +412,7 @@ fn test_rm_prompts() { answers.sort(); - let yes = format!("y{}", END_OF_LINE); + let yes = format!("y{END_OF_LINE}"); let scene = TestScenario::new(util_name!()); let at = &scene.fixtures; @@ -463,7 +461,7 @@ fn test_rm_prompts() { let mut trimmed_output = Vec::new(); for string in result.stderr_str().split("rm: ") { if !string.is_empty() { - let trimmed_string = format!("rm: {}", string).trim().to_string(); + let trimmed_string = format!("rm: {string}").trim().to_string(); trimmed_output.push(trimmed_string); } } @@ -484,7 +482,7 @@ fn test_rm_force_prompts_order() { // Needed for talking with stdin on platforms where CRLF or LF matters const END_OF_LINE: &str = if cfg!(windows) { "\r\n" } else { "\n" }; - let yes = format!("y{}", END_OF_LINE); + let yes = format!("y{END_OF_LINE}"); let scene = TestScenario::new(util_name!()); let at = &scene.fixtures; diff --git a/tests/by-util/test_rmdir.rs b/tests/by-util/test_rmdir.rs index 13a176989..df86e2423 100644 --- a/tests/by-util/test_rmdir.rs +++ b/tests/by-util/test_rmdir.rs @@ -57,7 +57,7 @@ fn test_rmdir_nonempty_directory_no_parents() { ucmd.arg(DIR) .fails() - .stderr_is(format!("rmdir: failed to remove 'dir': {}\n", NOT_EMPTY)); + .stderr_is(format!("rmdir: failed to remove 'dir': {NOT_EMPTY}\n")); assert!(at.dir_exists(DIR)); } @@ -70,8 +70,7 @@ fn test_rmdir_nonempty_directory_with_parents() { at.touch(NESTED_DIR_FILE); ucmd.arg("-p").arg(NESTED_DIR).fails().stderr_is(format!( - "rmdir: failed to remove 'dir/ect/ory': {}\n", - NOT_EMPTY + "rmdir: failed to remove 'dir/ect/ory': {NOT_EMPTY}\n" )); assert!(at.dir_exists(NESTED_DIR)); @@ -119,8 +118,7 @@ fn test_rmdir_not_a_directory() { .fails() .no_stdout() .stderr_is(format!( - "rmdir: failed to remove 'file': {}\n", - NOT_A_DIRECTORY + "rmdir: failed to remove 'file': {NOT_A_DIRECTORY}\n" )); } @@ -152,8 +150,7 @@ fn test_verbose_multi() { rmdir: removing directory, 'dir'\n", ) .stderr_is(format!( - "rmdir: failed to remove 'does_not_exist': {}\n", - NOT_FOUND + "rmdir: failed to remove 'does_not_exist': {NOT_FOUND}\n" )); } @@ -171,10 +168,7 @@ fn test_verbose_nested_failure() { "rmdir: removing directory, 'dir/ect/ory'\n\ rmdir: removing directory, 'dir/ect'\n", ) - .stderr_is(format!( - "rmdir: failed to remove 'dir/ect': {}\n", - NOT_EMPTY - )); + .stderr_is(format!("rmdir: failed to remove 'dir/ect': {NOT_EMPTY}\n")); } #[cfg(unix)] @@ -214,8 +208,7 @@ fn test_rmdir_remove_symlink_file() { at.symlink_file("file", "fl"); ucmd.arg("fl/").fails().stderr_is(format!( - "rmdir: failed to remove 'fl/': {}\n", - NOT_A_DIRECTORY + "rmdir: failed to remove 'fl/': {NOT_A_DIRECTORY}\n" )); } diff --git a/tests/by-util/test_sort.rs b/tests/by-util/test_sort.rs index 73679c497..8a03432af 100644 --- a/tests/by-util/test_sort.rs +++ b/tests/by-util/test_sort.rs @@ -12,17 +12,17 @@ use crate::common::util::*; fn test_helper(file_name: &str, possible_args: &[&str]) { for args in possible_args { new_ucmd!() - .arg(format!("{}.txt", file_name)) + .arg(format!("{file_name}.txt")) .args(&args.split_whitespace().collect::>()) .succeeds() - .stdout_is_fixture(format!("{}.expected", file_name)); + .stdout_is_fixture(format!("{file_name}.expected")); new_ucmd!() - .arg(format!("{}.txt", file_name)) + .arg(format!("{file_name}.txt")) .arg("--debug") .args(&args.split_whitespace().collect::>()) .succeeds() - .stdout_is_fixture(format!("{}.expected.debug", file_name)); + .stdout_is_fixture(format!("{file_name}.expected.debug")); } } @@ -810,21 +810,21 @@ fn test_dictionary_and_nonprinting_conflicts() { for restricted_arg in ["d", "i"] { for conflicting_arg in &conflicting_args { new_ucmd!() - .arg(&format!("-{}{}", restricted_arg, conflicting_arg)) + .arg(&format!("-{restricted_arg}{conflicting_arg}")) .fails(); } for conflicting_arg in &conflicting_args { new_ucmd!() .args(&[ - format!("-{}", restricted_arg).as_str(), + format!("-{restricted_arg}").as_str(), "-k", - &format!("1,1{}", conflicting_arg), + &format!("1,1{conflicting_arg}"), ]) .succeeds(); } for conflicting_arg in &conflicting_args { new_ucmd!() - .args(&["-k", &format!("1{},1{}", restricted_arg, conflicting_arg)]) + .args(&["-k", &format!("1{restricted_arg},1{conflicting_arg}")]) .fails(); } } diff --git a/tests/by-util/test_split.rs b/tests/by-util/test_split.rs index 50c67927a..a682b1b8c 100644 --- a/tests/by-util/test_split.rs +++ b/tests/by-util/test_split.rs @@ -425,7 +425,7 @@ fn test_numeric_dynamic_suffix_length() { ucmd.args(&["-d", "-b", "1", "ninetyonebytes.txt"]) .succeeds(); for i in 0..90 { - let filename = format!("x{:02}", i); + let filename = format!("x{i:02}"); let contents = file_read(&at, &filename); assert_eq!(contents, "a"); } @@ -447,7 +447,7 @@ fn test_hex_dynamic_suffix_length() { ucmd.args(&["-x", "-b", "1", "twohundredfortyonebytes.txt"]) .succeeds(); for i in 0..240 { - let filename = format!("x{:02x}", i); + let filename = format!("x{i:02x}"); let contents = file_read(&at, &filename); assert_eq!(contents, "a"); } diff --git a/tests/by-util/test_stat.rs b/tests/by-util/test_stat.rs index 5a6fa41f2..b404ef28e 100644 --- a/tests/by-util/test_stat.rs +++ b/tests/by-util/test_stat.rs @@ -53,8 +53,8 @@ fn test_terse_normal_format() { let ts = TestScenario::new(util_name!()); let actual = ts.ucmd().args(&args).succeeds().stdout_move_str(); let expect = unwrap_or_return!(expected_result(&ts, &args)).stdout_move_str(); - println!("actual: {:?}", actual); - println!("expect: {:?}", expect); + println!("actual: {actual:?}"); + println!("expect: {expect:?}"); let v_actual: Vec<&str> = actual.trim().split(' ').collect(); let mut v_expect: Vec<&str> = expect.trim().split(' ').collect(); assert!(!v_expect.is_empty()); @@ -83,8 +83,8 @@ fn test_format_created_time() { let ts = TestScenario::new(util_name!()); let actual = ts.ucmd().args(&args).succeeds().stdout_move_str(); let expect = unwrap_or_return!(expected_result(&ts, &args)).stdout_move_str(); - println!("actual: {:?}", actual); - println!("expect: {:?}", expect); + println!("actual: {actual:?}"); + println!("expect: {expect:?}"); // note: using a regex instead of `split_whitespace()` in order to detect whitespace differences let re = regex::Regex::new(r"\s").unwrap(); let v_actual: Vec<&str> = re.split(&actual).collect(); @@ -108,8 +108,8 @@ fn test_format_created_seconds() { let ts = TestScenario::new(util_name!()); let actual = ts.ucmd().args(&args).succeeds().stdout_move_str(); let expect = unwrap_or_return!(expected_result(&ts, &args)).stdout_move_str(); - println!("actual: {:?}", actual); - println!("expect: {:?}", expect); + println!("actual: {actual:?}"); + println!("expect: {expect:?}"); // note: using a regex instead of `split_whitespace()` in order to detect whitespace differences let re = regex::Regex::new(r"\s").unwrap(); let v_actual: Vec<&str> = re.split(&actual).collect(); diff --git a/tests/by-util/test_tail.rs b/tests/by-util/test_tail.rs index 421f04290..a82d66565 100644 --- a/tests/by-util/test_tail.rs +++ b/tests/by-util/test_tail.rs @@ -621,8 +621,7 @@ fn test_follow_invalid_pid() { .fails() .no_stdout() .stderr_is(format!( - "tail: invalid PID: '{}': number too large to fit in target type\n", - max_pid + "tail: invalid PID: '{max_pid}': number too large to fit in target type\n" )); } @@ -649,7 +648,7 @@ fn test_follow_with_pid() { let mut child = ucmd .arg("-f") - .arg(format!("--pid={}", pid)) + .arg(format!("--pid={pid}")) .arg(FOOBAR_TXT) .arg(FOOBAR_2_TXT) .run_no_wait(); @@ -706,17 +705,17 @@ fn test_single_big_args() { let mut big_input = at.make_file(FILE); for i in 0..LINES { - writeln!(big_input, "Line {}", i).expect("Could not write to FILE"); + writeln!(big_input, "Line {i}").expect("Could not write to FILE"); } big_input.flush().expect("Could not flush FILE"); let mut big_expected = at.make_file(EXPECTED_FILE); for i in (LINES - N_ARG)..LINES { - writeln!(big_expected, "Line {}", i).expect("Could not write to EXPECTED_FILE"); + writeln!(big_expected, "Line {i}").expect("Could not write to EXPECTED_FILE"); } big_expected.flush().expect("Could not flush EXPECTED_FILE"); - ucmd.arg(FILE).arg("-n").arg(format!("{}", N_ARG)).run(); + ucmd.arg(FILE).arg("-n").arg(format!("{N_ARG}")).run(); // .stdout_is(at.read(EXPECTED_FILE)); } @@ -753,21 +752,21 @@ fn test_bytes_big() { let mut big_input = at.make_file(FILE); for i in 0..BYTES { let digit = from_digit((i % 10) as u32, 10).unwrap(); - write!(big_input, "{}", digit).expect("Could not write to FILE"); + write!(big_input, "{digit}").expect("Could not write to FILE"); } big_input.flush().expect("Could not flush FILE"); let mut big_expected = at.make_file(EXPECTED_FILE); for i in (BYTES - N_ARG)..BYTES { let digit = from_digit((i % 10) as u32, 10).unwrap(); - write!(big_expected, "{}", digit).expect("Could not write to EXPECTED_FILE"); + write!(big_expected, "{digit}").expect("Could not write to EXPECTED_FILE"); } big_expected.flush().expect("Could not flush EXPECTED_FILE"); let result = ucmd .arg(FILE) .arg("-c") - .arg(format!("{}", N_ARG)) + .arg(format!("{N_ARG}")) .succeeds() .stdout_move_str(); let expected = at.read(EXPECTED_FILE); @@ -789,13 +788,13 @@ fn test_lines_with_size_suffix() { let mut big_input = at.make_file(FILE); for i in 0..LINES { - writeln!(big_input, "Line {}", i).expect("Could not write to FILE"); + writeln!(big_input, "Line {i}").expect("Could not write to FILE"); } big_input.flush().expect("Could not flush FILE"); let mut big_expected = at.make_file(EXPECTED_FILE); for i in (LINES - N_ARG)..LINES { - writeln!(big_expected, "Line {}", i).expect("Could not write to EXPECTED_FILE"); + writeln!(big_expected, "Line {i}").expect("Could not write to EXPECTED_FILE"); } big_expected.flush().expect("Could not flush EXPECTED_FILE"); @@ -1549,13 +1548,12 @@ fn test_retry9() { "\ tail: 'parent_dir/watched_file' has become inaccessible: No such file or directory\n\ tail: directory containing watched file was removed\n\ - tail: {} cannot be used, reverting to polling\n\ + tail: {BACKEND} cannot be used, reverting to polling\n\ tail: 'parent_dir/watched_file' has appeared; following new file\n\ tail: 'parent_dir/watched_file' has become inaccessible: No such file or directory\n\ tail: 'parent_dir/watched_file' has appeared; following new file\n\ tail: 'parent_dir/watched_file' has become inaccessible: No such file or directory\n\ - tail: 'parent_dir/watched_file' has appeared; following new file\n", - BACKEND + tail: 'parent_dir/watched_file' has appeared; following new file\n" ); let expected_stdout = "foo\nbar\nfoo\nbar\n"; @@ -2281,9 +2279,8 @@ fn test_follow_name_move2() { let file2 = "file2"; let expected_stdout = format!( - "==> {0} <==\n{0}_content\n\n==> {1} <==\n{1}_content\n{0}_content\n\ - more_{1}_content\n\n==> {0} <==\nmore_{0}_content\n", - file1, file2 + "==> {file1} <==\n{file1}_content\n\n==> {file2} <==\n{file2}_content\n{file1}_content\n\ + more_{file2}_content\n\n==> {file1} <==\nmore_{file1}_content\n" ); let mut expected_stderr = format!( "{0}: {1}: No such file or directory\n\ @@ -2438,9 +2435,8 @@ fn test_follow_name_move_retry2() { let file2 = "b"; let expected_stdout = format!( - "==> {0} <==\n\n==> {1} <==\n\n==> {0} <==\nx\n\n==> {1} <==\ - \nx\n\n==> {0} <==\nx2\n\n==> {1} <==\ny\n\n==> {0} <==\nz\n", - file1, file2 + "==> {file1} <==\n\n==> {file2} <==\n\n==> {file1} <==\nx\n\n==> {file2} <==\ + \nx\n\n==> {file1} <==\nx2\n\n==> {file2} <==\ny\n\n==> {file1} <==\nz\n" ); let mut expected_stderr = format!( "{0}: '{1}' has become inaccessible: No such file or directory\n\ @@ -3851,8 +3847,7 @@ fn test_args_when_settings_check_warnings_then_shows_warnings() { let expected_stdout = format!( "tail: warning: --retry ignored; --retry is useful only when following\n\ - {}", - file_data + {file_data}" ); scene .ucmd() @@ -3864,8 +3859,7 @@ fn test_args_when_settings_check_warnings_then_shows_warnings() { let expected_stdout = format!( "tail: warning: --retry only effective for the initial open\n\ - {}", - file_data + {file_data}" ); let mut child = scene .ucmd() @@ -3882,8 +3876,7 @@ fn test_args_when_settings_check_warnings_then_shows_warnings() { let expected_stdout = format!( "tail: warning: PID ignored; --pid=PID is useful only when following\n\ - {}", - file_data + {file_data}" ); scene .ucmd() @@ -3896,8 +3889,7 @@ fn test_args_when_settings_check_warnings_then_shows_warnings() { let expected_stdout = format!( "tail: warning: --retry ignored; --retry is useful only when following\n\ tail: warning: PID ignored; --pid=PID is useful only when following\n\ - {}", - file_data + {file_data}" ); scene .ucmd() @@ -3963,9 +3955,8 @@ fn test_args_when_settings_check_warnings_follow_indefinitely_then_warning() { let expected_stdout = format!( "tail: warning: following standard input indefinitely is ineffective\n\ ==> data <==\n\ - {}\n\ - ==> standard input <==\n", - file_data + {file_data}\n\ + ==> standard input <==\n" ); // tail -f data - < /dev/ptmx let mut child = scene @@ -4055,10 +4046,9 @@ fn test_args_when_settings_check_warnings_follow_indefinitely_then_no_warning() let pipe_data = "pipe data"; let expected_stdout = format!( "==> standard input <==\n\ - {}\n\ - ==> {} <==\n\ - {}", - pipe_data, file_name, file_data + {pipe_data}\n\ + ==> {file_name} <==\n\ + {file_data}" ); let mut child = scene .ucmd() @@ -4087,10 +4077,9 @@ fn test_args_when_settings_check_warnings_follow_indefinitely_then_no_warning() { let expected_stdout = format!( "==> standard input <==\n\ - {}\n\ - ==> {} <==\n\ - {}", - fifo_data, file_name, file_data + {fifo_data}\n\ + ==> {file_name} <==\n\ + {file_data}" ); let mut child = scene .ucmd() @@ -4108,10 +4097,9 @@ fn test_args_when_settings_check_warnings_follow_indefinitely_then_no_warning() let expected_stdout = format!( "==> standard input <==\n\ - {}\n\ - ==> {} <==\n\ - {}", - fifo_data, file_name, file_data + {fifo_data}\n\ + ==> {file_name} <==\n\ + {file_data}" ); let mut child = scene .ucmd() diff --git a/tests/by-util/test_tee.rs b/tests/by-util/test_tee.rs index e90c4dd48..5dc5a2871 100644 --- a/tests/by-util/test_tee.rs +++ b/tests/by-util/test_tee.rs @@ -70,7 +70,7 @@ fn test_tee_append() { fn test_tee_no_more_writeable_1() { // equals to 'tee /dev/full out2 (); + let content = (1..=10).map(|x| format!("{x}\n")).collect::(); let file_out = "tee_file_out"; ucmd.arg("/dev/full") @@ -90,7 +90,7 @@ fn test_tee_no_more_writeable_2() { // but currently there is no way to redirect stdout to /dev/full // so this test is disabled let (_at, mut ucmd) = at_and_ucmd!(); - let _content = (1..=10).map(|x| format!("{}\n", x)).collect::(); + let _content = (1..=10).map(|x| format!("{x}\n")).collect::(); let file_out_a = "tee_file_out_a"; let file_out_b = "tee_file_out_b"; @@ -130,7 +130,7 @@ mod linux_only { } fn run_tee(proc: &mut UCommand) -> (String, Output) { - let content = (1..=100000).map(|x| format!("{}\n", x)).collect::(); + let content = (1..=100000).map(|x| format!("{x}\n")).collect::(); #[allow(deprecated)] let output = proc @@ -204,9 +204,7 @@ mod linux_only { contents.len() ); assert!(contents.starts_with(&compare), - "Expected truncated output to be a prefix of the correct output, but it isn't.\n Correct: {}\n Compare: {}", - contents, - compare); + "Expected truncated output to be a prefix of the correct output, but it isn't.\n Correct: {contents}\n Compare: {compare}"); } #[test] diff --git a/tests/by-util/test_touch.rs b/tests/by-util/test_touch.rs index af00050e2..7ae8a3905 100644 --- a/tests/by-util/test_touch.rs +++ b/tests/by-util/test_touch.rs @@ -52,7 +52,7 @@ fn str_to_filetime(format: &str, s: &str) -> FileTime { let d = match time::OffsetDateTime::now_local() { Ok(now) => now, Err(e) => { - panic!("Error {} retrieving the OffsetDateTime::now_local", e); + panic!("Error {e} retrieving the OffsetDateTime::now_local"); } }; let offset_dt = tm.assume_offset(d.offset()); @@ -654,7 +654,7 @@ fn get_dst_switch_hour() -> Option { let now = match time::OffsetDateTime::now_local() { Ok(now) => now, Err(e) => { - panic!("Error {} retrieving the OffsetDateTime::now_local", e); + panic!("Error {e} retrieving the OffsetDateTime::now_local"); } }; @@ -712,8 +712,7 @@ fn test_touch_no_such_file_error_msg() { let path_str = path.to_str().unwrap(); new_ucmd!().arg(&path).fails().stderr_only(format!( - "touch: cannot touch '{}': No such file or directory\n", - path_str + "touch: cannot touch '{path_str}': No such file or directory\n" )); } diff --git a/tests/by-util/test_truncate.rs b/tests/by-util/test_truncate.rs index be7ee4145..f306a32a9 100644 --- a/tests/by-util/test_truncate.rs +++ b/tests/by-util/test_truncate.rs @@ -19,13 +19,8 @@ fn test_increase_file_size() { ucmd.args(&["-s", "+5K", FILE1]).succeeds(); file.seek(SeekFrom::End(0)).unwrap(); - let actual = file.seek(SeekFrom::Current(0)).unwrap(); - assert!( - expected == actual, - "expected '{}' got '{}'", - expected, - actual - ); + let actual = file.stream_position().unwrap(); + assert!(expected == actual, "expected '{expected}' got '{actual}'"); } #[test] @@ -36,13 +31,8 @@ fn test_increase_file_size_kb() { ucmd.args(&["-s", "+5KB", FILE1]).succeeds(); file.seek(SeekFrom::End(0)).unwrap(); - let actual = file.seek(SeekFrom::Current(0)).unwrap(); - assert!( - expected == actual, - "expected '{}' got '{}'", - expected, - actual - ); + let actual = file.stream_position().unwrap(); + assert!(expected == actual, "expected '{expected}' got '{actual}'"); } #[test] @@ -66,13 +56,8 @@ fn test_reference() { .succeeds(); file.seek(SeekFrom::End(0)).unwrap(); - let actual = file.seek(SeekFrom::Current(0)).unwrap(); - assert!( - expected == actual, - "expected '{}' got '{}'", - expected, - actual - ); + let actual = file.stream_position().unwrap(); + assert!(expected == actual, "expected '{expected}' got '{actual}'"); } #[test] @@ -83,13 +68,8 @@ fn test_decrease_file_size() { file.write_all(b"1234567890").unwrap(); ucmd.args(&["--size=-4", FILE2]).succeeds(); file.seek(SeekFrom::End(0)).unwrap(); - let actual = file.seek(SeekFrom::Current(0)).unwrap(); - assert!( - expected == actual, - "expected '{}' got '{}'", - expected, - actual - ); + let actual = file.stream_position().unwrap(); + assert!(expected == actual, "expected '{expected}' got '{actual}'"); } #[test] @@ -100,13 +80,8 @@ fn test_space_in_size() { file.write_all(b"1234567890").unwrap(); ucmd.args(&["--size", " 4", FILE2]).succeeds(); file.seek(SeekFrom::End(0)).unwrap(); - let actual = file.seek(SeekFrom::Current(0)).unwrap(); - assert!( - expected == actual, - "expected '{}' got '{}'", - expected, - actual - ); + let actual = file.stream_position().unwrap(); + assert!(expected == actual, "expected '{expected}' got '{actual}'"); } #[test] @@ -134,13 +109,8 @@ fn test_at_most_shrinks() { file.write_all(b"1234567890").unwrap(); ucmd.args(&["--size", "<4", FILE2]).succeeds(); file.seek(SeekFrom::End(0)).unwrap(); - let actual = file.seek(SeekFrom::Current(0)).unwrap(); - assert!( - expected == actual, - "expected '{}' got '{}'", - expected, - actual - ); + let actual = file.stream_position().unwrap(); + assert!(expected == actual, "expected '{expected}' got '{actual}'"); } #[test] @@ -151,13 +121,8 @@ fn test_at_most_no_change() { file.write_all(b"1234567890").unwrap(); ucmd.args(&["--size", "<40", FILE2]).succeeds(); file.seek(SeekFrom::End(0)).unwrap(); - let actual = file.seek(SeekFrom::Current(0)).unwrap(); - assert!( - expected == actual, - "expected '{}' got '{}'", - expected, - actual - ); + let actual = file.stream_position().unwrap(); + assert!(expected == actual, "expected '{expected}' got '{actual}'"); } #[test] @@ -168,13 +133,8 @@ fn test_at_least_grows() { file.write_all(b"1234567890").unwrap(); ucmd.args(&["--size", ">15", FILE2]).succeeds(); file.seek(SeekFrom::End(0)).unwrap(); - let actual = file.seek(SeekFrom::Current(0)).unwrap(); - assert!( - expected == actual, - "expected '{}' got '{}'", - expected, - actual - ); + let actual = file.stream_position().unwrap(); + assert!(expected == actual, "expected '{expected}' got '{actual}'"); } #[test] @@ -185,13 +145,8 @@ fn test_at_least_no_change() { file.write_all(b"1234567890").unwrap(); ucmd.args(&["--size", ">4", FILE2]).succeeds(); file.seek(SeekFrom::End(0)).unwrap(); - let actual = file.seek(SeekFrom::Current(0)).unwrap(); - assert!( - expected == actual, - "expected '{}' got '{}'", - expected, - actual - ); + let actual = file.stream_position().unwrap(); + assert!(expected == actual, "expected '{expected}' got '{actual}'"); } #[test] @@ -202,13 +157,8 @@ fn test_round_down() { file.write_all(b"1234567890").unwrap(); ucmd.args(&["--size", "/4", FILE2]).succeeds(); file.seek(SeekFrom::End(0)).unwrap(); - let actual = file.seek(SeekFrom::Current(0)).unwrap(); - assert!( - expected == actual, - "expected '{}' got '{}'", - expected, - actual - ); + let actual = file.stream_position().unwrap(); + assert!(expected == actual, "expected '{expected}' got '{actual}'"); } #[test] @@ -219,13 +169,8 @@ fn test_round_up() { file.write_all(b"1234567890").unwrap(); ucmd.args(&["--size", "%4", FILE2]).succeeds(); file.seek(SeekFrom::End(0)).unwrap(); - let actual = file.seek(SeekFrom::Current(0)).unwrap(); - assert!( - expected == actual, - "expected '{}' got '{}'", - expected, - actual - ); + let actual = file.stream_position().unwrap(); + assert!(expected == actual, "expected '{expected}' got '{actual}'"); } #[test] @@ -238,13 +183,8 @@ fn test_size_and_reference() { ucmd.args(&["--reference", FILE1, "--size", "+5", FILE2]) .succeeds(); file2.seek(SeekFrom::End(0)).unwrap(); - let actual = file2.seek(SeekFrom::Current(0)).unwrap(); - assert!( - expected == actual, - "expected '{}' got '{}'", - expected, - actual - ); + let actual = file2.stream_position().unwrap(); + assert!(expected == actual, "expected '{expected}' got '{actual}'"); } #[test] diff --git a/tests/by-util/test_wc.rs b/tests/by-util/test_wc.rs index db0df44a0..bbc057972 100644 --- a/tests/by-util/test_wc.rs +++ b/tests/by-util/test_wc.rs @@ -26,7 +26,7 @@ fn test_count_bytes_large_stdin() { 128 * 1024, ] { let data = vec_of_size(n); - let expected = format!("{}\n", n); + let expected = format!("{n}\n"); new_ucmd!() .args(&["-c"]) .pipe_in(data) diff --git a/tests/by-util/test_who.rs b/tests/by-util/test_who.rs index 6acba2099..6f98c8b9d 100644 --- a/tests/by-util/test_who.rs +++ b/tests/by-util/test_who.rs @@ -44,8 +44,8 @@ fn test_heading() { // specifically number of TABs between "TIME" and "COMMENT" may be variant let actual = ts.ucmd().arg(opt).succeeds().stdout_move_str(); let expect = unwrap_or_return!(expected_result(&ts, &[opt])).stdout_move_str(); - println!("actual: {:?}", actual); - println!("expect: {:?}", expect); + println!("actual: {actual:?}"); + println!("expect: {expect:?}"); let v_actual: Vec<&str> = actual.split_whitespace().collect(); let v_expect: Vec<&str> = expect.split_whitespace().collect(); assert_eq!(v_actual, v_expect); @@ -165,8 +165,8 @@ fn test_users() { for opt in ["-u", "--users", "--us"] { let actual = ts.ucmd().arg(opt).succeeds().stdout_move_str(); let expect = unwrap_or_return!(expected_result(&ts, &[opt])).stdout_move_str(); - println!("actual: {:?}", actual); - println!("expect: {:?}", expect); + println!("actual: {actual:?}"); + println!("expect: {expect:?}"); let mut v_actual: Vec<&str> = actual.split_whitespace().collect(); let mut v_expect: Vec<&str> = expect.split_whitespace().collect(); diff --git a/tests/by-util/test_whoami.rs b/tests/by-util/test_whoami.rs index a64dbb7cd..044f27c57 100644 --- a/tests/by-util/test_whoami.rs +++ b/tests/by-util/test_whoami.rs @@ -43,7 +43,7 @@ fn test_normal_compare_env() { if whoami == "nobody" { println!("test skipped:"); } else if !is_ci() { - new_ucmd!().succeeds().stdout_is(format!("{}\n", whoami)); + new_ucmd!().succeeds().stdout_is(format!("{whoami}\n")); } else { println!("test skipped:"); } diff --git a/tests/common/util.rs b/tests/common/util.rs index 7978ed87d..7229deb5a 100644 --- a/tests/common/util.rs +++ b/tests/common/util.rs @@ -293,7 +293,7 @@ impl CmdResult { pub fn signal_name_is(&self, name: &str) -> &Self { use uucore::signals::signal_by_name_or_value; let expected: i32 = signal_by_name_or_value(name) - .unwrap_or_else(|| panic!("Invalid signal name or value: '{}'", name)) + .unwrap_or_else(|| panic!("Invalid signal name or value: '{name}'")) .try_into() .unwrap(); @@ -2223,7 +2223,7 @@ pub fn host_name_for(util_name: &str) -> Cow { if util_name.starts_with('g') && util_name != "groups" { util_name.into() } else { - format!("g{}", util_name).into() + format!("g{util_name}").into() } } #[cfg(target_os = "linux")] @@ -3146,10 +3146,7 @@ mod tests { Err(error) if error.kind() == io::ErrorKind::Other => { std::assert_eq!(error.to_string(), "wait: Timeout of '1s' 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 `wait`."), } } @@ -3178,10 +3175,7 @@ mod tests { Err(error) if error.kind() == io::ErrorKind::Other => { 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`."), } }