From c1eab154c9139a281d17c5ae70151bac4fcbf60f Mon Sep 17 00:00:00 2001 From: Peter Hall Date: Wed, 7 Oct 2020 12:55:01 +0100 Subject: Use a custom env var for log settings intead of default RUST_LOG # Conflicts: # src/rustfmt/main.rs --- src/format-diff/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/format-diff/main.rs') diff --git a/src/format-diff/main.rs b/src/format-diff/main.rs index c751932273b..655aeda42bf 100644 --- a/src/format-diff/main.rs +++ b/src/format-diff/main.rs @@ -64,7 +64,7 @@ pub struct Opts { } fn main() { - env_logger::init(); + env_logger::Builder::from_env("RUSTFMT_LOG").init(); let opts = Opts::from_args(); if let Err(e) = run(opts) { println!("{}", e); -- cgit 1.4.1-3-g733a5 From 91995b6142faf1a5e56e1b7b1cb922504726197c Mon Sep 17 00:00:00 2001 From: Expyron <5100376+Expyron@users.noreply.github.com> Date: Thu, 7 Apr 2022 09:57:58 +0200 Subject: Replace `structopt` dependency by `clap` --- Cargo.lock | 127 +++++++++++++++++++++++----------------------- Cargo.toml | 2 +- src/cargo-fmt/main.rs | 33 +++++++----- src/cargo-fmt/test/mod.rs | 42 ++++++++------- src/format-diff/main.rs | 45 ++++++++-------- 5 files changed, 130 insertions(+), 119 deletions(-) (limited to 'src/format-diff/main.rs') diff --git a/Cargo.lock b/Cargo.lock index 1b444136585..4eaaee74cf9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -21,15 +21,6 @@ dependencies = [ "yansi-term", ] -[[package]] -name = "ansi_term" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2" -dependencies = [ - "winapi", -] - [[package]] name = "anyhow" version = "1.0.56" @@ -47,6 +38,12 @@ dependencies = [ "winapi", ] +[[package]] +name = "autocfg" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" + [[package]] name = "bitflags" version = "1.3.2" @@ -110,17 +107,32 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "clap" -version = "2.34.0" +version = "3.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c" +checksum = "71c47df61d9e16dc010b55dba1952a57d8c215dbb533fd13cdd13369aac73b1c" dependencies = [ - "ansi_term", "atty", "bitflags", + "clap_derive", + "indexmap", + "lazy_static", + "os_str_bytes", "strsim", + "termcolor", "textwrap", - "unicode-width", - "vec_map", +] + +[[package]] +name = "clap_derive" +version = "3.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3aab4734e083b809aaf5794e14e756d1c798d2c69c7f7de7a09a2f5214993c1" +dependencies = [ + "heck", + "proc-macro-error", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -249,14 +261,17 @@ dependencies = [ "regex", ] +[[package]] +name = "hashbrown" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" + [[package]] name = "heck" -version = "0.3.3" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c" -dependencies = [ - "unicode-segmentation", -] +checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9" [[package]] name = "hermit-abi" @@ -291,6 +306,16 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "indexmap" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f647032dfaa1f8b6dc29bd3edb7bbef4861b8b8007ebb118d6db284fd59f6ee" +dependencies = [ + "autocfg", + "hashbrown", +] + [[package]] name = "itertools" version = "0.10.3" @@ -314,9 +339,9 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" [[package]] name = "libc" -version = "0.2.121" +version = "0.2.122" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "efaa7b300f3b5fe8eb6bf21ce3895e1751d9665086af2d64b42f19701015ff4f" +checksum = "ec647867e2bf0772e28c8bcde4f0d19a9216916e890543b5a03ed8ef27b8f259" [[package]] name = "libm" @@ -345,6 +370,15 @@ version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "87f3e037eac156d1775da914196f0f37741a274155e34a0b7e427c35d2a2ecb9" +[[package]] +name = "os_str_bytes" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e22443d1643a904602595ba1cd8f7d896afe56d26712531c5ff73a15b2fbf64" +dependencies = [ + "memchr", +] + [[package]] name = "packed_simd_2" version = "0.3.7" @@ -381,9 +415,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.36" +version = "1.0.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7342d5883fbccae1cc37a2353b09c87c9b0f3afd73f5fb9bba687a1f733b029" +checksum = "ec757218438d5fda206afc041538b2f6d889286160d649a86a24d37e1235afd1" dependencies = [ "unicode-xid", ] @@ -457,6 +491,7 @@ dependencies = [ "anyhow", "bytecount", "cargo_metadata", + "clap", "derive-new", "diff", "dirs", @@ -471,7 +506,6 @@ dependencies = [ "rustfmt-config_proc_macro", "serde", "serde_json", - "structopt", "term", "thiserror", "toml", @@ -543,39 +577,15 @@ dependencies = [ [[package]] name = "strsim" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" - -[[package]] -name = "structopt" -version = "0.3.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c6b5c64445ba8094a6ab0c3cd2ad323e07171012d9c98b0b15651daf1787a10" -dependencies = [ - "clap", - "lazy_static", - "structopt-derive", -] - -[[package]] -name = "structopt-derive" -version = "0.4.18" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcb5ae327f9cc13b68763b5749770cb9e048a99bd9dfdfa58d0cf05d5f64afe0" -dependencies = [ - "heck", - "proc-macro-error", - "proc-macro2", - "quote", - "syn", -] +checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" [[package]] name = "syn" -version = "1.0.90" +version = "1.0.91" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "704df27628939572cd88d33f171cd6f896f4eaca85252c6e0a72d8d8287ee86f" +checksum = "b683b2b825c8eef438b77c36a06dc262294da3d5a5813fac20da149241dcd44d" dependencies = [ "proc-macro2", "quote", @@ -604,12 +614,9 @@ dependencies = [ [[package]] name = "textwrap" -version = "0.11.0" +version = "0.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" -dependencies = [ - "unicode-width", -] +checksum = "b1141d4d61095b28419e22cb0bbf02755f5e54e0526f97f1e3d1d160e60885fb" [[package]] name = "thiserror" @@ -673,12 +680,6 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e" -[[package]] -name = "vec_map" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" - [[package]] name = "version_check" version = "0.9.4" diff --git a/Cargo.toml b/Cargo.toml index 4325f46db9f..0be9723bc4d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,6 +37,7 @@ annotate-snippets = { version = "0.9", features = ["color"] } anyhow = "1.0" bytecount = "0.6" cargo_metadata = "0.14" +clap = { version = "3.1", features = ["derive"] } derive-new = "0.5" diff = "0.1" dirs = "4.0" @@ -49,7 +50,6 @@ log = "0.4" regex = "1.5" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" -structopt = "0.3" term = "0.7" thiserror = "1.0" toml = "0.5" diff --git a/src/cargo-fmt/main.rs b/src/cargo-fmt/main.rs index 8cb7b4585ec..3542536f29b 100644 --- a/src/cargo-fmt/main.rs +++ b/src/cargo-fmt/main.rs @@ -15,54 +15,59 @@ use std::path::{Path, PathBuf}; use std::process::Command; use std::str; -use structopt::StructOpt; +use clap::{CommandFactory, Parser}; #[path = "test/mod.rs"] #[cfg(test)] mod cargo_fmt_tests; -#[derive(StructOpt, Debug)] -#[structopt( +#[derive(Parser)] +#[clap( bin_name = "cargo fmt", about = "This utility formats all bin and lib files of \ the current crate using rustfmt." )] pub struct Opts { /// No output printed to stdout - #[structopt(short = "q", long = "quiet")] + #[clap(short = 'q', long = "quiet")] quiet: bool, /// Use verbose output - #[structopt(short = "v", long = "verbose")] + #[clap(short = 'v', long = "verbose")] verbose: bool, /// Print rustfmt version and exit - #[structopt(long = "version")] + #[clap(long = "version")] version: bool, /// Specify package to format - #[structopt(short = "p", long = "package", value_name = "package")] + #[clap( + short = 'p', + long = "package", + value_name = "package", + multiple_values = true + )] packages: Vec, /// Specify path to Cargo.toml - #[structopt(long = "manifest-path", value_name = "manifest-path")] + #[clap(long = "manifest-path", value_name = "manifest-path")] manifest_path: Option, /// Specify message-format: short|json|human - #[structopt(long = "message-format", value_name = "message-format")] + #[clap(long = "message-format", value_name = "message-format")] message_format: Option, /// Options passed to rustfmt // 'raw = true' to make `--` explicit. - #[structopt(name = "rustfmt_options", raw(true))] + #[clap(name = "rustfmt_options", raw(true))] rustfmt_options: Vec, /// Format all packages, and also their local path-based dependencies - #[structopt(long = "all")] + #[clap(long = "all")] format_all: bool, /// Run rustfmt in check mode - #[structopt(long = "check")] + #[clap(long = "check")] check: bool, } @@ -87,7 +92,7 @@ fn execute() -> i32 { } }); - let opts = Opts::from_iter(args); + let opts = Opts::parse_from(args); let verbosity = match (opts.verbose, opts.quiet) { (false, false) => Verbosity::Normal, @@ -204,7 +209,7 @@ fn convert_message_format_to_rustfmt_args( fn print_usage_to_stderr(reason: &str) { eprintln!("{}", reason); - let app = Opts::clap(); + let app = Opts::command(); app.after_help("") .write_help(&mut io::stderr()) .expect("failed to write to stderr"); diff --git a/src/cargo-fmt/test/mod.rs b/src/cargo-fmt/test/mod.rs index 360503632c7..56e52fbabb6 100644 --- a/src/cargo-fmt/test/mod.rs +++ b/src/cargo-fmt/test/mod.rs @@ -6,7 +6,7 @@ mod targets; #[test] fn default_options() { let empty: Vec = vec![]; - let o = Opts::from_iter(&empty); + let o = Opts::parse_from(&empty); assert_eq!(false, o.quiet); assert_eq!(false, o.verbose); assert_eq!(false, o.version); @@ -20,7 +20,7 @@ fn default_options() { #[test] fn good_options() { - let o = Opts::from_iter(&[ + let o = Opts::parse_from(&[ "test", "-q", "-p", @@ -47,8 +47,8 @@ fn good_options() { #[test] fn unexpected_option() { assert!( - Opts::clap() - .get_matches_from_safe(&["test", "unexpected"]) + Opts::command() + .try_get_matches_from(&["test", "unexpected"]) .is_err() ); } @@ -56,8 +56,8 @@ fn unexpected_option() { #[test] fn unexpected_flag() { assert!( - Opts::clap() - .get_matches_from_safe(&["test", "--flag"]) + Opts::command() + .try_get_matches_from(&["test", "--flag"]) .is_err() ); } @@ -65,20 +65,20 @@ fn unexpected_flag() { #[test] fn mandatory_separator() { assert!( - Opts::clap() - .get_matches_from_safe(&["test", "--emit"]) + Opts::command() + .try_get_matches_from(&["test", "--emit"]) .is_err() ); assert!( - !Opts::clap() - .get_matches_from_safe(&["test", "--", "--emit"]) + !Opts::command() + .try_get_matches_from(&["test", "--", "--emit"]) .is_err() ); } #[test] fn multiple_packages_one_by_one() { - let o = Opts::from_iter(&[ + let o = Opts::parse_from(&[ "test", "-p", "package1", @@ -92,7 +92,7 @@ fn multiple_packages_one_by_one() { #[test] fn multiple_packages_grouped() { - let o = Opts::from_iter(&[ + let o = Opts::parse_from(&[ "test", "--package", "package1", @@ -106,14 +106,18 @@ fn multiple_packages_grouped() { #[test] fn empty_packages_1() { - assert!(Opts::clap().get_matches_from_safe(&["test", "-p"]).is_err()); + assert!( + Opts::command() + .try_get_matches_from(&["test", "-p"]) + .is_err() + ); } #[test] fn empty_packages_2() { assert!( - Opts::clap() - .get_matches_from_safe(&["test", "-p", "--", "--check"]) + Opts::command() + .try_get_matches_from(&["test", "-p", "--", "--check"]) .is_err() ); } @@ -121,8 +125,8 @@ fn empty_packages_2() { #[test] fn empty_packages_3() { assert!( - Opts::clap() - .get_matches_from_safe(&["test", "-p", "--verbose"]) + Opts::command() + .try_get_matches_from(&["test", "-p", "--verbose"]) .is_err() ); } @@ -130,8 +134,8 @@ fn empty_packages_3() { #[test] fn empty_packages_4() { assert!( - Opts::clap() - .get_matches_from_safe(&["test", "-p", "--check"]) + Opts::command() + .try_get_matches_from(&["test", "-p", "--check"]) .is_err() ); } diff --git a/src/format-diff/main.rs b/src/format-diff/main.rs index 655aeda42bf..f6b739e1c2a 100644 --- a/src/format-diff/main.rs +++ b/src/format-diff/main.rs @@ -19,8 +19,7 @@ use std::process; use regex::Regex; -use structopt::clap::AppSettings; -use structopt::StructOpt; +use clap::{CommandFactory, Parser}; /// The default pattern of files to format. /// @@ -37,16 +36,16 @@ enum FormatDiffError { IoError(#[from] io::Error), } -#[derive(StructOpt, Debug)] -#[structopt( +#[derive(Parser, Debug)] +#[clap( name = "rustfmt-format-diff", - setting = AppSettings::DisableVersion, - setting = AppSettings::NextLineHelp + disable_version_flag = true, + next_line_help = true )] pub struct Opts { /// Skip the smallest prefix containing NUMBER slashes - #[structopt( - short = "p", + #[clap( + short = 'p', long = "skip-prefix", value_name = "NUMBER", default_value = "0" @@ -54,8 +53,8 @@ pub struct Opts { skip_prefix: u32, /// Custom pattern selecting file paths to reformat - #[structopt( - short = "f", + #[clap( + short = 'f', long = "filter", value_name = "PATTERN", default_value = DEFAULT_PATTERN @@ -65,10 +64,12 @@ pub struct Opts { fn main() { env_logger::Builder::from_env("RUSTFMT_LOG").init(); - let opts = Opts::from_args(); + let opts = Opts::parse(); if let Err(e) = run(opts) { println!("{}", e); - Opts::clap().print_help().expect("cannot write to stdout"); + Opts::command() + .print_help() + .expect("cannot write to stdout"); process::exit(1); } } @@ -230,14 +231,14 @@ mod cmd_line_tests { #[test] fn default_options() { let empty: Vec = vec![]; - let o = Opts::from_iter(&empty); + let o = Opts::parse_from(&empty); assert_eq!(DEFAULT_PATTERN, o.filter); assert_eq!(0, o.skip_prefix); } #[test] fn good_options() { - let o = Opts::from_iter(&["test", "-p", "10", "-f", r".*\.hs"]); + let o = Opts::parse_from(&["test", "-p", "10", "-f", r".*\.hs"]); assert_eq!(r".*\.hs", o.filter); assert_eq!(10, o.skip_prefix); } @@ -245,8 +246,8 @@ mod cmd_line_tests { #[test] fn unexpected_option() { assert!( - Opts::clap() - .get_matches_from_safe(&["test", "unexpected"]) + Opts::command() + .try_get_matches_from(&["test", "unexpected"]) .is_err() ); } @@ -254,8 +255,8 @@ mod cmd_line_tests { #[test] fn unexpected_flag() { assert!( - Opts::clap() - .get_matches_from_safe(&["test", "--flag"]) + Opts::command() + .try_get_matches_from(&["test", "--flag"]) .is_err() ); } @@ -263,8 +264,8 @@ mod cmd_line_tests { #[test] fn overridden_option() { assert!( - Opts::clap() - .get_matches_from_safe(&["test", "-p", "10", "-p", "20"]) + Opts::command() + .try_get_matches_from(&["test", "-p", "10", "-p", "20"]) .is_err() ); } @@ -272,8 +273,8 @@ mod cmd_line_tests { #[test] fn negative_filter() { assert!( - Opts::clap() - .get_matches_from_safe(&["test", "-p", "-1"]) + Opts::command() + .try_get_matches_from(&["test", "-p", "-1"]) .is_err() ); } -- cgit 1.4.1-3-g733a5 From 326af2bd2146e6502ea87b63f72a9de45ff38f85 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Sun, 25 Jun 2023 16:01:29 +0000 Subject: Switch to tracing for logging --- Cargo.lock | 163 ++++++++++++++++++++++++++++++++++++++---------- Cargo.toml | 6 +- src/bin/main.rs | 5 +- src/format-diff/main.rs | 7 ++- src/git-rustfmt/main.rs | 7 ++- src/test/mod.rs | 2 +- 6 files changed, 147 insertions(+), 43 deletions(-) (limited to 'src/format-diff/main.rs') diff --git a/Cargo.lock b/Cargo.lock index bd28df7a757..e867f2cb840 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -261,19 +261,6 @@ version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" -[[package]] -name = "env_logger" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85cdab6a89accf66733ad5a1693a4dcced6aeff64602b634530dd73c1f3ee9f0" -dependencies = [ - "humantime", - "is-terminal", - "log", - "regex", - "termcolor", -] - [[package]] name = "errno" version = "0.3.1" @@ -352,12 +339,6 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fed44880c466736ef9a5c5b5facefb5ed0785676d0c02d612db14e54f0d84286" -[[package]] -name = "humantime" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" - [[package]] name = "ignore" version = "0.4.18" @@ -457,18 +438,43 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "matchers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8263075bb86c5a1b1427b5ae862e8889656f126e9f77c484496e8b47cf5c5558" +dependencies = [ + "regex-automata", +] + [[package]] name = "memchr" version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a" +[[package]] +name = "nu-ansi-term" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84" +dependencies = [ + "overload", + "winapi", +] + [[package]] name = "once_cell" version = "1.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3" +[[package]] +name = "overload" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" + [[package]] name = "packed_simd_2" version = "0.3.7" @@ -479,6 +485,12 @@ dependencies = [ "libm", ] +[[package]] +name = "pin-project-lite" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" + [[package]] name = "proc-macro2" version = "1.0.63" @@ -519,20 +531,29 @@ dependencies = [ [[package]] name = "regex" -version = "1.5.5" +version = "1.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a11647b6b25ff05a515cb92c365cec08801e83423a235b51e231e1808747286" +checksum = "8b1f693b24f6ac912f4893ef08244d70b6067480d2f1a46e950c9691e6749d1d" dependencies = [ "aho-corasick", "memchr", "regex-syntax", ] +[[package]] +name = "regex-automata" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" +dependencies = [ + "regex-syntax", +] + [[package]] name = "regex-syntax" -version = "0.6.25" +version = "0.6.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b" +checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" [[package]] name = "rustfmt-config_proc_macro" @@ -554,12 +575,10 @@ dependencies = [ "clap", "diff", "dirs", - "env_logger", "getopts", "ignore", "itertools", "lazy_static", - "log", "regex", "rustfmt-config_proc_macro", "serde", @@ -567,6 +586,8 @@ dependencies = [ "term", "thiserror", "toml", + "tracing", + "tracing-subscriber", "unicode-segmentation", "unicode-width", "unicode_categories", @@ -656,6 +677,21 @@ dependencies = [ "serde", ] +[[package]] +name = "sharded-slab" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900fba806f70c630b0a382d0d825e17a0f19fcd059a2ade1ff237bcddf446b31" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "smallvec" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0" + [[package]] name = "strsim" version = "0.10.0" @@ -684,15 +720,6 @@ dependencies = [ "winapi", ] -[[package]] -name = "termcolor" -version = "1.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" -dependencies = [ - "winapi-util", -] - [[package]] name = "thiserror" version = "1.0.40" @@ -756,6 +783,68 @@ dependencies = [ "winnow", ] +[[package]] +name = "tracing" +version = "0.1.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8" +dependencies = [ + "cfg-if", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f4f31f56159e98206da9efd823404b79b6ef3143b4a7ab76e67b1751b25a4ab" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tracing-core" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0955b8137a1df6f1a2e9a37d8a6656291ff0297c1a97c24e0d8425fe2312f79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78ddad33d2d10b1ed7eb9d1f518a5674713876e97e5bb9b7345a7984fbb4f922" +dependencies = [ + "lazy_static", + "log", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30a651bc37f915e81f087d86e62a18eec5f79550c7faff886f7090b4ea757c77" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + [[package]] name = "unicode-ident" version = "1.0.8" @@ -786,6 +875,12 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" +[[package]] +name = "valuable" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" + [[package]] name = "walkdir" version = "2.3.2" diff --git a/Cargo.toml b/Cargo.toml index 8c312f47a28..f4c4bab37cb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,18 +40,18 @@ cargo_metadata = "0.15.4" clap = { version = "4.2.1", features = ["derive"] } diff = "0.1" dirs = "4.0" -env_logger = "0.10.0" getopts = "0.2" ignore = "0.4" itertools = "0.10" lazy_static = "1.4" -log = "0.4" -regex = "1.5" +regex = "1.7" serde = { version = "1.0.160", features = ["derive"] } serde_json = "1.0" term = "0.7" thiserror = "1.0.40" toml = "0.7.4" +tracing = "0.1.37" +tracing-subscriber = { version = "0.3.17", features = ["env-filter"] } unicode-segmentation = "1.9" unicode-width = "0.1" unicode_categories = "0.1" diff --git a/src/bin/main.rs b/src/bin/main.rs index 03b75c1b041..2ff67d27e1b 100644 --- a/src/bin/main.rs +++ b/src/bin/main.rs @@ -6,6 +6,7 @@ use io::Error as IoError; use thiserror::Error; use rustfmt_nightly as rustfmt; +use tracing_subscriber::EnvFilter; use std::collections::HashMap; use std::env; @@ -29,7 +30,9 @@ extern crate rustc_driver; fn main() { rustc_driver::install_ice_hook(BUG_REPORT_URL, |_| ()); - env_logger::Builder::from_env("RUSTFMT_LOG").init(); + tracing_subscriber::fmt() + .with_env_filter(EnvFilter::from_env("RUSTFMT_LOG")) + .init(); let opts = make_opts(); let exit_code = match execute(&opts) { diff --git a/src/format-diff/main.rs b/src/format-diff/main.rs index f6b739e1c2a..db4a21ba09e 100644 --- a/src/format-diff/main.rs +++ b/src/format-diff/main.rs @@ -5,11 +5,12 @@ #![deny(warnings)] #[macro_use] -extern crate log; +extern crate tracing; use serde::{Deserialize, Serialize}; use serde_json as json; use thiserror::Error; +use tracing_subscriber::EnvFilter; use std::collections::HashSet; use std::env; @@ -63,7 +64,9 @@ pub struct Opts { } fn main() { - env_logger::Builder::from_env("RUSTFMT_LOG").init(); + tracing_subscriber::fmt() + .with_env_filter(EnvFilter::from_env("RUSTFMT_LOG")) + .init(); let opts = Opts::parse(); if let Err(e) = run(opts) { println!("{}", e); diff --git a/src/git-rustfmt/main.rs b/src/git-rustfmt/main.rs index 579778edbe7..efeda53e7ec 100644 --- a/src/git-rustfmt/main.rs +++ b/src/git-rustfmt/main.rs @@ -1,5 +1,5 @@ #[macro_use] -extern crate log; +extern crate tracing; use std::env; use std::io::stdout; @@ -9,6 +9,7 @@ use std::str::FromStr; use getopts::{Matches, Options}; use rustfmt_nightly as rustfmt; +use tracing_subscriber::EnvFilter; use crate::rustfmt::{load_config, CliOptions, FormatReportFormatterBuilder, Input, Session}; @@ -170,7 +171,9 @@ impl Config { } fn main() { - env_logger::Builder::from_env("RUSTFMT_LOG").init(); + tracing_subscriber::fmt() + .with_env_filter(EnvFilter::from_env("RUSTFMT_LOG")) + .init(); let opts = make_opts(); let matches = opts diff --git a/src/test/mod.rs b/src/test/mod.rs index cfad4a8ed0e..f88ab3f194b 100644 --- a/src/test/mod.rs +++ b/src/test/mod.rs @@ -47,7 +47,7 @@ const FILE_SKIP_LIST: &[&str] = &[ ]; fn init_log() { - let _ = env_logger::builder().is_test(true).try_init(); + let _ = tracing_subscriber::fmt().with_test_writer().try_init(); } struct TestSetting { -- cgit 1.4.1-3-g733a5 From b069aac44ddfdb70d55d9ae40695be44515e5bb0 Mon Sep 17 00:00:00 2001 From: Yuri Astrakhan Date: Sun, 13 Aug 2023 21:14:31 +0200 Subject: Inline format arguments for easier reading (#5881) * Inline format arguments for easier reading Code becomes shorter and often easier to read when format args are inlined. Note that I skipped the mixed cases to make it more straightforward (could be done separatelly). Also, there are two FIXME comments - for some reasons inlining makes format string exceed 100 char line width and crash. ``` cargo clippy --workspace --allow-dirty --fix --benches --tests --bins -- -A clippy::all -W clippy::uninlined_format_args ``` * address feedback --- src/attr.rs | 8 +++--- src/attr/doc_comment.rs | 6 ++--- src/bin/main.rs | 19 ++++++------- src/cargo-fmt/main.rs | 9 +++---- src/chains.rs | 2 +- src/closures.rs | 7 ++--- src/comment.rs | 35 +++++++----------------- src/config/config_type.rs | 10 +++---- src/config/file_lines.rs | 2 +- src/config/macro_names.rs | 2 +- src/config/mod.rs | 15 +++++------ src/config/options.rs | 2 +- src/emitter.rs | 2 +- src/emitter/checkstyle.rs | 4 +-- src/emitter/checkstyle/xml.rs | 2 +- src/emitter/diff.rs | 6 ++--- src/emitter/json.rs | 6 ++--- src/emitter/stdout.rs | 4 +-- src/expr.rs | 57 +++++++++++++++++++-------------------- src/format-diff/main.rs | 8 +++--- src/formatting.rs | 2 +- src/git-rustfmt/main.rs | 4 +-- src/imports.rs | 20 +++++++------- src/items.rs | 40 +++++++++++++-------------- src/macros.rs | 32 +++++++++++----------- src/matches.rs | 6 ++--- src/pairs.rs | 4 +-- src/parse/session.rs | 3 +-- src/patterns.rs | 8 +++--- src/rustfmt_diff.rs | 17 ++++++------ src/skip.rs | 2 +- src/source_file.rs | 2 +- src/test/configuration_snippet.rs | 10 +++---- src/test/mod.rs | 22 +++++++-------- src/types.rs | 16 +++++------ src/utils.rs | 4 +-- tests/cargo-fmt/main.rs | 2 +- tests/rustfmt/main.rs | 6 ++--- 38 files changed, 183 insertions(+), 223 deletions(-) (limited to 'src/format-diff/main.rs') diff --git a/src/attr.rs b/src/attr.rs index 22e45082a9f..4d83547d664 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -308,7 +308,7 @@ impl Rewrite for ast::MetaItem { // See #2479 for example. let value = rewrite_literal(context, lit.as_token_lit(), lit.span, lit_shape) .unwrap_or_else(|| context.snippet(lit.span).to_owned()); - format!("{} = {}", path, value) + format!("{path} = {value}") } }) } @@ -342,7 +342,7 @@ impl Rewrite for ast::Attribute { let literal_str = literal.as_str(); let doc_comment_formatter = DocCommentFormatter::new(literal_str, comment_style); - let doc_comment = format!("{}", doc_comment_formatter); + let doc_comment = format!("{doc_comment_formatter}"); return rewrite_doc_comment( &doc_comment, shape.comment(context.config), @@ -406,9 +406,9 @@ impl Rewrite for [ast::Attribute] { 0, )?; let comment = if comment.is_empty() { - format!("\n{}", mlb) + format!("\n{mlb}") } else { - format!("{}{}\n{}", mla, comment, mlb) + format!("{mla}{comment}\n{mlb}") }; result.push_str(&comment); result.push_str(&shape.indent.to_string(context.config)); diff --git a/src/attr/doc_comment.rs b/src/attr/doc_comment.rs index 25c8158df8c..f55201839b5 100644 --- a/src/attr/doc_comment.rs +++ b/src/attr/doc_comment.rs @@ -20,15 +20,15 @@ impl Display for DocCommentFormatter<'_> { // Handle `#[doc = ""]`. if lines.peek().is_none() { - return write!(formatter, "{}", opener); + return write!(formatter, "{opener}"); } while let Some(line) = lines.next() { let is_last_line = lines.peek().is_none(); if is_last_line { - write!(formatter, "{}{}", opener, line)?; + write!(formatter, "{opener}{line}")?; } else { - writeln!(formatter, "{}{}", opener, line)?; + writeln!(formatter, "{opener}{line}")?; } } Ok(()) diff --git a/src/bin/main.rs b/src/bin/main.rs index 97d31852d63..6f564083656 100644 --- a/src/bin/main.rs +++ b/src/bin/main.rs @@ -38,7 +38,7 @@ fn main() { let exit_code = match execute(&opts) { Ok(code) => code, Err(e) => { - eprintln!("{:#}", e); + eprintln!("{e:#}"); 1 } }; @@ -284,7 +284,7 @@ fn format_string(input: String, options: GetOptsOptions) -> Result { for f in config.file_lines().files() { match *f { FileName::Stdin => {} - _ => eprintln!("Warning: Extra file listed in file_lines option '{}'", f), + _ => eprintln!("Warning: Extra file listed in file_lines option '{f}'"), } } @@ -380,7 +380,7 @@ fn format_and_emit_report(session: &mut Session<'_, T>, input: Input) } } Err(msg) => { - eprintln!("Error writing files: {}", msg); + eprintln!("Error writing files: {msg}"); session.add_operational_error(); } } @@ -403,12 +403,9 @@ fn print_usage_to_stdout(opts: &Options, reason: &str) { let sep = if reason.is_empty() { String::new() } else { - format!("{}\n\n", reason) + format!("{reason}\n\n") }; - let msg = format!( - "{}Format Rust code\n\nusage: rustfmt [options] ...", - sep - ); + let msg = format!("{sep}Format Rust code\n\nusage: rustfmt [options] ..."); println!("{}", opts.usage(&msg)); } @@ -442,7 +439,7 @@ fn print_version() { include_str!(concat!(env!("OUT_DIR"), "/commit-info.txt")) ); - println!("rustfmt {}", version_info); + println!("rustfmt {version_info}"); } fn determine_operation(matches: &Matches) -> Result { @@ -647,9 +644,9 @@ impl GetOptsOptions { match *f { FileName::Real(ref f) if files.contains(f) => {} FileName::Real(_) => { - eprintln!("Warning: Extra file listed in file_lines option '{}'", f) + eprintln!("Warning: Extra file listed in file_lines option '{f}'") } - FileName::Stdin => eprintln!("Warning: Not a file '{}'", f), + FileName::Stdin => eprintln!("Warning: Not a file '{f}'"), } } } diff --git a/src/cargo-fmt/main.rs b/src/cargo-fmt/main.rs index bc9745275f2..3d399c12978 100644 --- a/src/cargo-fmt/main.rs +++ b/src/cargo-fmt/main.rs @@ -200,14 +200,13 @@ fn convert_message_format_to_rustfmt_args( } "human" => Ok(()), _ => Err(format!( - "invalid --message-format value: {}. Allowed values are: short|json|human", - message_format + "invalid --message-format value: {message_format}. Allowed values are: short|json|human" )), } } fn print_usage_to_stderr(reason: &str) { - eprintln!("{}", reason); + eprintln!("{reason}"); let app = Opts::command(); app.after_help("") .write_help(&mut io::stderr()) @@ -460,7 +459,7 @@ fn get_targets_with_hitlist( let package = workspace_hitlist.iter().next().unwrap(); Err(io::Error::new( io::ErrorKind::InvalidInput, - format!("package `{}` is not a member of the workspace", package), + format!("package `{package}` is not a member of the workspace"), )) } } @@ -498,7 +497,7 @@ fn run_rustfmt( if verbosity == Verbosity::Verbose { print!("rustfmt"); - print!(" --edition {}", edition); + print!(" --edition {edition}"); fmt_args.iter().for_each(|f| print!(" {}", f)); files.iter().for_each(|f| print!(" {}", f.display())); println!(); diff --git a/src/chains.rs b/src/chains.rs index d4876389c86..ea23690caed 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -296,7 +296,7 @@ impl Rewrite for ChainItem { rewrite_comment(comment, false, shape, context.config)? } }; - Some(format!("{}{}", rewrite, "?".repeat(self.tries))) + Some(format!("{rewrite}{}", "?".repeat(self.tries))) } } diff --git a/src/closures.rs b/src/closures.rs index cf128752919..a09146e9592 100644 --- a/src/closures.rs +++ b/src/closures.rs @@ -175,7 +175,7 @@ fn rewrite_closure_with_block( shape, false, )?; - Some(format!("{} {}", prefix, block)) + Some(format!("{prefix} {block}")) } // Rewrite closure with a single expression without wrapping its body with block. @@ -310,10 +310,7 @@ fn rewrite_closure_fn_decl( .tactic(tactic) .preserve_newline(true); let list_str = write_list(&item_vec, &fmt)?; - let mut prefix = format!( - "{}{}{}{}{}|{}|", - binder, const_, immovable, is_async, mover, list_str - ); + let mut prefix = format!("{binder}{const_}{immovable}{is_async}{mover}|{list_str}|"); if !ret_str.is_empty() { if prefix.contains('\n') { diff --git a/src/comment.rs b/src/comment.rs index c241e12c56a..a000d110daa 100644 --- a/src/comment.rs +++ b/src/comment.rs @@ -621,7 +621,7 @@ impl<'a> CommentRewrite<'a> { is_prev_line_multi_line: false, code_block_attr: None, item_block: None, - comment_line_separator: format!("{}{}", indent_str, line_start), + comment_line_separator: format!("{indent_str}{line_start}"), max_width, indent_str, fmt_indent: shape.indent, @@ -951,7 +951,7 @@ const RUSTFMT_CUSTOM_COMMENT_PREFIX: &str = "//#### "; fn hide_sharp_behind_comment(s: &str) -> Cow<'_, str> { let s_trimmed = s.trim(); if s_trimmed.starts_with("# ") || s_trimmed == "#" { - Cow::from(format!("{}{}", RUSTFMT_CUSTOM_COMMENT_PREFIX, s)) + Cow::from(format!("{RUSTFMT_CUSTOM_COMMENT_PREFIX}{s}")) } else { Cow::from(s) } @@ -1035,7 +1035,7 @@ pub(crate) fn recover_missing_comment_in_span( } else { Cow::from(" ") }; - Some(format!("{}{}", sep, missing_comment)) + Some(format!("{sep}{missing_comment}")) } } @@ -1832,8 +1832,7 @@ fn remove_comment_header(comment: &str) -> &str { } else { assert!( comment.starts_with("/*"), - "string '{}' is not a comment", - comment + "string '{comment}' is not a comment" ); &comment[2..comment.len() - 2] } @@ -2069,26 +2068,13 @@ fn main() { expected_line_start: &str, ) { let block = ItemizedBlock::new(test_input).unwrap(); - assert_eq!(1, block.lines.len(), "test_input: {:?}", test_input); - assert_eq!( - expected_line, &block.lines[0], - "test_input: {:?}", - test_input - ); - assert_eq!( - expected_indent, block.indent, - "test_input: {:?}", - test_input - ); - assert_eq!( - expected_opener, &block.opener, - "test_input: {:?}", - test_input - ); + assert_eq!(1, block.lines.len(), "test_input: {test_input:?}"); + assert_eq!(expected_line, &block.lines[0], "test_input: {test_input:?}"); + assert_eq!(expected_indent, block.indent, "test_input: {test_input:?}"); + assert_eq!(expected_opener, &block.opener, "test_input: {test_input:?}"); assert_eq!( expected_line_start, &block.line_start, - "test_input: {:?}", - test_input + "test_input: {test_input:?}" ); } @@ -2145,8 +2131,7 @@ fn main() { let maybe_block = ItemizedBlock::new(line); assert!( maybe_block.is_none(), - "The following line shouldn't be classified as a list item: {}", - line + "The following line shouldn't be classified as a list item: {line}" ); } } diff --git a/src/config/config_type.rs b/src/config/config_type.rs index c836b4bbb78..feb452d7235 100644 --- a/src/config/config_type.rs +++ b/src/config/config_type.rs @@ -500,18 +500,16 @@ where // Stable with an unstable option (false, false, _) => { eprintln!( - "Warning: can't set `{} = {:?}`, unstable features are only \ - available in nightly channel.", - option_name, option_value + "Warning: can't set `{option_name} = {option_value:?}`, unstable features are only \ + available in nightly channel." ); false } // Stable with a stable option, but an unstable variant (false, true, false) => { eprintln!( - "Warning: can't set `{} = {:?}`, unstable variants are only \ - available in nightly channel.", - option_name, option_value + "Warning: can't set `{option_name} = {option_value:?}`, unstable variants are only \ + available in nightly channel." ); false } diff --git a/src/config/file_lines.rs b/src/config/file_lines.rs index e4e51a3f3b4..e33fe9bb283 100644 --- a/src/config/file_lines.rs +++ b/src/config/file_lines.rs @@ -162,7 +162,7 @@ impl fmt::Display for FileLines { None => write!(f, "None")?, Some(map) => { for (file_name, ranges) in map.iter() { - write!(f, "{}: ", file_name)?; + write!(f, "{file_name}: ")?; write!(f, "{}\n", ranges.iter().format(", "))?; } } diff --git a/src/config/macro_names.rs b/src/config/macro_names.rs index 61658f0a212..edfe925c2b3 100644 --- a/src/config/macro_names.rs +++ b/src/config/macro_names.rs @@ -123,6 +123,6 @@ mod test { #[test] fn macro_names_display() { let macro_names = MacroSelectors::from_str(r#"["foo", "*", "bar"]"#).unwrap(); - assert_eq!(format!("{}", macro_names), "foo, *, bar"); + assert_eq!(format!("{macro_names}"), "foo, *, bar"); } } diff --git a/src/config/mod.rs b/src/config/mod.rs index 6f41b299e87..7538b26522d 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -216,8 +216,8 @@ impl Config { let required_version = self.required_version(); if version != required_version { println!( - "Error: rustfmt version ({}) doesn't match the required version ({})", - version, required_version, + "Error: rustfmt version ({version}) doesn't match the required version \ +({required_version})" ); return false; } @@ -310,20 +310,20 @@ impl Config { .ok_or_else(|| String::from("Parsed config was not table"))?; for key in table.keys() { if !Config::is_valid_name(key) { - let msg = &format!("Warning: Unknown configuration option `{}`\n", key); + let msg = &format!("Warning: Unknown configuration option `{key}`\n"); err.push_str(msg) } } match parsed.try_into() { Ok(parsed_config) => { if !err.is_empty() { - eprint!("{}", err); + eprint!("{err}"); } Ok(Config::default().fill_from_parsed_config(parsed_config, dir)) } Err(e) => { err.push_str("Error: Decoding config file failed:\n"); - err.push_str(format!("{}\n", e).as_str()); + err.push_str(format!("{e}\n").as_str()); err.push_str("Please check your config file."); Err(err) } @@ -563,10 +563,7 @@ mod test { let toml = used_options.to_toml().unwrap(); assert_eq!( toml, - format!( - "merge_derives = {}\nskip_children = {}\n", - merge_derives, skip_children, - ) + format!("merge_derives = {merge_derives}\nskip_children = {skip_children}\n",) ); } diff --git a/src/config/options.rs b/src/config/options.rs index 3aa1a4de99d..e37f4027e4a 100644 --- a/src/config/options.rs +++ b/src/config/options.rs @@ -243,7 +243,7 @@ pub struct WidthHeuristics { impl fmt::Display for WidthHeuristics { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{:?}", self) + write!(f, "{self:?}") } } diff --git a/src/emitter.rs b/src/emitter.rs index dc2c99a301e..9c335314d75 100644 --- a/src/emitter.rs +++ b/src/emitter.rs @@ -47,6 +47,6 @@ pub(crate) trait Emitter { fn ensure_real_path(filename: &FileName) -> &Path { match *filename { FileName::Real(ref path) => path, - _ => panic!("cannot format `{}` and emit to files", filename), + _ => panic!("cannot format `{filename}` and emit to files"), } } diff --git a/src/emitter/checkstyle.rs b/src/emitter/checkstyle.rs index 545b259979d..56d6a0ed681 100644 --- a/src/emitter/checkstyle.rs +++ b/src/emitter/checkstyle.rs @@ -43,7 +43,7 @@ pub(crate) fn output_checkstyle_file( where T: Write, { - write!(writer, r#""#, filename)?; + write!(writer, r#""#)?; for mismatch in diff { let begin_line = mismatch.line_number; let mut current_line; @@ -82,7 +82,7 @@ mod tests { ); assert_eq!( &writer[..], - format!(r#""#, file_name).as_bytes() + format!(r#""#).as_bytes() ); } diff --git a/src/emitter/checkstyle/xml.rs b/src/emitter/checkstyle/xml.rs index f251aabe878..d1d9af70857 100644 --- a/src/emitter/checkstyle/xml.rs +++ b/src/emitter/checkstyle/xml.rs @@ -13,7 +13,7 @@ impl<'a> Display for XmlEscaped<'a> { '"' => write!(formatter, """), '\'' => write!(formatter, "'"), '&' => write!(formatter, "&"), - _ => write!(formatter, "{}", char), + _ => write!(formatter, "{char}"), }?; } diff --git a/src/emitter/diff.rs b/src/emitter/diff.rs index 5e1f1344656..764cd136e01 100644 --- a/src/emitter/diff.rs +++ b/src/emitter/diff.rs @@ -28,7 +28,7 @@ impl Emitter for DiffEmitter { if has_diff { if self.config.print_misformatted_file_names() { - writeln!(output, "{}", filename)?; + writeln!(output, "{filename}")?; } else { print_diff( mismatch, @@ -40,7 +40,7 @@ impl Emitter for DiffEmitter { // This occurs when the only difference between the original and formatted values // is the newline style. This happens because The make_diff function compares the // original and formatted values line by line, independent of line endings. - writeln!(output, "Incorrect newline style in {}", filename)?; + writeln!(output, "Incorrect newline style in {filename}")?; return Ok(EmitterResult { has_diff: true }); } @@ -110,7 +110,7 @@ mod tests { assert_eq!( String::from_utf8(writer).unwrap(), - format!("{}\n{}\n", bin_file, lib_file), + format!("{bin_file}\n{lib_file}\n"), ) } diff --git a/src/emitter/json.rs b/src/emitter/json.rs index c7f68d4675a..5594196bed9 100644 --- a/src/emitter/json.rs +++ b/src/emitter/json.rs @@ -96,7 +96,7 @@ impl JsonEmitter { }); } self.mismatched_files.push(MismatchedFile { - name: format!("{}", filename), + name: format!("{filename}"), mismatches, }); Ok(()) @@ -281,7 +281,7 @@ mod tests { }]) .unwrap(); assert_eq!(result.has_diff, true); - assert_eq!(&writer[..], format!("{}\n", exp_json).as_bytes()); + assert_eq!(&writer[..], format!("{exp_json}\n").as_bytes()); } #[test] @@ -341,6 +341,6 @@ mod tests { }; let exp_json = to_json_string(&vec![exp_bin, exp_lib]).unwrap(); - assert_eq!(&writer[..], format!("{}\n", exp_json).as_bytes()); + assert_eq!(&writer[..], format!("{exp_json}\n").as_bytes()); } } diff --git a/src/emitter/stdout.rs b/src/emitter/stdout.rs index 9fddd515e49..0bbc7332dfe 100644 --- a/src/emitter/stdout.rs +++ b/src/emitter/stdout.rs @@ -24,9 +24,9 @@ impl Emitter for StdoutEmitter { }: FormattedFile<'_>, ) -> Result { if self.verbosity != Verbosity::Quiet { - writeln!(output, "{}:\n", filename)?; + writeln!(output, "{filename}:\n")?; } - write!(output, "{}", formatted_text)?; + write!(output, "{formatted_text}")?; Ok(EmitterResult::default()) } } diff --git a/src/expr.rs b/src/expr.rs index 9a605d6427e..450f1476db0 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -187,7 +187,7 @@ pub(crate) fn format_expr( Some(label) => format!(" {}", label.ident), None => String::new(), }; - Some(format!("continue{}", id_str)) + Some(format!("continue{id_str}")) } ast::ExprKind::Break(ref opt_label, ref opt_expr) => { let id_str = match *opt_label { @@ -196,9 +196,9 @@ pub(crate) fn format_expr( }; if let Some(ref expr) = *opt_expr { - rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape) + rewrite_unary_prefix(context, &format!("break{id_str} "), &**expr, shape) } else { - Some(format!("break{}", id_str)) + Some(format!("break{id_str}")) } } ast::ExprKind::Yield(ref opt_expr) => { @@ -309,7 +309,7 @@ pub(crate) fn format_expr( match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) { (Some(lhs), Some(rhs)) => { let sp_delim = if context.config.spaces_around_ranges() { - format!(" {} ", delim) + format!(" {delim} ") } else { default_sp_delim(Some(lhs), Some(rhs)) }; @@ -324,7 +324,7 @@ pub(crate) fn format_expr( } (None, Some(rhs)) => { let sp_delim = if context.config.spaces_around_ranges() { - format!("{} ", delim) + format!("{delim} ") } else { default_sp_delim(None, Some(rhs)) }; @@ -332,7 +332,7 @@ pub(crate) fn format_expr( } (Some(lhs), None) => { let sp_delim = if context.config.spaces_around_ranges() { - format!(" {}", delim) + format!(" {delim}") } else { default_sp_delim(Some(lhs), None) }; @@ -375,7 +375,7 @@ pub(crate) fn format_expr( }; if let rw @ Some(_) = rewrite_single_line_block( context, - format!("{}{}", "async ", mover).as_str(), + format!("async {mover}").as_str(), block, Some(&expr.attrs), None, @@ -386,9 +386,7 @@ pub(crate) fn format_expr( // 6 = `async ` let budget = shape.width.saturating_sub(6); Some(format!( - "{}{}{}", - "async ", - mover, + "async {mover}{}", rewrite_block( block, Some(&expr.attrs), @@ -460,7 +458,7 @@ fn rewrite_empty_block( } if !block_contains_comment(context, block) && shape.width >= 2 { - return Some(format!("{}{}{{}}", prefix, label_str)); + return Some(format!("{prefix}{label_str}{{}}")); } // If a block contains only a single-line comment, then leave it on one line. @@ -473,7 +471,7 @@ fn rewrite_empty_block( && !comment_str.starts_with("//") && comment_str.len() + 4 <= shape.width { - return Some(format!("{}{}{{ {} }}", prefix, label_str, comment_str)); + return Some(format!("{prefix}{label_str}{{ {comment_str} }}")); } } @@ -520,7 +518,7 @@ fn rewrite_single_line_block( let expr_shape = shape.offset_left(last_line_width(prefix))?; let expr_str = block_expr.rewrite(context, expr_shape)?; let label_str = rewrite_label(label); - let result = format!("{}{}{{ {} }}", prefix, label_str, expr_str); + let result = format!("{prefix}{label_str}{{ {expr_str} }}"); if result.len() <= shape.width && !result.contains('\n') { return Some(result); } @@ -1100,7 +1098,7 @@ impl<'a> Rewrite for ControlFlow<'a> { result? }; - let mut result = format!("{}{}", cond_str, block_str); + let mut result = format!("{cond_str}{block_str}"); if let Some(else_block) = self.else_block { let shape = Shape::indented(shape.indent, context.config); @@ -1160,8 +1158,7 @@ fn rewrite_label(opt_label: Option) -> Cow<'static, str> { fn extract_comment(span: Span, context: &RewriteContext<'_>, shape: Shape) -> Option { match rewrite_missing_comment(span, shape, context) { Some(ref comment) if !comment.is_empty() => Some(format!( - "{indent}{}{indent}", - comment, + "{indent}{comment}{indent}", indent = shape.indent.to_string_with_newline(context.config) )), _ => None, @@ -1478,7 +1475,7 @@ pub(crate) fn rewrite_paren( let subexpr_str = subexpr.rewrite(context, sub_shape)?; let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//"); if fits_single_line { - Some(format!("({}{}{})", pre_comment, subexpr_str, post_comment)) + Some(format!("({pre_comment}{subexpr_str}{post_comment})")) } else { rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span) } @@ -1542,7 +1539,7 @@ fn rewrite_index( // Return if index fits in a single line. match orig_index_rw { Some(ref index_str) if !index_str.contains('\n') => { - return Some(format!("{}[{}]", expr_str, index_str)); + return Some(format!("{expr_str}[{index_str}]")); } _ => (), } @@ -1565,7 +1562,7 @@ fn rewrite_index( indent.to_string_with_newline(context.config), new_index_str, )), - (Some(ref index_str), _) => Some(format!("{}[{}]", expr_str, index_str)), + (Some(ref index_str), _) => Some(format!("{expr_str}[{index_str}]")), _ => None, } } @@ -1597,9 +1594,9 @@ fn rewrite_struct_lit<'a>( let path_str = rewrite_path(context, PathContext::Expr, qself, path, path_shape)?; let has_base_or_rest = match struct_rest { - ast::StructRest::None if fields.is_empty() => return Some(format!("{} {{}}", path_str)), + ast::StructRest::None if fields.is_empty() => return Some(format!("{path_str} {{}}")), ast::StructRest::Rest(_) if fields.is_empty() => { - return Some(format!("{} {{ .. }}", path_str)); + return Some(format!("{path_str} {{ .. }}")); } ast::StructRest::Rest(_) | ast::StructRest::Base(_) => true, _ => false, @@ -1690,7 +1687,7 @@ fn rewrite_struct_lit<'a>( let fields_str = wrap_struct_field(context, attrs, &fields_str, shape, v_shape, one_line_width)?; - Some(format!("{} {{{}}}", path_str, fields_str)) + Some(format!("{path_str} {{{fields_str}}}")) // FIXME if context.config.indent_style() == Visual, but we run out // of space, we should fall back to BlockIndent. @@ -1720,7 +1717,7 @@ pub(crate) fn wrap_struct_field( )) } else { // One liner or visual indent. - Some(format!(" {} ", fields_str)) + Some(format!(" {fields_str} ")) } } else { Some(format!( @@ -1769,7 +1766,7 @@ pub(crate) fn rewrite_field( { Some(attrs_str + name) } - Some(e) => Some(format!("{}{}{}{}", attrs_str, name, separator, e)), + Some(e) => Some(format!("{attrs_str}{name}{separator}{e}")), None => { let expr_offset = shape.indent.block_indent(context.config); let expr = field @@ -1834,7 +1831,7 @@ fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>( .ends_with_newline(false); let list_str = write_list(&item_vec, &fmt)?; - Some(format!("({})", list_str)) + Some(format!("({list_str})")) } pub(crate) fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>( @@ -2076,7 +2073,7 @@ fn choose_rhs( Some(ref new_str) if !new_str.contains('\n') && unicode_str_width(new_str) <= shape.width => { - Some(format!(" {}", new_str)) + Some(format!(" {new_str}")) } _ => { // Expression did not fit on the same line as the identifier. @@ -2093,21 +2090,21 @@ fn choose_rhs( (Some(ref orig_rhs), Some(ref new_rhs)) if !filtered_str_fits(&new_rhs, context.config.max_width(), new_shape) => { - Some(format!("{}{}", before_space_str, orig_rhs)) + Some(format!("{before_space_str}{orig_rhs}")) } (Some(ref orig_rhs), Some(ref new_rhs)) if prefer_next_line(orig_rhs, new_rhs, rhs_tactics) => { - Some(format!("{}{}", new_indent_str, new_rhs)) + Some(format!("{new_indent_str}{new_rhs}")) } - (None, Some(ref new_rhs)) => Some(format!("{}{}", new_indent_str, new_rhs)), + (None, Some(ref new_rhs)) => Some(format!("{new_indent_str}{new_rhs}")), (None, None) if rhs_tactics == RhsTactics::AllowOverflow => { let shape = shape.infinite_width(); expr.rewrite(context, shape) .map(|s| format!("{}{}", before_space_str, s)) } (None, None) => None, - (Some(orig_rhs), _) => Some(format!("{}{}", before_space_str, orig_rhs)), + (Some(orig_rhs), _) => Some(format!("{before_space_str}{orig_rhs}")), } } } diff --git a/src/format-diff/main.rs b/src/format-diff/main.rs index db4a21ba09e..61e2cb711a5 100644 --- a/src/format-diff/main.rs +++ b/src/format-diff/main.rs @@ -69,7 +69,7 @@ fn main() { .init(); let opts = Opts::parse(); if let Err(e) = run(opts) { - println!("{}", e); + println!("{e}"); Opts::command() .print_help() .expect("cannot write to stdout"); @@ -113,7 +113,7 @@ fn run_rustfmt(files: &HashSet, ranges: &[Range]) -> Result<(), FormatDi if !exit_status.success() { return Err(FormatDiffError::IoError(io::Error::new( io::ErrorKind::Other, - format!("rustfmt failed with {}", exit_status), + format!("rustfmt failed with {exit_status}"), ))); } Ok(()) @@ -129,12 +129,12 @@ fn scan_diff( where R: io::Read, { - let diff_pattern = format!(r"^\+\+\+\s(?:.*?/){{{}}}(\S*)", skip_prefix); + let diff_pattern = format!(r"^\+\+\+\s(?:.*?/){{{skip_prefix}}}(\S*)"); let diff_pattern = Regex::new(&diff_pattern).unwrap(); let lines_pattern = Regex::new(r"^@@.*\+(\d+)(,(\d+))?").unwrap(); - let file_filter = Regex::new(&format!("^{}$", file_filter))?; + let file_filter = Regex::new(&format!("^{file_filter}$"))?; let mut current_file = None; diff --git a/src/formatting.rs b/src/formatting.rs index 1f4ad6960e2..cd57a025b67 100644 --- a/src/formatting.rs +++ b/src/formatting.rs @@ -296,7 +296,7 @@ impl<'b, T: Write + 'b> FormatHandler for Session<'b, T> { Ok(ref result) if result.has_diff => report.add_diff(), Err(e) => { // Create a new error with path_str to help users see which files failed - let err_msg = format!("{}: {}", path, e); + let err_msg = format!("{path}: {e}"); return Err(io::Error::new(e.kind(), err_msg).into()); } _ => {} diff --git a/src/git-rustfmt/main.rs b/src/git-rustfmt/main.rs index efeda53e7ec..3059d917c6b 100644 --- a/src/git-rustfmt/main.rs +++ b/src/git-rustfmt/main.rs @@ -43,7 +43,7 @@ fn git_diff(commits: &str) -> String { let mut cmd = Command::new("git"); cmd.arg("diff"); if commits != "0" { - cmd.arg(format!("HEAD~{}", commits)); + cmd.arg(format!("HEAD~{commits}")); } let output = cmd.output().expect("Couldn't execute `git diff`"); String::from_utf8_lossy(&output.stdout).into_owned() @@ -108,7 +108,7 @@ fn check_uncommitted() { if !uncommitted.is_empty() { println!("Found untracked changes:"); for f in &uncommitted { - println!(" {}", f); + println!(" {f}"); } println!("Commit your work, or run with `-u`."); println!("Exiting."); diff --git a/src/imports.rs b/src/imports.rs index 339e5cef5af..6f0050647dc 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -191,7 +191,7 @@ impl UseSegment { "crate" => UseSegmentKind::Crate(None), _ => { let mod_sep = if modsep { "::" } else { "" }; - UseSegmentKind::Ident(format!("{}{}", mod_sep, name), None) + UseSegmentKind::Ident(format!("{mod_sep}{name}"), None) } }; @@ -295,8 +295,8 @@ impl fmt::Display for UseSegmentKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { UseSegmentKind::Glob => write!(f, "*"), - UseSegmentKind::Ident(ref s, Some(ref alias)) => write!(f, "{} as {}", s, alias), - UseSegmentKind::Ident(ref s, None) => write!(f, "{}", s), + UseSegmentKind::Ident(ref s, Some(ref alias)) => write!(f, "{s} as {alias}"), + UseSegmentKind::Ident(ref s, None) => write!(f, "{s}"), UseSegmentKind::Slf(..) => write!(f, "self"), UseSegmentKind::Super(..) => write!(f, "super"), UseSegmentKind::Crate(..) => write!(f, "crate"), @@ -306,7 +306,7 @@ impl fmt::Display for UseSegmentKind { if i != 0 { write!(f, ", ")?; } - write!(f, "{}", item)?; + write!(f, "{item}")?; } write!(f, "}}") } @@ -319,7 +319,7 @@ impl fmt::Display for UseTree { if i != 0 { write!(f, "::")?; } - write!(f, "{}", segment)?; + write!(f, "{segment}")?; } Ok(()) } @@ -1042,7 +1042,7 @@ fn rewrite_nested_use_tree( shape.indent.to_string(context.config) ) } else { - format!("{{{}}}", list_str) + format!("{{{list_str}}}") }; Some(result) @@ -1052,14 +1052,14 @@ impl Rewrite for UseSegment { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { Some(match self.kind { UseSegmentKind::Ident(ref ident, Some(ref rename)) => { - format!("{} as {}", ident, rename) + format!("{ident} as {rename}") } UseSegmentKind::Ident(ref ident, None) => ident.clone(), - UseSegmentKind::Slf(Some(ref rename)) => format!("self as {}", rename), + UseSegmentKind::Slf(Some(ref rename)) => format!("self as {rename}"), UseSegmentKind::Slf(None) => "self".to_owned(), - UseSegmentKind::Super(Some(ref rename)) => format!("super as {}", rename), + UseSegmentKind::Super(Some(ref rename)) => format!("super as {rename}"), UseSegmentKind::Super(None) => "super".to_owned(), - UseSegmentKind::Crate(Some(ref rename)) => format!("crate as {}", rename), + UseSegmentKind::Crate(Some(ref rename)) => format!("crate as {rename}"), UseSegmentKind::Crate(None) => "crate".to_owned(), UseSegmentKind::Glob => "*".to_owned(), UseSegmentKind::List(ref use_tree_list) => rewrite_nested_use_tree( diff --git a/src/items.rs b/src/items.rs index fd4e08ed403..a72646ef897 100644 --- a/src/items.rs +++ b/src/items.rs @@ -470,7 +470,7 @@ impl<'a> FmtVisitor<'a> { && self.block_indent.width() + fn_str.len() + 3 <= self.config.max_width() && !last_line_contains_single_line_comment(fn_str) { - return Some(format!("{} {{}}", fn_str)); + return Some(format!("{fn_str} {{}}")); } if !self.config.fn_single_line() || !is_simple_block_stmt(&context, block, None) { @@ -482,7 +482,7 @@ impl<'a> FmtVisitor<'a> { let width = self.block_indent.width() + fn_str.len() + res.len() + 5; if !res.contains('\n') && width <= self.config.max_width() { - Some(format!("{} {{ {} }}", fn_str, res)) + Some(format!("{fn_str} {{ {res} }}")) } else { None } @@ -664,7 +664,7 @@ impl<'a> FmtVisitor<'a> { }; let variant_body = if let Some(ref expr) = field.disr_expr { - let lhs = format!("{:1$} =", variant_body, pad_discrim_ident_to); + let lhs = format!("{variant_body:pad_discrim_ident_to$} ="); let ex = &*expr.value; rewrite_assign_rhs_with( &context, @@ -827,7 +827,7 @@ pub(crate) fn format_impl( if generics.where_clause.predicates.len() == 1 { result.push(','); } - result.push_str(&format!("{}{{{}}}", sep, sep)); + result.push_str(&format!("{sep}{{{sep}}}")); } else { result.push_str(" {}"); } @@ -1018,7 +1018,7 @@ fn rewrite_trait_ref( let shape = Shape::indented(offset + used_space, context.config); if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) { if !trait_ref_str.contains('\n') { - return Some(format!(" {}{}", polarity_str, trait_ref_str)); + return Some(format!(" {polarity_str}{trait_ref_str}")); } } // We could not make enough space for trait_ref, so put it on new line. @@ -1320,7 +1320,7 @@ impl<'a> Rewrite for TraitAliasBounds<'a> { shape.indent.to_string_with_newline(context.config) }; - Some(format!("{}{}{}", generic_bounds_str, space, where_str)) + Some(format!("{generic_bounds_str}{space}{where_str}")) } } @@ -1337,7 +1337,7 @@ pub(crate) fn format_trait_alias( let g_shape = shape.offset_left(6)?.sub_width(2)?; let generics_str = rewrite_generics(context, alias, generics, g_shape)?; let vis_str = format_visibility(context, vis); - let lhs = format!("{}trait {} =", vis_str, generics_str); + let lhs = format!("{vis_str}trait {generics_str} ="); // 1 = ";" let trait_alias_bounds = TraitAliasBounds { generic_bounds, @@ -1374,7 +1374,7 @@ fn format_unit_struct( } else { String::new() }; - Some(format!("{}{};", header_str, generics_str)) + Some(format!("{header_str}{generics_str};")) } pub(crate) fn format_struct_struct( @@ -1464,7 +1464,7 @@ pub(crate) fn format_struct_struct( && items_str.len() <= one_line_budget && !last_line_contains_single_line_comment(&items_str) { - Some(format!("{} {} }}", result, items_str)) + Some(format!("{result} {items_str} }}")) } else { Some(format!( "{}\n{}{}\n{}}}", @@ -1694,7 +1694,7 @@ pub(crate) fn rewrite_type_alias<'a, 'b>( rewrite_ty(rw_info, Some(bounds), ty_opt, vis) }?; match defaultness { - ast::Defaultness::Default(..) => Some(format!("default {}", result)), + ast::Defaultness::Default(..) => Some(format!("default {result}")), _ => Some(result), } } @@ -1801,14 +1801,14 @@ fn rewrite_ty( true, )? } - _ => format!("{}=", result), + _ => format!("{result}="), }; // 1 = `;` let shape = Shape::indented(indent, context.config).sub_width(1)?; rewrite_assign_rhs(context, lhs, &*ty, &RhsAssignKind::Ty, shape).map(|s| s + ";") } else { - Some(format!("{};", result)) + Some(format!("{result};")) } } @@ -2017,7 +2017,7 @@ fn rewrite_static( let expr_lo = expr.span.lo(); let comments_span = mk_sp(comments_lo, expr_lo); - let lhs = format!("{}{} =", prefix, ty_str); + let lhs = format!("{prefix}{ty_str} ="); // 1 = ; let remaining_width = context.budget(offset.block_indent + 1); @@ -2034,7 +2034,7 @@ fn rewrite_static( .and_then(|res| recover_comment_removed(res, static_parts.span, context)) .map(|s| if s.ends_with(';') { s } else { s + ";" }) } else { - Some(format!("{}{};", prefix, ty_str)) + Some(format!("{prefix}{ty_str};")) } } @@ -2227,7 +2227,7 @@ fn rewrite_explicit_self( Some(combine_strs_with_missing_comments( context, param_attrs, - &format!("&{} {}self", lifetime_str, mut_str), + &format!("&{lifetime_str} {mut_str}self"), span, shape, !has_multiple_attr_lines, @@ -2236,7 +2236,7 @@ fn rewrite_explicit_self( None => Some(combine_strs_with_missing_comments( context, param_attrs, - &format!("&{}self", mut_str), + &format!("&{mut_str}self"), span, shape, !has_multiple_attr_lines, @@ -2906,7 +2906,7 @@ fn rewrite_where_clause_rfc_style( clause_shape.indent.to_string_with_newline(context.config) }; - Some(format!("{}{}{}", where_keyword, clause_sep, preds_str)) + Some(format!("{where_keyword}{clause_sep}{preds_str}")) } /// Rewrite `where` and comment around it. @@ -2946,8 +2946,8 @@ fn rewrite_where_keyword( let newline_before_where = comment_separator(&comment_before, shape); let newline_after_where = comment_separator(&comment_after, clause_shape); let result = format!( - "{}{}{}where{}{}", - starting_newline, comment_before, newline_before_where, newline_after_where, comment_after + "{starting_newline}{comment_before}{newline_before_where}where\ +{newline_after_where}{comment_after}" ); let allow_single_line = where_clause_option.allow_single_line && comment_before.is_empty() @@ -3102,7 +3102,7 @@ fn rewrite_where_clause( preds_str )) } else { - Some(format!(" where {}", preds_str)) + Some(format!(" where {preds_str}")) } } diff --git a/src/macros.rs b/src/macros.rs index 88d26358b87..b6a49536d17 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -103,7 +103,7 @@ fn rewrite_macro_name( format!("{}!", pprust::path_to_string(path)) }; match extra_ident { - Some(ident) if ident.name != kw::Empty => format!("{} {}", name, ident), + Some(ident) if ident.name != kw::Empty => format!("{name} {ident}"), _ => name, } } @@ -214,14 +214,14 @@ fn rewrite_macro_inner( if ts.is_empty() && !has_comment { return match style { Delimiter::Parenthesis if position == MacroPosition::Item => { - Some(format!("{}();", macro_name)) + Some(format!("{macro_name}();")) } Delimiter::Bracket if position == MacroPosition::Item => { - Some(format!("{}[];", macro_name)) + Some(format!("{macro_name}[];")) } - Delimiter::Parenthesis => Some(format!("{}()", macro_name)), - Delimiter::Bracket => Some(format!("{}[]", macro_name)), - Delimiter::Brace => Some(format!("{} {{}}", macro_name)), + Delimiter::Parenthesis => Some(format!("{macro_name}()")), + Delimiter::Bracket => Some(format!("{macro_name}[]")), + Delimiter::Brace => Some(format!("{macro_name} {{}}")), _ => unreachable!(), }; } @@ -321,7 +321,7 @@ fn rewrite_macro_inner( _ => "", }; - Some(format!("{}{}", rewrite, comma)) + Some(format!("{rewrite}{comma}")) } } Delimiter::Brace => { @@ -330,8 +330,8 @@ fn rewrite_macro_inner( // anything in between the braces (for now). let snippet = context.snippet(mac.span()).trim_start_matches(|c| c != '{'); match trim_left_preserve_layout(snippet, shape.indent, context.config) { - Some(macro_body) => Some(format!("{} {}", macro_name, macro_body)), - None => Some(format!("{} {}", macro_name, snippet)), + Some(macro_body) => Some(format!("{macro_name} {macro_body}")), + None => Some(format!("{macro_name} {snippet}")), } } _ => unreachable!(), @@ -362,7 +362,7 @@ fn handle_vec_semi( && lhs.len() + rhs.len() + total_overhead <= shape.width { // macro_name(lhs; rhs) or macro_name[lhs; rhs] - Some(format!("{}{}{}; {}{}", macro_name, left, lhs, rhs, right)) + Some(format!("{macro_name}{left}{lhs}; {rhs}{right}")) } else { // macro_name(\nlhs;\nrhs\n) or macro_name[\nlhs;\nrhs\n] Some(format!( @@ -596,8 +596,8 @@ fn delim_token_to_str( .block_indent(context.config) .to_string_with_newline(context.config); ( - format!("{}{}", lhs, nested_indent_str), - format!("{}{}", indent_str, rhs), + format!("{lhs}{nested_indent_str}"), + format!("{indent_str}{rhs}"), ) } else { (lhs.to_owned(), rhs.to_owned()) @@ -654,7 +654,7 @@ impl MacroArgKind { }; match *self { - MacroArgKind::MetaVariable(ty, ref name) => Some(format!("${}:{}", name, ty)), + MacroArgKind::MetaVariable(ty, ref name) => Some(format!("${name}:{ty}")), MacroArgKind::Repeat(delim_tok, ref args, ref another, ref tok) => { let (lhs, inner, rhs) = rewrite_delimited_inner(delim_tok, args)?; let another = another @@ -663,14 +663,14 @@ impl MacroArgKind { .unwrap_or_else(|| "".to_owned()); let repeat_tok = pprust::token_to_string(tok); - Some(format!("${}{}{}{}{}", lhs, inner, rhs, another, repeat_tok)) + Some(format!("${lhs}{inner}{rhs}{another}{repeat_tok}")) } MacroArgKind::Delimited(delim_tok, ref args) => { rewrite_delimited_inner(delim_tok, args) .map(|(lhs, inner, rhs)| format!("{}{}{}", lhs, inner, rhs)) } - MacroArgKind::Separator(ref sep, ref prefix) => Some(format!("{}{} ", prefix, sep)), - MacroArgKind::Other(ref inner, ref prefix) => Some(format!("{}{}", prefix, inner)), + MacroArgKind::Separator(ref sep, ref prefix) => Some(format!("{prefix}{sep} ")), + MacroArgKind::Other(ref inner, ref prefix) => Some(format!("{prefix}{inner}")), } } } diff --git a/src/matches.rs b/src/matches.rs index a7677c3a35c..27a9c1d3130 100644 --- a/src/matches.rs +++ b/src/matches.rs @@ -124,7 +124,7 @@ pub(crate) fn rewrite_match( if arms.is_empty() { let snippet = context.snippet(mk_sp(open_brace_pos, span.hi() - BytePos(1))); if snippet.trim().is_empty() { - Some(format!("match {} {{}}", cond_str)) + Some(format!("match {cond_str} {{}}")) } else { // Empty match with comments or inner attributes? We are not going to bother, sorry ;) Some(context.snippet(span).to_owned()) @@ -274,7 +274,7 @@ fn rewrite_match_arm( let lhs_str = combine_strs_with_missing_comments( context, &attrs_str, - &format!("{}{}{}", pipe_str, pats_str, guard_str), + &format!("{pipe_str}{pats_str}{guard_str}"), missing_span, shape, false, @@ -543,7 +543,7 @@ fn rewrite_guard( if let Some(cond_shape) = cond_shape { if let Some(cond_str) = guard.rewrite(context, cond_shape) { if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() { - return Some(format!(" if {}", cond_str)); + return Some(format!(" if {cond_str}")); } } } diff --git a/src/pairs.rs b/src/pairs.rs index d135da7e359..96f023b3b0e 100644 --- a/src/pairs.rs +++ b/src/pairs.rs @@ -234,8 +234,8 @@ where let rhs_result = rhs.rewrite(context, rhs_shape)?; let indent_str = rhs_shape.indent.to_string_with_newline(context.config); let infix_with_sep = match separator_place { - SeparatorPlace::Back => format!("{}{}", infix, indent_str), - SeparatorPlace::Front => format!("{}{}", indent_str, infix), + SeparatorPlace::Back => format!("{infix}{indent_str}"), + SeparatorPlace::Front => format!("{indent_str}{infix}"), }; Some(format!( "{}{}{}{}", diff --git a/src/parse/session.rs b/src/parse/session.rs index 81b5015dde3..2edb830a573 100644 --- a/src/parse/session.rs +++ b/src/parse/session.rs @@ -331,8 +331,7 @@ impl LineRangeUtils for ParseSess { debug_assert_eq!( lo.sf.name, hi.sf.name, - "span crossed file boundary: lo: {:?}, hi: {:?}", - lo, hi + "span crossed file boundary: lo: {lo:?}, hi: {hi:?}" ); // in case the span starts with a newline, the line range is off by 1 without the diff --git a/src/patterns.rs b/src/patterns.rs index 3f335172590..33f3b4b8a21 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -208,7 +208,7 @@ impl Rewrite for Pat { None => "", Some(_) => " ", }; - format!("{}{}{}", lhs_spacing, infix, rhs_spacing) + format!("{lhs_spacing}{infix}{rhs_spacing}") } else { infix.to_owned() }; @@ -283,7 +283,7 @@ fn rewrite_struct_pat( let path_str = rewrite_path(context, PathContext::Expr, qself, path, path_shape)?; if fields.is_empty() && !ellipsis { - return Some(format!("{} {{}}", path_str)); + return Some(format!("{path_str} {{}}")); } let (ellipsis_str, terminator) = if ellipsis { (", ..", "..") } else { ("", "}") }; @@ -344,7 +344,7 @@ fn rewrite_struct_pat( // ast::Pat doesn't have attrs so use &[] let fields_str = wrap_struct_field(context, &[], &fields_str, shape, v_shape, one_line_width)?; - Some(format!("{} {{{}}}", path_str, fields_str)) + Some(format!("{path_str} {{{fields_str}}}")) } impl Rewrite for PatField { @@ -376,7 +376,7 @@ impl Rewrite for PatField { let id_str = rewrite_ident(context, self.ident); let one_line_width = id_str.len() + 2 + pat_str.len(); let pat_and_id_str = if one_line_width <= shape.width { - format!("{}: {}", id_str, pat_str) + format!("{id_str}: {pat_str}") } else { format!( "{}:\n{}{}", diff --git a/src/rustfmt_diff.rs b/src/rustfmt_diff.rs index 1724a0f87bf..c9883452185 100644 --- a/src/rustfmt_diff.rs +++ b/src/rustfmt_diff.rs @@ -95,7 +95,7 @@ impl fmt::Display for ModifiedLines { )?; for line in &chunk.lines { - writeln!(f, "{}", line)?; + writeln!(f, "{line}")?; } } @@ -166,12 +166,12 @@ impl OutputWriter { if let Some(color) = color { t.fg(color).unwrap(); } - writeln!(t, "{}", msg).unwrap(); + writeln!(t, "{msg}").unwrap(); if color.is_some() { t.reset().unwrap(); } } - None => println!("{}", msg), + None => println!("{msg}"), } } } @@ -265,16 +265,15 @@ where for line in mismatch.lines { match line { DiffLine::Context(ref str) => { - writer.writeln(&format!(" {}{}", str, line_terminator), None) + writer.writeln(&format!(" {str}{line_terminator}"), None) } DiffLine::Expected(ref str) => writer.writeln( - &format!("+{}{}", str, line_terminator), + &format!("+{str}{line_terminator}"), Some(term::color::GREEN), ), - DiffLine::Resulting(ref str) => writer.writeln( - &format!("-{}{}", str, line_terminator), - Some(term::color::RED), - ), + DiffLine::Resulting(ref str) => { + writer.writeln(&format!("-{str}{line_terminator}"), Some(term::color::RED)) + } } } } diff --git a/src/skip.rs b/src/skip.rs index 68f85b2ade4..d733f7068fd 100644 --- a/src/skip.rs +++ b/src/skip.rs @@ -105,7 +105,7 @@ pub(crate) fn is_skip_attr(segments: &[ast::PathSegment]) -> bool { fn get_skip_names(kind: &str, attrs: &[ast::Attribute]) -> Vec { let mut skip_names = vec![]; - let path = format!("{}::{}::{}", RUSTFMT, SKIP, kind); + let path = format!("{RUSTFMT}::{SKIP}::{kind}"); for attr in attrs { // rustc_ast::ast::Path is implemented partialEq // but it is designed for segments.len() == 1 diff --git a/src/source_file.rs b/src/source_file.rs index 56d4ab40038..958f9b0154f 100644 --- a/src/source_file.rs +++ b/src/source_file.rs @@ -62,7 +62,7 @@ where fn ensure_real_path(filename: &FileName) -> &Path { match *filename { FileName::Real(ref path) => path, - _ => panic!("cannot format `{}` and emit to files", filename), + _ => panic!("cannot format `{filename}` and emit to files"), } } diff --git a/src/test/configuration_snippet.rs b/src/test/configuration_snippet.rs index c70b3c5facd..80b61c88a00 100644 --- a/src/test/configuration_snippet.rs +++ b/src/test/configuration_snippet.rs @@ -233,13 +233,11 @@ impl ConfigCodeBlock { Some(ConfigurationSection::ConfigName(name)) => { assert!( Config::is_valid_name(&name), - "an unknown configuration option was found: {}", - name + "an unknown configuration option was found: {name}" ); assert!( hash_set.remove(&name), - "multiple configuration guides found for option {}", - name + "multiple configuration guides found for option {name}" ); code_block.set_config_name(Some(name)); } @@ -266,7 +264,7 @@ fn configuration_snippet_tests() { // Display results. println!("Ran {} configurations tests.", blocks.len()); - assert_eq!(failures, 0, "{} configurations tests failed", failures); + assert_eq!(failures, 0, "{failures} configurations tests failed"); } // Read Configurations.md and build a `Vec` of `ConfigCodeBlock` structs with one @@ -289,7 +287,7 @@ fn get_code_blocks() -> Vec { for name in hash_set { if !Config::is_hidden_option(&name) { - panic!("{} does not have a configuration guide", name); + panic!("{name} does not have a configuration guide"); } } diff --git a/src/test/mod.rs b/src/test/mod.rs index f88ab3f194b..c8137c1bd28 100644 --- a/src/test/mod.rs +++ b/src/test/mod.rs @@ -203,8 +203,8 @@ fn coverage_tests() { let files = get_test_files(Path::new("tests/coverage/source"), true); let (_reports, count, fails) = check_files(files, &None); - println!("Ran {} tests in coverage mode.", count); - assert_eq!(fails, 0, "{} tests failed", fails); + println!("Ran {count} tests in coverage mode."); + assert_eq!(fails, 0, "{fails} tests failed"); } #[test] @@ -396,8 +396,8 @@ fn self_tests() { let mut warnings = 0; // Display results. - println!("Ran {} self tests.", count); - assert_eq!(fails, 0, "{} self tests failed", fails); + println!("Ran {count} self tests."); + assert_eq!(fails, 0, "{fails} self tests failed"); for format_report in reports { println!( @@ -407,11 +407,7 @@ fn self_tests() { warnings += format_report.warning_count(); } - assert_eq!( - warnings, 0, - "Rustfmt's code generated {} warnings", - warnings - ); + assert_eq!(warnings, 0, "Rustfmt's code generated {warnings} warnings"); } #[test] @@ -606,7 +602,7 @@ fn stdin_handles_mod_inner_ignore_attr() { fn format_lines_errors_are_reported() { init_log(); let long_identifier = String::from_utf8(vec![b'a'; 239]).unwrap(); - let input = Input::Text(format!("fn {}() {{}}", long_identifier)); + let input = Input::Text(format!("fn {long_identifier}() {{}}")); let mut config = Config::default(); config.set().error_on_line_overflow(true); let mut session = Session::::new(config, None); @@ -618,7 +614,7 @@ fn format_lines_errors_are_reported() { fn format_lines_errors_are_reported_with_tabs() { init_log(); let long_identifier = String::from_utf8(vec![b'a'; 97]).unwrap(); - let input = Input::Text(format!("fn a() {{\n\t{}\n}}", long_identifier)); + let input = Input::Text(format!("fn a() {{\n\t{long_identifier}\n}}")); let mut config = Config::default(); config.set().error_on_line_overflow(true); config.set().hard_tabs(true); @@ -829,11 +825,11 @@ fn handle_result( for (file_name, fmt_text) in result { // If file is in tests/source, compare to file with same name in tests/target. let target = get_target(&file_name, target); - let open_error = format!("couldn't open target {:?}", target); + let open_error = format!("couldn't open target {target:?}"); let mut f = fs::File::open(&target).expect(&open_error); let mut text = String::new(); - let read_error = format!("failed reading target {:?}", target); + let read_error = format!("failed reading target {target:?}"); f.read_to_string(&mut text).expect(&read_error); // Ignore LF and CRLF difference for Windows. diff --git a/src/types.rs b/src/types.rs index aef85598f06..8be474d5bca 100644 --- a/src/types.rs +++ b/src/types.rs @@ -301,7 +301,7 @@ where let output = match *output { FnRetTy::Ty(ref ty) => { let type_str = ty.rewrite(context, ty_shape)?; - format!(" -> {}", type_str) + format!(" -> {type_str}") } FnRetTy::Default(..) => String::new(), }; @@ -373,7 +373,7 @@ where || !context.use_block_indent() || is_inputs_empty { - format!("({})", list_str) + format!("({list_str})") } else { format!( "({}{}{})", @@ -383,7 +383,7 @@ where ) }; if output.is_empty() || last_line_width(&args) + first_line_width(&output) <= shape.width { - Some(format!("{}{}", args, output)) + Some(format!("{args}{output}")) } else { Some(format!( "{}\n{}{}", @@ -429,9 +429,9 @@ impl Rewrite for ast::WherePredicate { let lhs = if let Some(binder_str) = rewrite_bound_params(context, shape, bound_generic_params) { - format!("for<{}> {}{}", binder_str, type_str, colon) + format!("for<{binder_str}> {type_str}{colon}") } else { - format!("{}{}", type_str, colon) + format!("{type_str}{colon}") }; rewrite_assign_rhs(context, lhs, bounds, &RhsAssignKind::Bounds, shape)? @@ -665,7 +665,7 @@ impl Rewrite for ast::PolyTraitRef { .trait_ref .rewrite(context, shape.offset_left(extra_offset)?)?; - Some(format!("for<{}> {}", lifetime_str, path_str)) + Some(format!("for<{lifetime_str}> {path_str}")) } else { self.trait_ref.rewrite(context, shape) } @@ -695,7 +695,7 @@ impl Rewrite for ast::Ty { res.push('+'); } } - Some(format!("{}{}", prefix, res)) + Some(format!("{prefix}{res}")) } ast::TyKind::Ptr(ref mt) => { let prefix = match mt.mutbl { @@ -791,7 +791,7 @@ impl Rewrite for ast::Ty { if let Some(sh) = shape.sub_width(2) { if let Some(ref s) = ty.rewrite(context, sh) { if !s.contains('\n') { - return Some(format!("({})", s)); + return Some(format!("({s})")); } } } diff --git a/src/utils.rs b/src/utils.rs index b8a44d4bade..d1cb197cb51 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -69,7 +69,7 @@ pub(crate) fn format_visibility( let path = segments_iter.collect::>().join("::"); let in_str = if is_keyword(&path) { "" } else { "in " }; - Cow::from(format!("pub({}{}) ", in_str, path)) + Cow::from(format!("pub({in_str}{path}) ")) } } } @@ -147,7 +147,7 @@ pub(crate) fn format_extern( } else if abi == "C" && !explicit_abi { Cow::from("extern ") } else { - Cow::from(format!(r#"extern "{}" "#, abi)) + Cow::from(format!(r#"extern "{abi}" "#)) } } diff --git a/tests/cargo-fmt/main.rs b/tests/cargo-fmt/main.rs index 701c36fadea..63573bf341b 100644 --- a/tests/cargo-fmt/main.rs +++ b/tests/cargo-fmt/main.rs @@ -26,7 +26,7 @@ fn cargo_fmt(args: &[&str]) -> (String, String) { String::from_utf8(output.stdout).expect("utf-8"), String::from_utf8(output.stderr).expect("utf-8"), ), - Err(e) => panic!("failed to run `{:?} {:?}`: {}", cmd, args, e), + Err(e) => panic!("failed to run `{cmd:?} {args:?}`: {e}"), } } diff --git a/tests/rustfmt/main.rs b/tests/rustfmt/main.rs index 4936a717463..7dcf7c8416e 100644 --- a/tests/rustfmt/main.rs +++ b/tests/rustfmt/main.rs @@ -27,7 +27,7 @@ fn rustfmt(args: &[&str]) -> (String, String) { String::from_utf8(output.stdout).expect("utf-8"), String::from_utf8(output.stderr).expect("utf-8"), ), - Err(e) => panic!("failed to run `{:?} {:?}`: {}", cmd, args, e), + Err(e) => panic!("failed to run `{cmd:?} {args:?}`: {e}"), } } @@ -71,9 +71,7 @@ fn print_config() { ]); assert!( Path::new("minimal-config").exists(), - "stdout:\n{}\nstderr:\n{}", - stdout, - stderr + "stdout:\n{stdout}\nstderr:\n{stderr}" ); remove_file("minimal-config").unwrap(); } -- cgit 1.4.1-3-g733a5