From ab480856a5ef3252ef5a57e8a3b553c0fce4ab4a Mon Sep 17 00:00:00 2001 From: Stefan Holderbach Date: Mon, 30 Jan 2023 02:37:54 +0100 Subject: [PATCH] Use variable names directly in the format strings (#7906) # Description Lint: `clippy::uninlined_format_args` More readable in most situations. (May be slightly confusing for modifier format strings https://doc.rust-lang.org/std/fmt/index.html#formatting-parameters) Alternative to #7865 # User-Facing Changes None intended # Tests + Formatting (Ran `cargo +stable clippy --fix --workspace -- -A clippy::all -D clippy::uninlined_format_args` to achieve this. Depends on Rust `1.67`) --- crates/nu-cli/src/completions/completer.rs | 2 +- .../src/completions/directory_completions.rs | 4 +- .../src/completions/dotnu_completions.rs | 2 +- .../src/completions/file_completions.rs | 6 +- crates/nu-cli/src/eval_file.rs | 4 +- crates/nu-cli/src/menus/description_menu.rs | 6 +- crates/nu-cli/src/menus/menu_completions.rs | 2 +- crates/nu-cli/src/prompt.rs | 2 +- crates/nu-cli/src/prompt_update.rs | 3 +- crates/nu-cli/src/reedline_config.rs | 2 +- crates/nu-cli/src/repl.rs | 10 ++-- crates/nu-cli/src/util.rs | 5 +- crates/nu-cli/tests/completions.rs | 4 +- crates/nu-color-config/src/nu_style.rs | 2 +- crates/nu-command/build.rs | 2 +- crates/nu-command/src/bits/rotate_left.rs | 3 +- crates/nu-command/src/bits/rotate_right.rs | 3 +- crates/nu-command/src/bits/shift_left.rs | 8 +-- crates/nu-command/src/bits/shift_right.rs | 8 +-- crates/nu-command/src/charting/histogram.rs | 2 +- crates/nu-command/src/conversions/fmt.rs | 16 +++--- .../src/conversions/into/datetime.rs | 2 +- crates/nu-command/src/conversions/into/int.rs | 3 +- .../nu-command/src/conversions/into/string.rs | 2 +- crates/nu-command/src/core_commands/ast.rs | 2 +- crates/nu-command/src/core_commands/help.rs | 2 +- .../src/database/commands/into_sqlite.rs | 20 +++---- .../nu-command/src/database/values/sqlite.rs | 4 +- crates/nu-command/src/date/format.rs | 2 +- crates/nu-command/src/default_context.rs | 2 +- .../nu-command/src/env/config/config_reset.rs | 4 +- crates/nu-command/src/env/env_command.rs | 2 +- crates/nu-command/src/example_test.rs | 4 +- crates/nu-command/src/filesystem/cd.rs | 13 ++--- crates/nu-command/src/filesystem/cp.rs | 3 +- crates/nu-command/src/filesystem/glob.rs | 2 +- crates/nu-command/src/filesystem/mkdir.rs | 2 +- crates/nu-command/src/filesystem/mv.rs | 11 ++-- crates/nu-command/src/filesystem/open.rs | 4 +- crates/nu-command/src/filesystem/rm.rs | 6 +- crates/nu-command/src/filesystem/save.rs | 2 +- crates/nu-command/src/filesystem/touch.rs | 8 +-- crates/nu-command/src/filesystem/watch.rs | 4 +- crates/nu-command/src/filters/find.rs | 2 +- crates/nu-command/src/filters/flatten.rs | 10 ++-- crates/nu-command/src/filters/headers.rs | 2 +- crates/nu-command/src/filters/rotate.rs | 2 +- crates/nu-command/src/filters/skip/skip_.rs | 2 +- crates/nu-command/src/filters/transpose.rs | 2 +- .../nu-command/src/formats/from/delimited.rs | 2 +- crates/nu-command/src/formats/from/ics.rs | 2 +- crates/nu-command/src/formats/from/ini.rs | 2 +- crates/nu-command/src/formats/from/json.rs | 2 +- crates/nu-command/src/formats/from/ods.rs | 2 +- crates/nu-command/src/formats/from/ssv.rs | 2 +- crates/nu-command/src/formats/from/vcf.rs | 2 +- crates/nu-command/src/formats/from/xlsx.rs | 2 +- crates/nu-command/src/formats/from/yaml.rs | 4 +- crates/nu-command/src/formats/to/nuon.rs | 6 +- crates/nu-command/src/formats/to/text.rs | 10 ++-- crates/nu-command/src/hash/generic_digest.rs | 2 +- crates/nu-command/src/misc/tutor.rs | 4 +- crates/nu-command/src/network/http/get.rs | 31 +++++----- crates/nu-command/src/network/http/post.rs | 29 +++++----- crates/nu-command/src/network/url/join.rs | 22 ++++---- crates/nu-command/src/path/join.rs | 3 +- crates/nu-command/src/platform/ansi/ansi_.rs | 8 +-- crates/nu-command/src/platform/ansi/link.rs | 2 +- crates/nu-command/src/platform/input.rs | 4 +- .../reedline_commands/keybindings_listen.rs | 14 ++--- .../src/strings/encode_decode/base64.rs | 3 +- .../src/strings/encode_decode/encoding.rs | 3 +- .../nu-command/src/strings/format/command.rs | 2 +- crates/nu-command/src/strings/size.rs | 2 +- .../nu-command/src/strings/str_/trim/trim_.rs | 4 +- crates/nu-command/src/system/run_external.rs | 2 +- crates/nu-command/src/system/which_.rs | 2 +- crates/nu-command/src/viewers/griddle.rs | 2 +- crates/nu-command/src/viewers/table.rs | 6 +- crates/nu-command/tests/commands/math/sum.rs | 4 +- .../tests/commands/platform/kill.rs | 2 +- crates/nu-command/tests/commands/roll.rs | 7 +-- crates/nu-command/tests/commands/save.rs | 6 +- .../nu-command/tests/commands/source_env.rs | 7 +-- crates/nu-command/tests/commands/zip.rs | 2 +- .../tests/format_conversions/nuon.rs | 20 +++---- crates/nu-engine/src/documentation.rs | 23 ++++---- crates/nu-engine/src/env.rs | 12 ++-- crates/nu-engine/src/eval.rs | 2 +- crates/nu-explore/src/commands/config.rs | 2 +- crates/nu-explore/src/commands/mod.rs | 2 +- crates/nu-explore/src/nu_common/table.rs | 2 +- crates/nu-explore/src/pager/mod.rs | 13 ++--- crates/nu-explore/src/views/interactive.rs | 8 +-- crates/nu-explore/src/views/record/mod.rs | 8 +-- crates/nu-explore/src/views/util.rs | 2 +- crates/nu-json/src/error.rs | 4 +- crates/nu-json/src/ser.rs | 18 +++--- crates/nu-parser/src/deparse.rs | 6 +- crates/nu-parser/src/eval.rs | 2 +- crates/nu-parser/src/parse_keywords.rs | 6 +- crates/nu-parser/src/parser.rs | 13 ++--- crates/nu-parser/tests/test_parser.rs | 4 +- .../tests/test_parser_unicode_escapes.rs | 8 +-- crates/nu-plugin/src/plugin/declaration.rs | 4 +- crates/nu-plugin/src/plugin/mod.rs | 12 ++-- crates/nu-plugin/src/protocol/mod.rs | 6 +- .../src/protocol/plugin_custom_value.rs | 4 +- crates/nu-pretty-hex/src/pretty_hex.rs | 2 +- crates/nu-protocol/src/ast/cell_path.rs | 2 +- crates/nu-protocol/src/engine/engine_state.rs | 8 +-- crates/nu-protocol/src/shell_error.rs | 7 +-- crates/nu-protocol/src/signature.rs | 2 +- crates/nu-protocol/src/span.rs | 4 +- crates/nu-protocol/src/syntax_shape.rs | 8 +-- crates/nu-protocol/src/ty.rs | 8 +-- crates/nu-protocol/src/value/mod.rs | 56 +++++++++---------- crates/nu-table/examples/table_demo.rs | 4 +- crates/nu-term-grid/examples/grid_demo.rs | 2 +- crates/nu-test-support/src/commands.rs | 2 +- .../src/playground/director.rs | 4 +- .../src/playground/matchers.rs | 9 ++- crates/nu_plugin_example/src/example.rs | 16 +++--- crates/nu_plugin_gstat/src/gstat.rs | 2 +- crates/nu_plugin_inc/src/inc.rs | 2 +- crates/nu_plugin_query/src/query_web.rs | 4 +- crates/nu_plugin_query/src/web_tables.rs | 2 +- src/command.rs | 4 +- src/config_files.rs | 9 +-- src/logger.rs | 2 +- src/test_bins.rs | 20 +++---- src/tests.rs | 20 +++---- src/tests/test_config_path.rs | 4 +- tests/shell/pipeline/commands/external.rs | 4 +- 134 files changed, 386 insertions(+), 431 deletions(-) diff --git a/crates/nu-cli/src/completions/completer.rs b/crates/nu-cli/src/completions/completer.rs index a7cd5096b0..446122133a 100644 --- a/crates/nu-cli/src/completions/completer.rs +++ b/crates/nu-cli/src/completions/completer.rs @@ -104,7 +104,7 @@ impl NuCompleter { return Some(result); } } - Err(err) => println!("failed to eval completer block: {}", err), + Err(err) => println!("failed to eval completer block: {err}"), } None diff --git a/crates/nu-cli/src/completions/directory_completions.rs b/crates/nu-cli/src/completions/directory_completions.rs index 6ec0888d28..36e043b53c 100644 --- a/crates/nu-cli/src/completions/directory_completions.rs +++ b/crates/nu-cli/src/completions/directory_completions.rs @@ -119,7 +119,7 @@ pub fn directory_completion( let mut file_name = entry.file_name().to_string_lossy().into_owned(); if matches(&partial, &file_name, options) { let mut path = if prepend_base_dir(original_input, &base_dir_name) { - format!("{}{}", base_dir_name, file_name) + format!("{base_dir_name}{file_name}") } else { file_name.to_string() }; @@ -135,7 +135,7 @@ pub fn directory_completion( || path.contains(' ') || path.contains('#') { - path = format!("`{}`", path); + path = format!("`{path}`"); } Some((span, path)) diff --git a/crates/nu-cli/src/completions/dotnu_completions.rs b/crates/nu-cli/src/completions/dotnu_completions.rs index 243d07dd9d..c1a5ae9e91 100644 --- a/crates/nu-cli/src/completions/dotnu_completions.rs +++ b/crates/nu-cli/src/completions/dotnu_completions.rs @@ -58,7 +58,7 @@ impl Completer for DotNuCompletion { }; // Check if the base_dir is a folder - if base_dir != format!(".{}", SEP) { + if base_dir != format!(".{SEP}") { // Add the base dir into the directories to be searched search_dirs.push(base_dir.clone()); diff --git a/crates/nu-cli/src/completions/file_completions.rs b/crates/nu-cli/src/completions/file_completions.rs index 4a303bde10..100ee5ca71 100644 --- a/crates/nu-cli/src/completions/file_completions.rs +++ b/crates/nu-cli/src/completions/file_completions.rs @@ -124,7 +124,7 @@ pub fn file_path_completion( let mut file_name = entry.file_name().to_string_lossy().into_owned(); if matches(&partial, &file_name, options) { let mut path = if prepend_base_dir(original_input, &base_dir_name) { - format!("{}{}", base_dir_name, file_name) + format!("{base_dir_name}{file_name}") } else { file_name.to_string() }; @@ -142,7 +142,7 @@ pub fn file_path_completion( || path.contains('(') || path.contains(')') { - path = format!("`{}`", path); + path = format!("`{path}`"); } Some((span, path)) @@ -170,7 +170,7 @@ pub fn matches(partial: &str, from: &str, options: &CompletionOptions) -> bool { /// Returns whether the base_dir should be prepended to the file path pub fn prepend_base_dir(input: &str, base_dir: &str) -> bool { - if base_dir == format!(".{}", SEP) { + if base_dir == format!(".{SEP}") { // if the current base_dir path is the local folder we only add a "./" prefix if the user // input already includes a local folder prefix. let manually_entered = { diff --git a/crates/nu-cli/src/eval_file.rs b/crates/nu-cli/src/eval_file.rs index e37a6869e2..528a41ed4a 100644 --- a/crates/nu-cli/src/eval_file.rs +++ b/crates/nu-cli/src/eval_file.rs @@ -81,7 +81,7 @@ pub fn evaluate_file( report_error( &working_set, &ShellError::FileNotFoundCustom( - format!("The file path '{}' does not have a parent", file_path_str), + format!("The file path '{file_path_str}' does not have a parent"), Span::unknown(), ), ); @@ -193,6 +193,6 @@ fn print_or_exit(pipeline_data: PipelineData, engine_state: &mut EngineState, co } let out = item.into_string("\n", config) + "\n"; - let _ = stdout_write_all_and_flush(out).map_err(|err| eprintln!("{}", err)); + let _ = stdout_write_all_and_flush(out).map_err(|err| eprintln!("{err}")); } } diff --git a/crates/nu-cli/src/menus/description_menu.rs b/crates/nu-cli/src/menus/description_menu.rs index e841735919..5f7434bb0c 100644 --- a/crates/nu-cli/src/menus/description_menu.rs +++ b/crates/nu-cli/src/menus/description_menu.rs @@ -411,10 +411,10 @@ impl DescriptionMenu { RESET ) } else { - format!(" {}\r\n", example) + format!(" {example}\r\n") } } else { - format!(" {}\r\n", example) + format!(" {example}\r\n") } }) .collect(); @@ -429,7 +429,7 @@ impl DescriptionMenu { examples, ) } else { - format!("\r\n\r\nExamples:\r\n{}", examples,) + format!("\r\n\r\nExamples:\r\n{examples}",) } } } diff --git a/crates/nu-cli/src/menus/menu_completions.rs b/crates/nu-cli/src/menus/menu_completions.rs index 8f904b3289..a40750e5fb 100644 --- a/crates/nu-cli/src/menus/menu_completions.rs +++ b/crates/nu-cli/src/menus/menu_completions.rs @@ -154,7 +154,7 @@ fn convert_to_suggestions( .flat_map(|val| convert_to_suggestions(val, line, pos, only_buffer_difference)) .collect(), _ => vec![Suggestion { - value: format!("Not a record: {:?}", value), + value: format!("Not a record: {value:?}"), description: None, extra: None, span: reedline::Span { diff --git a/crates/nu-cli/src/prompt.rs b/crates/nu-cli/src/prompt.rs index 4abc3ff74f..f6c9f81853 100644 --- a/crates/nu-cli/src/prompt.rs +++ b/crates/nu-cli/src/prompt.rs @@ -91,7 +91,7 @@ impl NushellPrompt { } fn default_wrapped_custom_string(&self, str: String) -> String { - format!("({})", str) + format!("({str})") } } diff --git a/crates/nu-cli/src/prompt_update.rs b/crates/nu-cli/src/prompt_update.rs index 1b98f4c8ca..ff8fef1e1a 100644 --- a/crates/nu-cli/src/prompt_update.rs +++ b/crates/nu-cli/src/prompt_update.rs @@ -106,8 +106,7 @@ pub(crate) fn update_prompt<'prompt>( let left_prompt_string = if config.shell_integration { if let Some(prompt_string) = left_prompt_string { Some(format!( - "{}{}{}", - PRE_PROMPT_MARKER, prompt_string, POST_PROMPT_MARKER + "{PRE_PROMPT_MARKER}{prompt_string}{POST_PROMPT_MARKER}" )) } else { left_prompt_string diff --git a/crates/nu-cli/src/reedline_config.rs b/crates/nu-cli/src/reedline_config.rs index 4b5dd615fb..1746a1e1ee 100644 --- a/crates/nu-cli/src/reedline_config.rs +++ b/crates/nu-cli/src/reedline_config.rs @@ -683,7 +683,7 @@ fn add_parsed_keybinding( .filter(|num| matches!(num, 1..=20)) .ok_or(ShellError::UnsupportedConfigValue( "(f1|f2|...|f20)".to_string(), - format!("unknown function key: {}", c), + format!("unknown function key: {c}"), keybinding.keycode.span()?, ))?; KeyCode::F(fn_num) diff --git a/crates/nu-cli/src/repl.rs b/crates/nu-cli/src/repl.rs index 360630f768..5ee2d44de2 100644 --- a/crates/nu-cli/src/repl.rs +++ b/crates/nu-cli/src/repl.rs @@ -125,7 +125,7 @@ pub fn evaluate_repl( if show_banner { let banner = get_banner(engine_state, stack); if use_ansi { - println!("{}", banner); + println!("{banner}"); } else { println!("{}", nu_utils::strip_ansi_string_likely(banner)); } @@ -143,7 +143,7 @@ pub fn evaluate_repl( engine_state, stack, s.item.as_bytes(), - &format!("entry #{}", entry_num), + &format!("entry #{entry_num}"), PipelineData::empty(), ); engine_state.merge_env(stack, get_guaranteed_cwd(engine_state, stack))?; @@ -470,7 +470,7 @@ pub fn evaluate_repl( engine_state, stack, s.as_bytes(), - &format!("entry #{}", entry_num), + &format!("entry #{entry_num}"), PipelineData::empty(), ); } @@ -528,7 +528,7 @@ pub fn evaluate_repl( // ESC]0;stringBEL -- Set icon name and window title to string // ESC]1;stringBEL -- Set icon name to string // ESC]2;stringBEL -- Set window title to string - run_ansi_sequence(&format!("\x1b]2;{}\x07", maybe_abbrev_path))?; + run_ansi_sequence(&format!("\x1b]2;{maybe_abbrev_path}\x07"))?; } run_ansi_sequence(RESET_APPLICATION_MODE)?; } @@ -568,7 +568,7 @@ pub fn evaluate_repl( Err(err) => { let message = err.to_string(); if !message.contains("duration") { - eprintln!("Error: {:?}", err); + eprintln!("Error: {err:?}"); // TODO: Identify possible error cases where a hard failure is preferable // Ignoring and reporting could hide bigger problems // e.g. https://github.com/nushell/nushell/issues/6452 diff --git a/crates/nu-cli/src/util.rs b/crates/nu-cli/src/util.rs index d1560a8453..1f57eac31e 100644 --- a/crates/nu-cli/src/util.rs +++ b/crates/nu-cli/src/util.rs @@ -44,7 +44,7 @@ fn gather_env_vars( report_error( &working_set, &ShellError::GenericError( - format!("Environment variable was not captured: {}", env_str), + format!("Environment variable was not captured: {env_str}"), "".to_string(), None, Some(msg.into()), @@ -80,8 +80,7 @@ fn gather_env_vars( "".to_string(), None, Some(format!( - "Retrieving current directory failed: {:?} not a valid utf-8 path", - init_cwd + "Retrieving current directory failed: {init_cwd:?} not a valid utf-8 path" )), Vec::new(), ), diff --git a/crates/nu-cli/tests/completions.rs b/crates/nu-cli/tests/completions.rs index 4d646cbc95..219015f54e 100644 --- a/crates/nu-cli/tests/completions.rs +++ b/crates/nu-cli/tests/completions.rs @@ -173,7 +173,7 @@ fn file_completions() { let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack); // Test completions for the current folder - let target_dir = format!("cp {}", dir_str); + let target_dir = format!("cp {dir_str}"); let suggestions = completer.complete(&target_dir, target_dir.len()); // Create the expected values @@ -494,7 +494,7 @@ fn folder_with_directorycompletions() { let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack); // Test completions for the current folder - let target_dir = format!("cd {}", dir_str); + let target_dir = format!("cd {dir_str}"); let suggestions = completer.complete(&target_dir, target_dir.len()); // Create the expected values diff --git a/crates/nu-color-config/src/nu_style.rs b/crates/nu-color-config/src/nu_style.rs index b11a4184e4..0d85726037 100644 --- a/crates/nu-color-config/src/nu_style.rs +++ b/crates/nu-color-config/src/nu_style.rs @@ -65,7 +65,7 @@ fn color_to_string(color: Color) -> Option { Color::White => Some(String::from("white")), Color::LightGray => Some(String::from("light_gray")), Color::Default => Some(String::from("default")), - Color::Rgb(r, g, b) => Some(format!("#{:X}{:X}{:X}", r, g, b)), + Color::Rgb(r, g, b) => Some(format!("#{r:X}{g:X}{b:X}")), Color::Fixed(_) => None, } } diff --git a/crates/nu-command/build.rs b/crates/nu-command/build.rs index 7ad06cc6f1..0d49abde0b 100644 --- a/crates/nu-command/build.rs +++ b/crates/nu-command/build.rs @@ -4,7 +4,7 @@ fn main() -> shadow_rs::SdResult<()> { // Look up the current Git commit ourselves instead of relying on shadow_rs, // because shadow_rs does it in a really slow-to-compile way (it builds libgit2) let hash = get_git_hash().unwrap_or_default(); - println!("cargo:rustc-env=NU_COMMIT_HASH={}", hash); + println!("cargo:rustc-env=NU_COMMIT_HASH={hash}"); shadow_rs::new() } diff --git a/crates/nu-command/src/bits/rotate_left.rs b/crates/nu-command/src/bits/rotate_left.rs index 5860049100..146133b4ca 100644 --- a/crates/nu-command/src/bits/rotate_left.rs +++ b/crates/nu-command/src/bits/rotate_left.rs @@ -106,8 +106,7 @@ where error: ShellError::GenericError( "Rotate left result beyond the range of 64 bit signed number".to_string(), format!( - "{} of the specified number of bytes rotate left {} bits exceed limit", - val, bits + "{val} of the specified number of bytes rotate left {bits} bits exceed limit" ), Some(span), None, diff --git a/crates/nu-command/src/bits/rotate_right.rs b/crates/nu-command/src/bits/rotate_right.rs index 5ac5a99e9f..d773004734 100644 --- a/crates/nu-command/src/bits/rotate_right.rs +++ b/crates/nu-command/src/bits/rotate_right.rs @@ -110,8 +110,7 @@ where error: ShellError::GenericError( "Rotate right result beyond the range of 64 bit signed number".to_string(), format!( - "{} of the specified number of bytes rotate right {} bits exceed limit", - val, bits + "{val} of the specified number of bytes rotate right {bits} bits exceed limit" ), Some(span), None, diff --git a/crates/nu-command/src/bits/shift_left.rs b/crates/nu-command/src/bits/shift_left.rs index 03f1ac0060..ac467e740b 100644 --- a/crates/nu-command/src/bits/shift_left.rs +++ b/crates/nu-command/src/bits/shift_left.rs @@ -118,8 +118,7 @@ where error: ShellError::GenericError( "Shift left result beyond the range of 64 bit signed number".to_string(), format!( - "{} of the specified number of bytes shift left {} bits exceed limit", - val, bits + "{val} of the specified number of bytes shift left {bits} bits exceed limit" ), Some(span), None, @@ -131,10 +130,7 @@ where None => Value::Error { error: ShellError::GenericError( "Shift left failed".to_string(), - format!( - "{} shift left {} bits failed, you may shift too many bits", - val, bits - ), + format!("{val} shift left {bits} bits failed, you may shift too many bits"), Some(span), None, Vec::new(), diff --git a/crates/nu-command/src/bits/shift_right.rs b/crates/nu-command/src/bits/shift_right.rs index 77c38f8bc4..e31e53507c 100644 --- a/crates/nu-command/src/bits/shift_right.rs +++ b/crates/nu-command/src/bits/shift_right.rs @@ -108,8 +108,7 @@ where error: ShellError::GenericError( "Shift right result beyond the range of 64 bit signed number".to_string(), format!( - "{} of the specified number of bytes shift right {} bits exceed limit", - val, bits + "{val} of the specified number of bytes shift right {bits} bits exceed limit" ), Some(span), None, @@ -121,10 +120,7 @@ where None => Value::Error { error: ShellError::GenericError( "Shift right failed".to_string(), - format!( - "{} shift right {} bits failed, you may shift too many bits", - val, bits - ), + format!("{val} shift right {bits} bits failed, you may shift too many bits"), Some(span), None, Vec::new(), diff --git a/crates/nu-command/src/charting/histogram.rs b/crates/nu-command/src/charting/histogram.rs index 56c859fdd8..da33526cc3 100644 --- a/crates/nu-command/src/charting/histogram.rs +++ b/crates/nu-command/src/charting/histogram.rs @@ -166,7 +166,7 @@ fn run_histogram( ShellError::UnsupportedInput( "Since --column-name was not provided, only lists of hashable values are supported.".to_string(), format!( - "input type: {:?}", t + "input type: {t:?}" ), head_span, span, diff --git a/crates/nu-command/src/conversions/fmt.rs b/crates/nu-command/src/conversions/fmt.rs index 42d8ea14df..ed033a4f21 100644 --- a/crates/nu-command/src/conversions/fmt.rs +++ b/crates/nu-command/src/conversions/fmt.rs @@ -103,31 +103,31 @@ fn fmt_it(num: i64, span: Span) -> Value { let mut vals = vec![]; cols.push("binary".into()); - vals.push(Value::string(format!("{:#b}", num), span)); + vals.push(Value::string(format!("{num:#b}"), span)); cols.push("debug".into()); - vals.push(Value::string(format!("{:#?}", num), span)); + vals.push(Value::string(format!("{num:#?}"), span)); cols.push("display".into()); - vals.push(Value::string(format!("{}", num), span)); + vals.push(Value::string(format!("{num}"), span)); cols.push("lowerexp".into()); - vals.push(Value::string(format!("{:#e}", num), span)); + vals.push(Value::string(format!("{num:#e}"), span)); cols.push("lowerhex".into()); - vals.push(Value::string(format!("{:#x}", num), span)); + vals.push(Value::string(format!("{num:#x}"), span)); cols.push("octal".into()); - vals.push(Value::string(format!("{:#o}", num), span)); + vals.push(Value::string(format!("{num:#o}"), span)); // cols.push("pointer".into()); // vals.push(Value::string(format!("{:#p}", &num), span)); cols.push("upperexp".into()); - vals.push(Value::string(format!("{:#E}", num), span)); + vals.push(Value::string(format!("{num:#E}"), span)); cols.push("upperhex".into()); - vals.push(Value::string(format!("{:#X}", num), span)); + vals.push(Value::string(format!("{num:#X}"), span)); Value::Record { cols, vals, span } } diff --git a/crates/nu-command/src/conversions/into/datetime.rs b/crates/nu-command/src/conversions/into/datetime.rs index 7f8f044369..dec6737f6d 100644 --- a/crates/nu-command/src/conversions/into/datetime.rs +++ b/crates/nu-command/src/conversions/into/datetime.rs @@ -232,7 +232,7 @@ fn action(input: &Value, args: &Arguments, head: Span) -> Value { return Value::Error { error: ShellError::UnsupportedInput( "timestamp is out of range; it should between -8e+12 and 8e+12".to_string(), - format!("timestamp is {:?}", ts), + format!("timestamp is {ts:?}"), head, // Again, can safely unwrap this from here on input.expect_span(), diff --git a/crates/nu-command/src/conversions/into/int.rs b/crates/nu-command/src/conversions/into/int.rs index a4b549790f..8013e1ed05 100644 --- a/crates/nu-command/src/conversions/into/int.rs +++ b/crates/nu-command/src/conversions/into/int.rs @@ -367,8 +367,7 @@ fn int_from_string(a_string: &str, span: Span) -> Result { "string".to_string(), span, Some(format!( - r#"string "{}" does not represent a valid integer"#, - trimmed + r#"string "{trimmed}" does not represent a valid integer"# )), )), }, diff --git a/crates/nu-command/src/conversions/into/string.rs b/crates/nu-command/src/conversions/into/string.rs index 2d058e4ca3..146f05e273 100644 --- a/crates/nu-command/src/conversions/into/string.rs +++ b/crates/nu-command/src/conversions/into/string.rs @@ -206,7 +206,7 @@ fn action(input: &Value, args: &Arguments, span: Span) -> Value { if decimals { let decimal_value = digits.unwrap_or(2) as usize; Value::String { - val: format!("{:.*}", decimal_value, val), + val: format!("{val:.decimal_value$}"), span, } } else { diff --git a/crates/nu-command/src/core_commands/ast.rs b/crates/nu-command/src/core_commands/ast.rs index e06fdf6e20..854ac11513 100644 --- a/crates/nu-command/src/core_commands/ast.rs +++ b/crates/nu-command/src/core_commands/ast.rs @@ -41,7 +41,7 @@ impl Command for Ast { let mut working_set = StateWorkingSet::new(engine_state); let (output, err) = parse(&mut working_set, None, pipeline.item.as_bytes(), false, &[]); - eprintln!("output: {:#?}\nerror: {:#?}", output, err); + eprintln!("output: {output:#?}\nerror: {err:#?}"); Ok(PipelineData::empty()) } diff --git a/crates/nu-command/src/core_commands/help.rs b/crates/nu-command/src/core_commands/help.rs index 74d8de92d4..f1a487d163 100644 --- a/crates/nu-command/src/core_commands/help.rs +++ b/crates/nu-command/src/core_commands/help.rs @@ -195,7 +195,7 @@ pub fn highlight_search_string( needle: &str, string_style: &Style, ) -> Result { - let regex_string = format!("(?i){}", needle); + let regex_string = format!("(?i){needle}"); let regex = match Regex::new(®ex_string) { Ok(regex) => regex, Err(err) => { diff --git a/crates/nu-command/src/database/commands/into_sqlite.rs b/crates/nu-command/src/database/commands/into_sqlite.rs index 7a97184da0..416cb36773 100644 --- a/crates/nu-command/src/database/commands/into_sqlite.rs +++ b/crates/nu-command/src/database/commands/into_sqlite.rs @@ -117,7 +117,7 @@ fn action( let table_columns_creation = columns .iter() - .map(|(name, sql_type)| format!("{} {}", name, sql_type)) + .map(|(name, sql_type)| format!("{name} {sql_type}")) .join(","); // get the values @@ -156,10 +156,8 @@ fn action( let conn = open_sqlite_db(Path::new(&file.item), file.span)?; // create a string for sql table creation - let create_statement = format!( - "CREATE TABLE IF NOT EXISTS {} ({})", - table_name, table_columns_creation - ); + let create_statement = + format!("CREATE TABLE IF NOT EXISTS {table_name} ({table_columns_creation})"); // prepare the string as a sqlite statement let mut stmt = conn.prepare(&create_statement).map_err(|e| { @@ -191,7 +189,7 @@ fn action( // ('dd', 'ee', 'ff') // create the string for inserting data into the table - let insert_statement = format!("INSERT INTO {} VALUES {}", table_name, table_values); + let insert_statement = format!("INSERT INTO {table_name} VALUES {table_values}"); // prepare the string as a sqlite statement let mut stmt = conn.prepare(&insert_statement).map_err(|e| { @@ -264,13 +262,13 @@ fn nu_value_to_string(value: Value, separator: &str) -> String { .join(separator), Value::LazyRecord { val, .. } => match val.collect() { Ok(val) => nu_value_to_string(val, separator), - Err(error) => format!("{:?}", error), + Err(error) => format!("{error:?}"), }, - Value::Block { val, .. } => format!("", val), - Value::Closure { val, .. } => format!("", val), + Value::Block { val, .. } => format!(""), + Value::Closure { val, .. } => format!(""), Value::Nothing { .. } => String::new(), - Value::Error { error } => format!("{:?}", error), - Value::Binary { val, .. } => format!("{:?}", val), + Value::Error { error } => format!("{error:?}"), + Value::Binary { val, .. } => format!("{val:?}"), Value::CellPath { val, .. } => val.into_string(), Value::CustomValue { val, .. } => val.value_string(), } diff --git a/crates/nu-command/src/database/values/sqlite.rs b/crates/nu-command/src/database/values/sqlite.rs index 47c6c4344b..50d9482e01 100644 --- a/crates/nu-command/src/database/values/sqlite.rs +++ b/crates/nu-command/src/database/values/sqlite.rs @@ -364,7 +364,7 @@ fn read_single_table( call_span: Span, ctrlc: Option>, ) -> Result { - let stmt = conn.prepare(&format!("SELECT * FROM {}", table_name))?; + let stmt = conn.prepare(&format!("SELECT * FROM {table_name}"))?; prepared_statement_to_nu_list(stmt, call_span, ctrlc) } @@ -426,7 +426,7 @@ fn read_entire_sqlite_db( let table_name: String = row?; table_names.push(table_name.clone()); - let table_stmt = conn.prepare(&format!("select * from [{}]", table_name))?; + let table_stmt = conn.prepare(&format!("select * from [{table_name}]"))?; let rows = prepared_statement_to_nu_list(table_stmt, call_span, ctrlc.clone())?; tables.push(rows); } diff --git a/crates/nu-command/src/date/format.rs b/crates/nu-command/src/date/format.rs index 16b3470ea0..9863baf9da 100644 --- a/crates/nu-command/src/date/format.rs +++ b/crates/nu-command/src/date/format.rs @@ -126,7 +126,7 @@ where .unwrap_or(Locale::en_US); let format = date_time.format_localized(formatter, locale); - match formatter_buf.write_fmt(format_args!("{}", format)) { + match formatter_buf.write_fmt(format_args!("{format}")) { Ok(_) => Value::String { val: formatter_buf, span, diff --git a/crates/nu-command/src/default_context.rs b/crates/nu-command/src/default_context.rs index fc2794d035..37e343ac08 100644 --- a/crates/nu-command/src/default_context.rs +++ b/crates/nu-command/src/default_context.rs @@ -495,7 +495,7 @@ pub fn create_default_context() -> EngineState { }; if let Err(err) = engine_state.merge_delta(delta) { - eprintln!("Error creating default context: {:?}", err); + eprintln!("Error creating default context: {err:?}"); } engine_state diff --git a/crates/nu-command/src/env/config/config_reset.rs b/crates/nu-command/src/env/config/config_reset.rs index b901ce1604..c0bbb41314 100644 --- a/crates/nu-command/src/env/config/config_reset.rs +++ b/crates/nu-command/src/env/config/config_reset.rs @@ -79,7 +79,7 @@ impl Command for ConfigReset { } } if let Ok(mut file) = std::fs::File::create(nu_config) { - if writeln!(&mut file, "{}", config_file).is_err() { + if writeln!(&mut file, "{config_file}").is_err() { return Err(ShellError::FileNotFoundCustom( "config.nu could not be written to".into(), span, @@ -102,7 +102,7 @@ impl Command for ConfigReset { } } if let Ok(mut file) = std::fs::File::create(env_config) { - if writeln!(&mut file, "{}", config_file).is_err() { + if writeln!(&mut file, "{config_file}").is_err() { return Err(ShellError::FileNotFoundCustom( "env.nu could not be written to".into(), span, diff --git a/crates/nu-command/src/env/env_command.rs b/crates/nu-command/src/env/env_command.rs index b545a02b27..3f7d4dd3f6 100644 --- a/crates/nu-command/src/env/env_command.rs +++ b/crates/nu-command/src/env/env_command.rs @@ -54,7 +54,7 @@ impl Command for Env { vals.push(Value::string(name, span)); cols.push("type".into()); - vals.push(Value::string(format!("{}", val_type), span)); + vals.push(Value::string(format!("{val_type}"), span)); cols.push("value".into()); vals.push(val); diff --git a/crates/nu-command/src/example_test.rs b/crates/nu-command/src/example_test.rs index 2e816f42d9..81f0919182 100644 --- a/crates/nu-command/src/example_test.rs +++ b/crates/nu-command/src/example_test.rs @@ -251,7 +251,7 @@ mod test_examples { {:?}", declared_type_transformations .difference(&witnessed_type_transformations) - .map(|(s1, s2)| format!("{} -> {}", s1, s2)) + .map(|(s1, s2)| format!("{s1} -> {s2}")) .join(", ") ); } @@ -273,7 +273,7 @@ mod test_examples { nu_parser::parse(&mut working_set, None, contents.as_bytes(), false, &[]); if let Some(err) = err { - panic!("test parse error in `{}`: {:?}", contents, err) + panic!("test parse error in `{contents}`: {err:?}") } (output, working_set.render()) diff --git a/crates/nu-command/src/filesystem/cd.rs b/crates/nu-command/src/filesystem/cd.rs index 47d3acea9c..92fc2209a1 100644 --- a/crates/nu-command/src/filesystem/cd.rs +++ b/crates/nu-command/src/filesystem/cd.rs @@ -93,14 +93,14 @@ impl Command for Cd { Err(e) => { return Err(ShellError::DirectoryNotFound( v.span, - Some(format!("IO Error: {:?}", e)), + Some(format!("IO Error: {e:?}")), )) } } } else { return Err(ShellError::DirectoryNotFound( v.span, - Some(format!("IO Error: {:?}", e1)), + Some(format!("IO Error: {e1:?}")), )); } } @@ -123,7 +123,7 @@ impl Command for Cd { Err(e) => { return Err(ShellError::DirectoryNotFound( v.span, - Some(format!("IO Error: {:?}", e)), + Some(format!("IO Error: {e:?}")), )) } }; @@ -142,14 +142,14 @@ impl Command for Cd { Err(e) => { return Err(ShellError::DirectoryNotFound( v.span, - Some(format!("IO Error: {:?}", e)), + Some(format!("IO Error: {e:?}")), )) } } } else { return Err(ShellError::DirectoryNotFound( v.span, - Some(format!("IO Error: {:?}", e1)), + Some(format!("IO Error: {e1:?}")), )); } } @@ -197,8 +197,7 @@ impl Command for Cd { Ok(PipelineData::empty()) } PermissionResult::PermissionDenied(reason) => Err(ShellError::IOError(format!( - "Cannot change directory to {}: {}", - path, reason + "Cannot change directory to {path}: {reason}" ))), } } diff --git a/crates/nu-command/src/filesystem/cp.rs b/crates/nu-command/src/filesystem/cp.rs index 27a3b85c89..687b5f278c 100644 --- a/crates/nu-command/src/filesystem/cp.rs +++ b/crates/nu-command/src/filesystem/cp.rs @@ -168,8 +168,7 @@ impl Command for Cp { canonicalize_with(dst.as_path(), ¤t_dir_path).unwrap_or(dst); let res = if src == dst { let message = format!( - "src {:?} and dst {:?} are identical(not copied)", - source, destination + "src {source:?} and dst {destination:?} are identical(not copied)" ); return Err(ShellError::GenericError( diff --git a/crates/nu-command/src/filesystem/glob.rs b/crates/nu-command/src/filesystem/glob.rs index 29f6bb6823..20245f0bb4 100644 --- a/crates/nu-command/src/filesystem/glob.rs +++ b/crates/nu-command/src/filesystem/glob.rs @@ -145,7 +145,7 @@ impl Command for Glob { Err(e) => { return Err(ShellError::GenericError( "error with glob pattern".to_string(), - format!("{}", e), + format!("{e}"), Some(glob_pattern.span), None, Vec::new(), diff --git a/crates/nu-command/src/filesystem/mkdir.rs b/crates/nu-command/src/filesystem/mkdir.rs index 07b7e199da..c66bd4fefd 100644 --- a/crates/nu-command/src/filesystem/mkdir.rs +++ b/crates/nu-command/src/filesystem/mkdir.rs @@ -70,7 +70,7 @@ impl Command for Mkdir { if let Err(reason) = dir_res { return Err(ShellError::CreateNotPossible( - format!("failed to create directory: {}", reason), + format!("failed to create directory: {reason}"), call.positional_nth(i) .expect("already checked through directories") .span, diff --git a/crates/nu-command/src/filesystem/mv.rs b/crates/nu-command/src/filesystem/mv.rs index 1d621c4999..e0bf407473 100644 --- a/crates/nu-command/src/filesystem/mv.rs +++ b/crates/nu-command/src/filesystem/mv.rs @@ -290,7 +290,7 @@ fn move_file( ); if let Err(e) = interaction { return Err(ShellError::GenericError( - format!("Error during interaction: {:}", e), + format!("Error during interaction: {e:}"), "could not move".into(), None, None, @@ -325,10 +325,10 @@ fn move_item(from: &Path, from_span: Span, to: &Path) -> Result<(), ShellError> Err(e) => { let error_kind = match e.kind { fs_extra::error::ErrorKind::Io(io) => { - format!("I/O error: {}", io) + format!("I/O error: {io}") } fs_extra::error::ErrorKind::StripPrefix(sp) => { - format!("Strip prefix error: {}", sp) + format!("Strip prefix error: {sp}") } fs_extra::error::ErrorKind::OsString(os) => { format!("OsString error: {:?}", os.to_str()) @@ -336,10 +336,7 @@ fn move_item(from: &Path, from_span: Span, to: &Path) -> Result<(), ShellError> _ => e.to_string(), }; Err(ShellError::GenericError( - format!( - "Could not move {:?} to {:?}. Error Kind: {}", - from, to, error_kind - ), + format!("Could not move {from:?} to {to:?}. Error Kind: {error_kind}"), "could not move".into(), Some(from_span), None, diff --git a/crates/nu-command/src/filesystem/open.rs b/crates/nu-command/src/filesystem/open.rs index 8cb7e65ece..9c230cdb44 100644 --- a/crates/nu-command/src/filesystem/open.rs +++ b/crates/nu-command/src/filesystem/open.rs @@ -156,7 +156,7 @@ impl Command for Open { }; if let Some(ext) = ext { - match engine_state.find_decl(format!("from {}", ext).as_bytes(), &[]) { + match engine_state.find_decl(format!("from {ext}").as_bytes(), &[]) { Some(converter_id) => { let decl = engine_state.get_decl(converter_id); if let Some(block_id) = decl.get_block_id() { @@ -167,7 +167,7 @@ impl Command for Open { } .map_err(|inner| { ShellError::GenericError( - format!("Error while parsing as {}", ext), + format!("Error while parsing as {ext}"), format!("Could not parse '{}' with `from {}`", path.display(), ext), Some(arg_span), Some(format!("Check out `help from {}` or `help from` for more options or open raw data with `open --raw '{}'`", ext, path.display())), diff --git a/crates/nu-command/src/filesystem/rm.rs b/crates/nu-command/src/filesystem/rm.rs index b1feefb8d6..76c51fe809 100644 --- a/crates/nu-command/src/filesystem/rm.rs +++ b/crates/nu-command/src/filesystem/rm.rs @@ -318,7 +318,7 @@ fn rm( ); if let Err(e) = interaction { return Err(ShellError::GenericError( - format!("Error during interaction: {:}", e), + format!("Error during interaction: {e:}"), "could not move".into(), None, None, @@ -375,7 +375,7 @@ fn rm( Ok(()) } else if trash || (rm_always_trash && !permanent) { trash::delete(&f).map_err(|e: trash::Error| { - Error::new(ErrorKind::Other, format!("{:?}\nTry '--trash' flag", e)) + Error::new(ErrorKind::Other, format!("{e:?}\nTry '--trash' flag")) }) } else if metadata.is_file() || is_socket || is_fifo { std::fs::remove_file(&f) @@ -403,7 +403,7 @@ fn rm( } if let Err(e) = result { - let msg = format!("Could not delete because: {:}", e); + let msg = format!("Could not delete because: {e:}"); Value::Error { error: ShellError::GenericError( msg, diff --git a/crates/nu-command/src/filesystem/save.rs b/crates/nu-command/src/filesystem/save.rs index af57d87abb..46fed55f00 100644 --- a/crates/nu-command/src/filesystem/save.rs +++ b/crates/nu-command/src/filesystem/save.rs @@ -215,7 +215,7 @@ fn convert_to_extension( input: PipelineData, span: Span, ) -> Result, ShellError> { - let converter = engine_state.find_decl(format!("to {}", extension).as_bytes(), &[]); + let converter = engine_state.find_decl(format!("to {extension}").as_bytes(), &[]); let output = match converter { Some(converter_id) => { diff --git a/crates/nu-command/src/filesystem/touch.rs b/crates/nu-command/src/filesystem/touch.rs index 0aca3a35f4..a8e8e17f6a 100644 --- a/crates/nu-command/src/filesystem/touch.rs +++ b/crates/nu-command/src/filesystem/touch.rs @@ -137,7 +137,7 @@ impl Command for Touch { if let Err(err) = OpenOptions::new().write(true).create(true).open(&item) { return Err(ShellError::CreateNotPossible( - format!("Failed to create file: {}", err), + format!("Failed to create file: {err}"), call.positional_nth(index) .expect("already checked positional") .span, @@ -151,7 +151,7 @@ impl Command for Touch { FileTime::from_system_time(date.expect("should be a valid date").into()), ) { return Err(ShellError::ChangeModifiedTimeNotPossible( - format!("Failed to change the modified time: {}", err), + format!("Failed to change the modified time: {err}"), call.positional_nth(index) .expect("already checked positional") .span, @@ -170,7 +170,7 @@ impl Command for Touch { ), ) { return Err(ShellError::ChangeAccessTimeNotPossible( - format!("Failed to change the access time: {}", err), + format!("Failed to change the access time: {err}"), call.positional_nth(index) .expect("already checked positional") .span, @@ -183,7 +183,7 @@ impl Command for Touch { FileTime::from_system_time(date.expect("should be a valid date").into()), ) { return Err(ShellError::ChangeAccessTimeNotPossible( - format!("Failed to change the access time: {}", err), + format!("Failed to change the access time: {err}"), call.positional_nth(index) .expect("already checked positional") .span, diff --git a/crates/nu-command/src/filesystem/watch.rs b/crates/nu-command/src/filesystem/watch.rs index b1cbe97b1a..ed9edffa0f 100644 --- a/crates/nu-command/src/filesystem/watch.rs +++ b/crates/nu-command/src/filesystem/watch.rs @@ -79,7 +79,7 @@ impl Command for Watch { Err(e) => { return Err(ShellError::DirectoryNotFound( path_arg.span, - Some(format!("IO Error: {:?}", e)), + Some(format!("IO Error: {e:?}")), )) } }; @@ -227,7 +227,7 @@ impl Command for Watch { match rx.recv_timeout(CHECK_CTRL_C_FREQUENCY) { Ok(event) => { if verbose { - eprintln!("{:?}", event); + eprintln!("{event:?}"); } let handler_result = match event { DebouncedEvent::Create(path) => event_handler("Create", path, None), diff --git a/crates/nu-command/src/filters/find.rs b/crates/nu-command/src/filters/find.rs index 542aacd545..daf6ee8d28 100644 --- a/crates/nu-command/src/filters/find.rs +++ b/crates/nu-command/src/filters/find.rs @@ -186,7 +186,7 @@ fn find_with_regex( let regex = flags.to_string() + regex.as_str(); let re = Regex::new(regex.as_str()) - .map_err(|e| ShellError::TypeMismatch(format!("invalid regex: {}", e), span))?; + .map_err(|e| ShellError::TypeMismatch(format!("invalid regex: {e}"), span))?; input.filter( move |value| match value { diff --git a/crates/nu-command/src/filters/flatten.rs b/crates/nu-command/src/filters/flatten.rs index 060c8b74de..be9a5426a3 100644 --- a/crates/nu-command/src/filters/flatten.rs +++ b/crates/nu-command/src/filters/flatten.rs @@ -213,7 +213,7 @@ fn flat_value(columns: &[CellPath], item: &Value, _name_tag: Span, all: bool) -> cols.iter().enumerate().for_each(|(idx, inner_record_col)| { if out.contains_key(inner_record_col) { out.insert( - format!("{}_{}", column, inner_record_col), + format!("{column}_{inner_record_col}"), vals[idx].clone(), ); } else { @@ -221,7 +221,7 @@ fn flat_value(columns: &[CellPath], item: &Value, _name_tag: Span, all: bool) -> } }) } else if out.contains_key(column) { - out.insert(format!("{}_{}", column, column), value.clone()); + out.insert(format!("{column}_{column}"), value.clone()); } else { out.insert(column.to_string(), value.clone()); } @@ -261,7 +261,7 @@ fn flat_value(columns: &[CellPath], item: &Value, _name_tag: Span, all: bool) -> parent_column_index: column_index, }); } else if out.contains_key(column) { - out.insert(format!("{}_{}", column, column), value.clone()); + out.insert(format!("{column}_{column}"), value.clone()); } else { out.insert(column.to_string(), value.clone()); } @@ -358,7 +358,7 @@ fn flat_value(columns: &[CellPath], item: &Value, _name_tag: Span, all: bool) -> if index == parent_column_index { for (col, val) in inner_cols.iter().zip(inner_vals.iter()) { if record_cols.contains(col) { - record_cols.push(format!("{}_{}", parent_column_name, col)); + record_cols.push(format!("{parent_column_name}_{col}")); } else { record_cols.push(col.to_string()); } @@ -375,7 +375,7 @@ fn flat_value(columns: &[CellPath], item: &Value, _name_tag: Span, all: bool) -> if index == parent_column_index { for (col, val) in inner_cols.iter().zip(inner_vals.iter()) { if record_cols.contains(col) { - record_cols.push(format!("{}_{}", parent_column_name, col)); + record_cols.push(format!("{parent_column_name}_{col}")); } else { record_cols.push(col.to_string()); } diff --git a/crates/nu-command/src/filters/headers.rs b/crates/nu-command/src/filters/headers.rs index 40f1ef16d9..52306deb5d 100644 --- a/crates/nu-command/src/filters/headers.rs +++ b/crates/nu-command/src/filters/headers.rs @@ -151,7 +151,7 @@ fn extract_headers(value: &Value, config: &Config) -> Result, ShellE .map(|(idx, value)| { let col = value.into_string("", config); if col.is_empty() { - format!("column{}", idx) + format!("column{idx}") } else { col } diff --git a/crates/nu-command/src/filters/rotate.rs b/crates/nu-command/src/filters/rotate.rs index 73134a45ca..a4dace7702 100644 --- a/crates/nu-command/src/filters/rotate.rs +++ b/crates/nu-command/src/filters/rotate.rs @@ -269,7 +269,7 @@ pub fn rotate( let mut new_column_names = { let mut res = vec![]; for idx in 0..(*total_rows + 1) { - res.push(format!("column{}", idx)); + res.push(format!("column{idx}")); } res.to_vec() }; diff --git a/crates/nu-command/src/filters/skip/skip_.rs b/crates/nu-command/src/filters/skip/skip_.rs index 1976aa9245..49067c06f6 100644 --- a/crates/nu-command/src/filters/skip/skip_.rs +++ b/crates/nu-command/src/filters/skip/skip_.rs @@ -80,7 +80,7 @@ impl Command for Skip { let n: usize = match n { Some(Value::Int { val, span }) => val.try_into().map_err(|err| { ShellError::TypeMismatch( - format!("Could not convert {} to unsigned integer: {}", val, err), + format!("Could not convert {val} to unsigned integer: {err}"), span, ) })?, diff --git a/crates/nu-command/src/filters/transpose.rs b/crates/nu-command/src/filters/transpose.rs index bd7104c7ea..a20b0ffc44 100644 --- a/crates/nu-command/src/filters/transpose.rs +++ b/crates/nu-command/src/filters/transpose.rs @@ -231,7 +231,7 @@ pub fn transpose( if let Some(name) = args.rest.get(i) { headers.push(name.item.clone()) } else { - headers.push(format!("column{}", i)); + headers.push(format!("column{i}")); } } } diff --git a/crates/nu-command/src/formats/from/delimited.rs b/crates/nu-command/src/formats/from/delimited.rs index e047eff0a3..b5dbb24695 100644 --- a/crates/nu-command/src/formats/from/delimited.rs +++ b/crates/nu-command/src/formats/from/delimited.rs @@ -17,7 +17,7 @@ fn from_delimited_string_to_value( let headers = if noheaders { (1..=reader.headers()?.len()) - .map(|i| format!("column{}", i)) + .map(|i| format!("column{i}")) .collect::>() } else { reader.headers()?.iter().map(String::from).collect() diff --git a/crates/nu-command/src/formats/from/ics.rs b/crates/nu-command/src/formats/from/ics.rs index b170c34287..cecc64b99f 100644 --- a/crates/nu-command/src/formats/from/ics.rs +++ b/crates/nu-command/src/formats/from/ics.rs @@ -113,7 +113,7 @@ fn from_ics(input: PipelineData, head: Span) -> Result Ok(c) => output.push(calendar_to_value(c, head)), Err(e) => output.push(Value::Error { error: ShellError::UnsupportedInput( - format!("input cannot be parsed as .ics ({})", e), + format!("input cannot be parsed as .ics ({e})"), "value originates from here".into(), head, span, diff --git a/crates/nu-command/src/formats/from/ini.rs b/crates/nu-command/src/formats/from/ini.rs index 5d7689e546..33d42171d9 100644 --- a/crates/nu-command/src/formats/from/ini.rs +++ b/crates/nu-command/src/formats/from/ini.rs @@ -77,7 +77,7 @@ pub fn from_ini_string_to_value( Ok(Value::Record { cols, vals, span }) } Err(err) => Err(ShellError::UnsupportedInput( - format!("Could not load ini: {}", err), + format!("Could not load ini: {err}"), "value originates from here".into(), span, val_span, diff --git a/crates/nu-command/src/formats/from/json.rs b/crates/nu-command/src/formats/from/json.rs index 1a13c43d96..08a6a45453 100644 --- a/crates/nu-command/src/formats/from/json.rs +++ b/crates/nu-command/src/formats/from/json.rs @@ -183,7 +183,7 @@ fn convert_string_to_value(string_input: String, span: Span) -> Result Err(ShellError::CantConvert( - format!("structured json data ({})", x), + format!("structured json data ({x})"), "string".into(), span, None, diff --git a/crates/nu-command/src/formats/from/ods.rs b/crates/nu-command/src/formats/from/ods.rs index 28aa7466e3..a0b733b8d4 100644 --- a/crates/nu-command/src/formats/from/ods.rs +++ b/crates/nu-command/src/formats/from/ods.rs @@ -149,7 +149,7 @@ fn from_ods( _ => Value::nothing(head), }; - row_output.insert(format!("column{}", i), value); + row_output.insert(format!("column{i}"), value); } let (cols, vals) = diff --git a/crates/nu-command/src/formats/from/ssv.rs b/crates/nu-command/src/formats/from/ssv.rs index 2ade91b32f..24afbeb337 100644 --- a/crates/nu-command/src/formats/from/ssv.rs +++ b/crates/nu-command/src/formats/from/ssv.rs @@ -197,7 +197,7 @@ fn parse_separated_columns<'a>( let num_columns = ls.iter().map(|r| r.len()).max().unwrap_or(0); let headers = (1..=num_columns) - .map(|i| format!("column{}", i)) + .map(|i| format!("column{i}")) .collect::>(); collect(headers, ls.into_iter(), separator) }; diff --git a/crates/nu-command/src/formats/from/vcf.rs b/crates/nu-command/src/formats/from/vcf.rs index 12820dc5fb..7356056357 100644 --- a/crates/nu-command/src/formats/from/vcf.rs +++ b/crates/nu-command/src/formats/from/vcf.rs @@ -123,7 +123,7 @@ fn from_vcf(input: PipelineData, head: Span) -> Result Ok(c) => contact_to_value(c, head), Err(e) => Value::Error { error: ShellError::UnsupportedInput( - format!("input cannot be parsed as .vcf ({})", e), + format!("input cannot be parsed as .vcf ({e})"), "value originates from here".into(), head, span, diff --git a/crates/nu-command/src/formats/from/xlsx.rs b/crates/nu-command/src/formats/from/xlsx.rs index 41bd355b89..4f1a0c5402 100644 --- a/crates/nu-command/src/formats/from/xlsx.rs +++ b/crates/nu-command/src/formats/from/xlsx.rs @@ -148,7 +148,7 @@ fn from_xlsx( _ => Value::nothing(head), }; - row_output.insert(format!("column{}", i), value); + row_output.insert(format!("column{i}"), value); } let (cols, vals) = diff --git a/crates/nu-command/src/formats/from/yaml.rs b/crates/nu-command/src/formats/from/yaml.rs index d1e4e34a83..99d2fbc844 100644 --- a/crates/nu-command/src/formats/from/yaml.rs +++ b/crates/nu-command/src/formats/from/yaml.rs @@ -120,7 +120,7 @@ fn convert_yaml_value_to_nu_value( for (k, v) in t { // A ShellError that we re-use multiple times in the Mapping scenario let err_unexpected_map = ShellError::UnsupportedInput( - format!("Unexpected YAML:\nKey: {:?}\nValue: {:?}", k, v), + format!("Unexpected YAML:\nKey: {k:?}\nValue: {v:?}"), "value originates from here".into(), span, val_span, @@ -189,7 +189,7 @@ pub fn from_yaml_string_to_value( for document in serde_yaml::Deserializer::from_str(&s) { let v: serde_yaml::Value = serde_yaml::Value::deserialize(document).map_err(|x| { ShellError::UnsupportedInput( - format!("Could not load YAML: {}", x), + format!("Could not load YAML: {x}"), "value originates from here".into(), span, val_span, diff --git a/crates/nu-command/src/formats/to/nuon.rs b/crates/nu-command/src/formats/to/nuon.rs index 43c10d589a..f457b4eecf 100644 --- a/crates/nu-command/src/formats/to/nuon.rs +++ b/crates/nu-command/src/formats/to/nuon.rs @@ -55,7 +55,7 @@ pub fn value_to_string(v: &Value, span: Span) -> Result { Value::Binary { val, .. } => { let mut s = String::with_capacity(2 * val.len()); for byte in val { - if write!(s, "{:02X}", byte).is_err() { + if write!(s, "{byte:02X}").is_err() { return Err(ShellError::UnsupportedInput( "could not convert binary to string".into(), "value originates from here".into(), @@ -64,7 +64,7 @@ pub fn value_to_string(v: &Value, span: Span) -> Result { )); } } - Ok(format!("0x[{}]", s)) + Ok(format!("0x[{s}]")) } Value::Block { .. } => Err(ShellError::UnsupportedInput( "blocks are currently not nuon-compatible".into(), @@ -125,7 +125,7 @@ pub fn value_to_string(v: &Value, span: Span) -> Result { .iter() .map(|string| { if needs_quotes(string) { - format!("\"{}\"", string) + format!("\"{string}\"") } else { string.to_string() } diff --git a/crates/nu-command/src/formats/to/text.rs b/crates/nu-command/src/formats/to/text.rs index bfea06c9f3..12202d6377 100644 --- a/crates/nu-command/src/formats/to/text.rs +++ b/crates/nu-command/src/formats/to/text.rs @@ -143,13 +143,13 @@ fn local_into_string(value: Value, separator: &str, config: &Config) -> String { .join(separator), Value::LazyRecord { val, .. } => match val.collect() { Ok(val) => local_into_string(val, separator, config), - Err(error) => format!("{:?}", error), + Err(error) => format!("{error:?}"), }, - Value::Block { val, .. } => format!("", val), - Value::Closure { val, .. } => format!("", val), + Value::Block { val, .. } => format!(""), + Value::Closure { val, .. } => format!(""), Value::Nothing { .. } => String::new(), - Value::Error { error } => format!("{:?}", error), - Value::Binary { val, .. } => format!("{:?}", val), + Value::Error { error } => format!("{error:?}"), + Value::Binary { val, .. } => format!("{val:?}"), Value::CellPath { val, .. } => val.into_string(), Value::CustomValue { val, .. } => val.value_string(), } diff --git a/crates/nu-command/src/hash/generic_digest.rs b/crates/nu-command/src/hash/generic_digest.rs index d7bad3a6f0..0cf346664f 100644 --- a/crates/nu-command/src/hash/generic_digest.rs +++ b/crates/nu-command/src/hash/generic_digest.rs @@ -131,7 +131,7 @@ where } } else { Value::String { - val: format!("{:x}", digest), + val: format!("{digest:x}"), span, } } diff --git a/crates/nu-command/src/misc/tutor.rs b/crates/nu-command/src/misc/tutor.rs index d3885f5208..7feea66625 100644 --- a/crates/nu-command/src/misc/tutor.rs +++ b/crates/nu-command/src/misc/tutor.rs @@ -117,7 +117,7 @@ fn tutor( let message = format!( "You can find '{find}' in the following topics:\n\n{}\n\n{notes}", - results.into_iter().map(|x| format!("- {}", x)).join("\n") + results.into_iter().map(|x| format!("- {x}")).join("\n") ); return Ok(display(&message, engine_state, stack, span)); @@ -126,7 +126,7 @@ fn tutor( let results = search_space.map(|s| s.0[0].to_string()); let message = format!( "This tutorial contains the following topics:\n\n{}\n\n{notes}", - results.map(|x| format!("- {}", x)).join("\n") + results.map(|x| format!("- {x}")).join("\n") ); return Ok(display(&message, engine_state, stack, span)); } diff --git a/crates/nu-command/src/network/http/get.rs b/crates/nu-command/src/network/http/get.rs index 897e7ae932..4a8a51306c 100644 --- a/crates/nu-command/src/network/http/get.rs +++ b/crates/nu-command/src/network/http/get.rs @@ -167,17 +167,17 @@ fn helper( let login = match (user, password) { (Some(user), Some(password)) => { let mut enc_str = String::new(); - base64_engine.encode_string(&format!("{}:{}", user, password), &mut enc_str); + base64_engine.encode_string(&format!("{user}:{password}"), &mut enc_str); Some(enc_str) } (Some(user), _) => { let mut enc_str = String::new(); - base64_engine.encode_string(&format!("{}:", user), &mut enc_str); + base64_engine.encode_string(&format!("{user}:"), &mut enc_str); Some(enc_str) } (_, Some(password)) => { let mut enc_str = String::new(); - base64_engine.encode_string(&format!(":{}", password), &mut enc_str); + base64_engine.encode_string(&format!(":{password}"), &mut enc_str); Some(enc_str) } _ => None, @@ -200,7 +200,7 @@ fn helper( } if let Some(login) = login { - request = request.header("Authorization", format!("Basic {}", login)); + request = request.header("Authorization", format!("Basic {login}")); } if let Some(headers) = headers { @@ -268,7 +268,7 @@ fn helper( })?; let content_type = mime::Mime::from_str(content_type).map_err(|_| { ShellError::GenericError( - format!("MIME type unknown: {}", content_type), + format!("MIME type unknown: {content_type}"), "".to_string(), None, Some("given unknown MIME type".to_string()), @@ -280,7 +280,7 @@ fn helper( let path_extension = url::Url::parse(&requested_url) .map_err(|_| { ShellError::GenericError( - format!("Cannot parse URL: {}", requested_url), + format!("Cannot parse URL: {requested_url}"), "".to_string(), None, Some("cannot parse".to_string()), @@ -307,7 +307,7 @@ fn helper( } if let Some(ext) = ext { - match engine_state.find_decl(format!("from {}", ext).as_bytes(), &[]) { + match engine_state.find_decl(format!("from {ext}").as_bytes(), &[]) { Some(converter_id) => engine_state.get_decl(converter_id).run( engine_state, stack, @@ -323,28 +323,25 @@ fn helper( None => Ok(response_to_buffer(resp, engine_state, span)), }, Err(e) if e.is_timeout() => Err(ShellError::NetworkFailure( - format!("Request to {} has timed out", requested_url), + format!("Request to {requested_url} has timed out"), span, )), Err(e) if e.is_status() => match e.status() { Some(err_code) if err_code == StatusCode::NOT_FOUND => Err(ShellError::NetworkFailure( - format!("Requested file not found (404): {:?}", requested_url), + format!("Requested file not found (404): {requested_url:?}"), span, )), Some(err_code) if err_code == StatusCode::MOVED_PERMANENTLY => { Err(ShellError::NetworkFailure( - format!("Resource moved permanently (301): {:?}", requested_url), - span, - )) - } - Some(err_code) if err_code == StatusCode::BAD_REQUEST => { - Err(ShellError::NetworkFailure( - format!("Bad request (400) to {:?}", requested_url), + format!("Resource moved permanently (301): {requested_url:?}"), span, )) } + Some(err_code) if err_code == StatusCode::BAD_REQUEST => Err( + ShellError::NetworkFailure(format!("Bad request (400) to {requested_url:?}"), span), + ), Some(err_code) if err_code == StatusCode::FORBIDDEN => Err(ShellError::NetworkFailure( - format!("Access forbidden (403) to {:?}", requested_url), + format!("Access forbidden (403) to {requested_url:?}"), span, )), _ => Err(ShellError::NetworkFailure( diff --git a/crates/nu-command/src/network/http/post.rs b/crates/nu-command/src/network/http/post.rs index ce582cf854..90bbfe0d30 100644 --- a/crates/nu-command/src/network/http/post.rs +++ b/crates/nu-command/src/network/http/post.rs @@ -174,7 +174,7 @@ fn helper( return Err(ShellError::UnsupportedInput( "Incomplete or incorrect URL. Expected a full URL, e.g., https://www.example.com" .to_string(), - format!("value: '{:?}'", requested_url), + format!("value: '{requested_url:?}'"), call.head, span, )); @@ -190,12 +190,12 @@ fn helper( let login = match (user, password) { (Some(user), Some(password)) => { let mut enc_str = String::new(); - base64_engine.encode_string(&format!("{}:{}", user, password), &mut enc_str); + base64_engine.encode_string(&format!("{user}:{password}"), &mut enc_str); Some(enc_str) } (Some(user), _) => { let mut enc_str = String::new(); - base64_engine.encode_string(&format!("{}:", user), &mut enc_str); + base64_engine.encode_string(&format!("{user}:"), &mut enc_str); Some(enc_str) } _ => None, @@ -249,7 +249,7 @@ fn helper( request = request.header("Content-Length", val); } if let Some(login) = login { - request = request.header("Authorization", format!("Basic {}", login)); + request = request.header("Authorization", format!("Basic {login}")); } if let Some(headers) = headers { @@ -317,7 +317,7 @@ fn helper( })?; let content_type = mime::Mime::from_str(content_type).map_err(|_| { ShellError::GenericError( - format!("MIME type unknown: {}", content_type), + format!("MIME type unknown: {content_type}"), "".to_string(), None, Some("given unknown MIME type".to_string()), @@ -329,7 +329,7 @@ fn helper( let path_extension = url::Url::parse(&requested_url) .map_err(|_| { ShellError::GenericError( - format!("Cannot parse URL: {}", requested_url), + format!("Cannot parse URL: {requested_url}"), "".to_string(), None, Some("cannot parse".to_string()), @@ -354,7 +354,7 @@ fn helper( return Ok(output); } if let Some(ext) = ext { - match engine_state.find_decl(format!("from {}", ext).as_bytes(), &[]) { + match engine_state.find_decl(format!("from {ext}").as_bytes(), &[]) { Some(converter_id) => engine_state.get_decl(converter_id).run( engine_state, stack, @@ -371,23 +371,20 @@ fn helper( }, Err(e) if e.is_status() => match e.status() { Some(err_code) if err_code == StatusCode::NOT_FOUND => Err(ShellError::NetworkFailure( - format!("Requested file not found (404): {:?}", requested_url), + format!("Requested file not found (404): {requested_url:?}"), span, )), Some(err_code) if err_code == StatusCode::MOVED_PERMANENTLY => { Err(ShellError::NetworkFailure( - format!("Resource moved permanently (301): {:?}", requested_url), - span, - )) - } - Some(err_code) if err_code == StatusCode::BAD_REQUEST => { - Err(ShellError::NetworkFailure( - format!("Bad request (400) to {:?}", requested_url), + format!("Resource moved permanently (301): {requested_url:?}"), span, )) } + Some(err_code) if err_code == StatusCode::BAD_REQUEST => Err( + ShellError::NetworkFailure(format!("Bad request (400) to {requested_url:?}"), span), + ), Some(err_code) if err_code == StatusCode::FORBIDDEN => Err(ShellError::NetworkFailure( - format!("Access forbidden (403) to {:?}", requested_url), + format!("Access forbidden (403) to {requested_url:?}"), span, )), _ => Err(ShellError::NetworkFailure( diff --git a/crates/nu-command/src/network/url/join.rs b/crates/nu-command/src/network/url/join.rs index af3de14870..6fd6ab3b31 100644 --- a/crates/nu-command/src/network/url/join.rs +++ b/crates/nu-command/src/network/url/join.rs @@ -180,21 +180,21 @@ impl UrlComponents { .iter() .zip(vals.iter()) .map(|(k, v)| match v.as_string() { - Ok(val) => Ok(format!("{}={}", k, val)), + Ok(val) => Ok(format!("{k}={val}")), Err(err) => Err(err), }) .collect::, ShellError>>()? .join("&"); - qs = format!("?{}", qs); + qs = format!("?{qs}"); if let Some(q) = self.query { if q != qs { // if query is present it means that also query_span is set. return Err(ShellError::IncompatibleParameters { - left_message: format!("Mismatch, qs from params is: {}", qs), + left_message: format!("Mismatch, qs from params is: {qs}"), left_span: value.expect_span(), - right_message: format!("instead query is: {}", q), + right_message: format!("instead query is: {q}"), right_span: self.query_span.unwrap_or(Span::unknown()), }); } @@ -241,7 +241,7 @@ impl UrlComponents { path: Some(if s.starts_with('/') { s } else { - format!("/{}", s) + format!("/{s}") }), ..self }), @@ -250,16 +250,16 @@ impl UrlComponents { if q != s { // if query is present it means that also params_span is set. return Err(ShellError::IncompatibleParameters { - left_message: format!("Mismatch, query param is: {}", s), + left_message: format!("Mismatch, query param is: {s}"), left_span: value.expect_span(), - right_message: format!("instead qs from params is: {}", q), + right_message: format!("instead qs from params is: {q}"), right_span: self.params_span.unwrap_or(Span::unknown()), }); } } Ok(Self { - query: Some(format!("?{}", s)), + query: Some(format!("?{s}")), query_span: Some(value.expect_span()), ..self }) @@ -268,7 +268,7 @@ impl UrlComponents { fragment: Some(if s.starts_with('#') { s } else { - format!("#{}", s) + format!("#{s}") }), ..self }), @@ -285,7 +285,7 @@ impl UrlComponents { if let Some(usr) = &self.username { if let Some(pwd) = &self.password { - user_and_pwd = format!("{}:{}@", usr, pwd); + user_and_pwd = format!("{usr}:{pwd}@"); } } @@ -311,7 +311,7 @@ impl UrlComponents { user_and_pwd, host_result?, self.port - .map(|p| format!(":{}", p)) + .map(|p| format!(":{p}")) .as_deref() .unwrap_or_default(), self.path.as_deref().unwrap_or_default(), diff --git a/crates/nu-command/src/path/join.rs b/crates/nu-command/src/path/join.rs index ab78c8c3f4..021238c535 100644 --- a/crates/nu-command/src/path/join.rs +++ b/crates/nu-command/src/path/join.rs @@ -233,8 +233,7 @@ fn merge_record( let allowed_cols = super::ALLOWED_COLUMNS.join(", "); return Err(ShellError::UnsupportedInput( format!( - "Column '{}' is not valid for a structured path. Allowed columns on this platform are: {}", - key, allowed_cols + "Column '{key}' is not valid for a structured path. Allowed columns on this platform are: {allowed_cols}" ), "value originates from here".into(), head, diff --git a/crates/nu-command/src/platform/ansi/ansi_.rs b/crates/nu-command/src/platform/ansi/ansi_.rs index b218ed5531..2fad9f88e0 100644 --- a/crates/nu-command/src/platform/ansi/ansi_.rs +++ b/crates/nu-command/src/platform/ansi/ansi_.rs @@ -682,13 +682,13 @@ Format: # } let output = if escape && param_is_valid_string { - format!("\x1b[{}", code_string) + format!("\x1b[{code_string}") } else if osc && param_is_valid_string { // Operating system command aka osc ESC ] <- note the right brace, not left brace for osc // OCS's need to end with either: // bel '\x07' char // string terminator aka st '\\' char - format!("\x1b]{}", code_string) + format!("\x1b]{code_string}") } else if param_is_valid_string { // parse hex colors like #00FF00 if code_string.starts_with('#') { @@ -700,7 +700,7 @@ Format: # Err(err) => { return Err(ShellError::GenericError( "error parsing hex color".to_string(), - format!("{}", err), + format!("{err}"), Some(code.span()?), None, Vec::new(), @@ -738,7 +738,7 @@ Format: # "attr" => nu_style.attr = Some(v.as_string()?), _ => { return Err(ShellError::IncompatibleParametersSingle( - format!("problem with key: {}", k), + format!("problem with key: {k}"), code.expect_span(), )) } diff --git a/crates/nu-command/src/platform/ansi/link.rs b/crates/nu-command/src/platform/ansi/link.rs index 362ce90f3c..f150fa1d7c 100644 --- a/crates/nu-command/src/platform/ansi/link.rs +++ b/crates/nu-command/src/platform/ansi/link.rs @@ -146,7 +146,7 @@ fn process_value(value: &Value, text: &Option, command_span: &Span) -> V } fn add_osc_link(text: &str, link: &str) -> String { - format!("\u{1b}]8;;{}\u{1b}\\{}\u{1b}]8;;\u{1b}\\", link, text) + format!("\u{1b}]8;;{link}\u{1b}\\{text}\u{1b}]8;;\u{1b}\\") } #[cfg(test)] diff --git a/crates/nu-command/src/platform/input.rs b/crates/nu-command/src/platform/input.rs index c7b6f87522..45553ea131 100644 --- a/crates/nu-command/src/platform/input.rs +++ b/crates/nu-command/src/platform/input.rs @@ -57,7 +57,7 @@ impl Command for Input { let _ = crossterm::terminal::enable_raw_mode(); if let Some(prompt) = prompt { - print!("{}", prompt); + print!("{prompt}"); let _ = std::io::stdout().flush(); } if let Some(c) = bytes_until.bytes().next() { @@ -92,7 +92,7 @@ impl Command for Input { } } else { if let Some(prompt) = prompt { - print!("{}", prompt); + print!("{prompt}"); let _ = std::io::stdout().flush(); } diff --git a/crates/nu-command/src/platform/reedline_commands/keybindings_listen.rs b/crates/nu-command/src/platform/reedline_commands/keybindings_listen.rs index e7e8fcf2a5..6e38799a4a 100644 --- a/crates/nu-command/src/platform/reedline_commands/keybindings_listen.rs +++ b/crates/nu-command/src/platform/reedline_commands/keybindings_listen.rs @@ -113,10 +113,10 @@ fn print_events_helper(event: Event) -> Result { "flags".into(), ], vals: vec![ - Value::string(format!("{}", c), Span::unknown()), + Value::string(format!("{c}"), Span::unknown()), Value::string(format!("{:#08x}", u32::from(c)), Span::unknown()), - Value::string(format!("{:?}", modifiers), Span::unknown()), - Value::string(format!("{:#08b}", modifiers), Span::unknown()), + Value::string(format!("{modifiers:?}"), Span::unknown()), + Value::string(format!("{modifiers:#08b}"), Span::unknown()), ], span: Span::unknown(), }; @@ -126,9 +126,9 @@ fn print_events_helper(event: Event) -> Result { let record = Value::Record { cols: vec!["code".into(), "modifier".into(), "flags".into()], vals: vec![ - Value::string(format!("{:?}", code), Span::unknown()), - Value::string(format!("{:?}", modifiers), Span::unknown()), - Value::string(format!("{:#08b}", modifiers), Span::unknown()), + Value::string(format!("{code:?}"), Span::unknown()), + Value::string(format!("{modifiers:?}"), Span::unknown()), + Value::string(format!("{modifiers:#08b}"), Span::unknown()), ], span: Span::unknown(), }; @@ -138,7 +138,7 @@ fn print_events_helper(event: Event) -> Result { } else { let record = Value::Record { cols: vec!["event".into()], - vals: vec![Value::string(format!("{:?}", event), Span::unknown())], + vals: vec![Value::string(format!("{event:?}"), Span::unknown())], span: Span::unknown(), }; Ok(record) diff --git a/crates/nu-command/src/strings/encode_decode/base64.rs b/crates/nu-command/src/strings/encode_decode/base64.rs index f9545ad712..6401b709e7 100644 --- a/crates/nu-command/src/strings/encode_decode/base64.rs +++ b/crates/nu-command/src/strings/encode_decode/base64.rs @@ -93,8 +93,7 @@ fn action( not_valid => return Value::Error { error:ShellError::GenericError( "value is not an accepted character set".to_string(), format!( - "{} is not a valid character-set.\nPlease use `help hash base64` to see a list of valid character sets.", - not_valid + "{not_valid} is not a valid character-set.\nPlease use `help hash base64` to see a list of valid character sets." ), Some(config_character_set.span), None, diff --git a/crates/nu-command/src/strings/encode_decode/encoding.rs b/crates/nu-command/src/strings/encode_decode/encoding.rs index 39f481fe08..6c11f1713f 100644 --- a/crates/nu-command/src/strings/encode_decode/encoding.rs +++ b/crates/nu-command/src/strings/encode_decode/encoding.rs @@ -62,8 +62,7 @@ fn parse_encoding(span: Span, label: &str) -> Result<&'static Encoding, ShellErr match Encoding::for_label_no_replacement(label.as_bytes()) { None => Err(ShellError::GenericError( format!( - r#"{} is not a valid encoding"#, - label + r#"{label} is not a valid encoding"# ), "invalid encoding".into(), Some(span), diff --git a/crates/nu-command/src/strings/format/command.rs b/crates/nu-command/src/strings/format/command.rs index ac3849c689..24c3ab5406 100644 --- a/crates/nu-command/src/strings/format/command.rs +++ b/crates/nu-command/src/strings/format/command.rs @@ -303,7 +303,7 @@ fn format_record( } Some(err) => { return Err(ShellError::TypeMismatch( - format!("expression is invalid, detail message: {:?}", err), + format!("expression is invalid, detail message: {err:?}"), *span, )) } diff --git a/crates/nu-command/src/strings/size.rs b/crates/nu-command/src/strings/size.rs index 894a5e68a5..2a8d4da328 100644 --- a/crates/nu-command/src/strings/size.rs +++ b/crates/nu-command/src/strings/size.rs @@ -298,7 +298,7 @@ impl fmt::Display for Counter { Counter::CodePoints => "codepoints", }; - write!(f, "{}", s) + write!(f, "{s}") } } diff --git a/crates/nu-command/src/strings/str_/trim/trim_.rs b/crates/nu-command/src/strings/str_/trim/trim_.rs index 3fc67ab868..e32d367f74 100644 --- a/crates/nu-command/src/strings/str_/trim/trim_.rs +++ b/crates/nu-command/src/strings/str_/trim/trim_.rs @@ -266,10 +266,10 @@ fn trim(s: &str, char_: Option, closure_flags: &ClosureFlags) -> String { '\x0B' => r"\v".to_string(), '\x0C' => r"\f".to_string(), '\x0D' => r"\r".to_string(), - _ => format!(r"\{}", r), + _ => format!(r"\{r}"), }; // create a regex string that looks for 2 or more of each of these characters - let re_str = format!("{}{{2,}}", reg); + let re_str = format!("{reg}{{2,}}"); // create the regex let re = Regex::new(&re_str).expect("Error creating regular expression"); // replace all multiple occurrences with single occurrences represented by r diff --git a/crates/nu-command/src/system/run_external.rs b/crates/nu-command/src/system/run_external.rs index 7de612b34a..a065ebe68c 100644 --- a/crates/nu-command/src/system/run_external.rs +++ b/crates/nu-command/src/system/run_external.rs @@ -753,7 +753,7 @@ fn shell_arg_escape(arg: &str) -> String { s if !has_unsafe_shell_characters(s) => String::from(s), _ => { let single_quotes_escaped = arg.split('\'').join("'\"'\"'"); - format!("'{}'", single_quotes_escaped) + format!("'{single_quotes_escaped}'") } } } diff --git a/crates/nu-command/src/system/which_.rs b/crates/nu-command/src/system/which_.rs index d4f59af110..0d0fd892a1 100644 --- a/crates/nu-command/src/system/which_.rs +++ b/crates/nu-command/src/system/which_.rs @@ -86,7 +86,7 @@ fn get_entry_in_aliases(engine_state: &EngineState, name: &str, span: Span) -> O Some(entry( name, - format!("Nushell alias: {}", alias_str), + format!("Nushell alias: {alias_str}"), false, span, )) diff --git a/crates/nu-command/src/viewers/griddle.rs b/crates/nu-command/src/viewers/griddle.rs index 5ebbd64966..3cd87cf839 100644 --- a/crates/nu-command/src/viewers/griddle.rs +++ b/crates/nu-command/src/viewers/griddle.rs @@ -239,7 +239,7 @@ fn create_grid_output( Value::string(grid_display.to_string(), call.head) } else { Value::String { - val: format!("Couldn't fit grid into {} columns!", cols), + val: format!("Couldn't fit grid into {cols} columns!"), span: call.head, } } diff --git a/crates/nu-command/src/viewers/table.rs b/crates/nu-command/src/viewers/table.rs index 7369a5387a..372d028ac2 100644 --- a/crates/nu-command/src/viewers/table.rs +++ b/crates/nu-command/src/viewers/table.rs @@ -320,7 +320,7 @@ fn handle_table_command( } else { // assume this failed because the table was too wide // TODO: more robust error classification - format!("Couldn't fit table into {} columns!", term_width) + format!("Couldn't fit table into {term_width} columns!") } }); @@ -1481,7 +1481,7 @@ fn convert_with_precision(val: &str, precision: usize) -> Result bool { @@ -1696,7 +1696,7 @@ impl Iterator for PagingTableCreator { // assume this failed because the table was too wide // TODO: more robust error classification let term_width = get_width_param(self.width_param); - format!("Couldn't fit table into {} columns!", term_width) + format!("Couldn't fit table into {term_width} columns!") }; Some(Ok(msg.as_bytes().to_vec())) } diff --git a/crates/nu-command/tests/commands/math/sum.rs b/crates/nu-command/tests/commands/math/sum.rs index ba66fbf3f4..d69cf5507e 100644 --- a/crates/nu-command/tests/commands/math/sum.rs +++ b/crates/nu-command/tests/commands/math/sum.rs @@ -45,7 +45,7 @@ fn compute_sum_of_individual_row() -> Result<(), String> { for (column_name, expected_value) in answers_for_columns { let actual = nu!( cwd: "tests/fixtures/formats/", - format!("open sample-ps-output.json | select {} | math sum | get {}", column_name, column_name) + format!("open sample-ps-output.json | select {column_name} | math sum | get {column_name}") ); let result = f64::from_str(&actual.out).map_err(|_| String::from("Failed to parse float."))?; @@ -66,7 +66,7 @@ fn compute_sum_of_table() -> Result<(), String> { for (column_name, expected_value) in answers_for_columns { let actual = nu!( cwd: "tests/fixtures/formats/", - format!("open sample-ps-output.json | select cpu mem virtual | math sum | get {}", column_name) + format!("open sample-ps-output.json | select cpu mem virtual | math sum | get {column_name}") ); let result = f64::from_str(&actual.out).map_err(|_| String::from("Failed to parse float."))?; diff --git a/crates/nu-command/tests/commands/platform/kill.rs b/crates/nu-command/tests/commands/platform/kill.rs index d74ffd372a..5814ea41ee 100644 --- a/crates/nu-command/tests/commands/platform/kill.rs +++ b/crates/nu-command/tests/commands/platform/kill.rs @@ -3,7 +3,7 @@ use nu_test_support::nu; #[test] fn test_kill_invalid_pid() { let pid = i32::MAX; - let actual = nu!(format!("kill {}", pid)); + let actual = nu!(format!("kill {pid}")); assert!(actual.err.contains("process didn't terminate successfully")); } diff --git a/crates/nu-command/tests/commands/roll.rs b/crates/nu-command/tests/commands/roll.rs index 2964283276..e59b70b9d3 100644 --- a/crates/nu-command/tests/commands/roll.rs +++ b/crates/nu-command/tests/commands/roll.rs @@ -97,7 +97,7 @@ mod columns { let actual = nu!( cwd: ".", - format!("{} | roll right --by 3 --cells-only | columns | str join '-' ", four_bitstring) + format!("{four_bitstring} | roll right --by 3 --cells-only | columns | str join '-' ") ); assert_eq!(actual.out, expected_value.1); @@ -142,12 +142,11 @@ mod columns { "#, ); println!( - "{} | roll left --by 3 | {}", - bitstring_as_nu_row_pipeline, nu_row_literal_bitstring_to_decimal_value_pipeline + "{bitstring_as_nu_row_pipeline} | roll left --by 3 | {nu_row_literal_bitstring_to_decimal_value_pipeline}" ); nu!( cwd: ".", - format!("{} | roll left --by 3 | {}", bitstring_as_nu_row_pipeline, nu_row_literal_bitstring_to_decimal_value_pipeline) + format!("{bitstring_as_nu_row_pipeline} | roll left --by 3 | {nu_row_literal_bitstring_to_decimal_value_pipeline}") ).out } diff --git a/crates/nu-command/tests/commands/save.rs b/crates/nu-command/tests/commands/save.rs index 44f1b5ba35..2e5c34428e 100644 --- a/crates/nu-command/tests/commands/save.rs +++ b/crates/nu-command/tests/commands/save.rs @@ -16,7 +16,7 @@ fn writes_out_csv() { ); let actual = file_contents(expected_file); - println!("{}", actual); + println!("{actual}"); assert!(actual.contains("nu,0.14,A new type of shell,MIT,2018")); }) } @@ -52,7 +52,7 @@ fn save_append_will_create_file_if_not_exists() { ); let actual = file_contents(expected_file); - println!("{}", actual); + println!("{actual}"); assert_eq!(actual, "hello"); }) } @@ -78,7 +78,7 @@ fn save_append_will_not_overwrite_content() { ); let actual = file_contents(expected_file); - println!("{}", actual); + println!("{actual}"); assert_eq!(actual, "hello world"); }) } diff --git a/crates/nu-command/tests/commands/source_env.rs b/crates/nu-command/tests/commands/source_env.rs index aa7ae739b4..7036aee68a 100644 --- a/crates/nu-command/tests/commands/source_env.rs +++ b/crates/nu-command/tests/commands/source_env.rs @@ -16,10 +16,9 @@ fn sources_also_files_under_custom_lib_dirs_path() { "config.toml", &format!( r#" - lib_dirs = ["{}"] + lib_dirs = ["{library_path}"] skip_welcome_message = true - "#, - library_path + "# ), )]); @@ -151,7 +150,7 @@ fn can_source_dynamic_path() { sandbox.with_files(vec![FileWithContent(foo_file, "echo foo")]); - let cmd = format!("let file = `{}`; source-env $file", foo_file); + let cmd = format!("let file = `{foo_file}`; source-env $file"); let actual = nu!(cwd: dirs.test(), &cmd); assert_eq!(actual.out, "foo"); diff --git a/crates/nu-command/tests/commands/zip.rs b/crates/nu-command/tests/commands/zip.rs index e8b743616e..ae3c30f645 100644 --- a/crates/nu-command/tests/commands/zip.rs +++ b/crates/nu-command/tests/commands/zip.rs @@ -19,7 +19,7 @@ fn zips_two_tables() { Playground::setup("zip_test_1", |dirs, nu| { nu.with_files(vec![FileWithContent( "zip_test.nu", - &format!("{}\n", ZIP_POWERED_TEST_ASSERTION_SCRIPT), + &format!("{ZIP_POWERED_TEST_ASSERTION_SCRIPT}\n"), )]); let actual = nu!( diff --git a/crates/nu-command/tests/format_conversions/nuon.rs b/crates/nu-command/tests/format_conversions/nuon.rs index 1898d73fa7..3b6f48f424 100644 --- a/crates/nu-command/tests/format_conversions/nuon.rs +++ b/crates/nu-command/tests/format_conversions/nuon.rs @@ -390,11 +390,11 @@ proptest! { let actual = nu!( cwd: "tests/fixtures/formats", pipeline( format!(r#" - {{"prop{0}test": "sam"}} | to nuon | from nuon; - [ [ "prop{0}test" ]; [ 'test' ] ] | to nuon | from nuon; - [ [ "{0}" ]; [ 'test' ] ] | to nuon | from nuon; - {{"{0}": "sam"}} | to nuon | from nuon; - "#, c).as_ref() + {{"prop{c}test": "sam"}} | to nuon | from nuon; + [ [ "prop{c}test" ]; [ 'test' ] ] | to nuon | from nuon; + [ [ "{c}" ]; [ 'test' ] ] | to nuon | from nuon; + {{"{c}": "sam"}} | to nuon | from nuon; + "#).as_ref() )); assert!(actual.err.is_empty() || actual.err.contains("Unexpected end of code") || actual.err.contains("only strings can be keys") || actual.err.contains("unbalanced { and }")); // The second is for weird escapes due to backslashes @@ -407,11 +407,11 @@ proptest! { let actual = nu!( cwd: "tests/fixtures/formats", pipeline( format!(r#" - {{"prop{0}test": "sam"}} | to nuon | from nuon; - [ [ "prop{0}test" ]; [ 'test' ] ] | to nuon | from nuon; - [ [ "{0}" ]; [ 'test' ] ] | to nuon | from nuon; - {{"{0}": "sam"}} | to nuon | from nuon; - "#, s).as_ref() + {{"prop{s}test": "sam"}} | to nuon | from nuon; + [ [ "prop{s}test" ]; [ 'test' ] ] | to nuon | from nuon; + [ [ "{s}" ]; [ 'test' ] ] | to nuon | from nuon; + {{"{s}": "sam"}} | to nuon | from nuon; + "#).as_ref() )); assert!(actual.err.is_empty() || actual.err.contains("only strings can be keys") || actual.err.contains("unknown command")); // TODO: fix parser error for "unknown command" when '=$' is the name diff --git a/crates/nu-engine/src/documentation.rs b/crates/nu-engine/src/documentation.rs index d24be36c1e..cdd5b82986 100644 --- a/crates/nu-engine/src/documentation.rs +++ b/crates/nu-engine/src/documentation.rs @@ -69,7 +69,7 @@ fn get_documentation( if !config.no_subcommands { let signatures = engine_state.get_signatures(true); for sig in signatures { - if sig.name.starts_with(&format!("{} ", cmd_name)) + if sig.name.starts_with(&format!("{cmd_name} ")) // Don't display deprecated commands in the Subcommands list && !sig.usage.starts_with("Deprecated command") { @@ -84,11 +84,11 @@ fn get_documentation( sig.search_terms.join(", "), RESET ); - let _ = write!(long_desc, "{}", text); + let _ = write!(long_desc, "{text}"); } let text = format!("{}Usage{}:\n > {}\n", G, RESET, sig.call_signature()); - let _ = write!(long_desc, "{}", text); + let _ = write!(long_desc, "{text}"); if !subcommands.is_empty() { let _ = write!(long_desc, "\n{G}Subcommands{RESET}:\n"); @@ -105,11 +105,10 @@ fn get_documentation( if sig.operates_on_cell_paths() { let _ = writeln!( long_desc, - "\n{}Signatures(Cell paths are supported){}:\n{}", - G, RESET, sig + "\n{G}Signatures(Cell paths are supported){RESET}:\n{sig}" ); } else { - let _ = writeln!(long_desc, "\n{}Signatures{}:\n{}", G, RESET, sig); + let _ = writeln!(long_desc, "\n{G}Signatures{RESET}:\n{sig}"); } } @@ -137,7 +136,7 @@ fn get_documentation( ) } }; - let _ = writeln!(long_desc, "{}", text); + let _ = writeln!(long_desc, "{text}"); } for positional in &sig.optional_positional { let text = match &positional.shape { @@ -158,7 +157,7 @@ fn get_documentation( ) } }; - let _ = writeln!(long_desc, "{}", text); + let _ = writeln!(long_desc, "{text}"); } if let Some(rest_positional) = &sig.rest_positional { @@ -168,12 +167,12 @@ fn get_documentation( document_shape(rest_positional.shape.clone()), rest_positional.desc ); - let _ = writeln!(long_desc, "{}", text); + let _ = writeln!(long_desc, "{text}"); } } if !examples.is_empty() { - let _ = write!(long_desc, "\n{}Examples{}:", G, RESET); + let _ = write!(long_desc, "\n{G}Examples{RESET}:"); } for example in examples { @@ -196,7 +195,7 @@ fn get_documentation( let result = output.into_value(Span::unknown()); match result.as_string() { Ok(s) => { - let _ = write!(long_desc, "\n > {}\n", s); + let _ = write!(long_desc, "\n > {s}\n"); } _ => { let _ = write!(long_desc, "\n > {}\n", example.example); @@ -237,7 +236,7 @@ pub fn get_flags_section(signature: &Signature) -> String { const D: &str = "\x1b[39m"; // default let mut long_desc = String::new(); - let _ = write!(long_desc, "\n{}Flags{}:\n", G, RESET); + let _ = write!(long_desc, "\n{G}Flags{RESET}:\n"); for flag in &signature.named { let msg = if let Some(arg) = &flag.arg { if let Some(short) = flag.short { diff --git a/crates/nu-engine/src/env.rs b/crates/nu-engine/src/env.rs index 9dc25e7e96..4424336e26 100644 --- a/crates/nu-engine/src/env.rs +++ b/crates/nu-engine/src/env.rs @@ -174,7 +174,7 @@ pub fn current_dir_str(engine_state: &EngineState, stack: &Stack) -> Result, env_path_name: &str) -> Optio if !vals.iter().all(|v| matches!(v, Value::String { .. })) { error = error.or_else(|| { Some(ShellError::GenericError( - format!("Wrong {} environment variable value", env_path_name), - format!("{} must be a list of strings", env_path_name), + format!("Wrong {env_path_name} environment variable value"), + format!("{env_path_name} must be a list of strings"), Some(*span), None, Vec::new(), @@ -416,8 +416,8 @@ fn ensure_path(scope: &mut HashMap, env_path_name: &str) -> Optio error = error.or_else(|| { Some(ShellError::GenericError( - format!("Wrong {} environment variable value", env_path_name), - format!("{} must be a list of strings", env_path_name), + format!("Wrong {env_path_name} environment variable value"), + format!("{env_path_name} must be a list of strings"), Some(span), None, Vec::new(), diff --git a/crates/nu-engine/src/eval.rs b/crates/nu-engine/src/eval.rs index b09a7169f9..6c15784790 100644 --- a/crates/nu-engine/src/eval.rs +++ b/crates/nu-engine/src/eval.rs @@ -19,7 +19,7 @@ pub fn eval_operator(op: &Expression) -> Result { .. } => Ok(operator.clone()), Expression { span, expr, .. } => { - Err(ShellError::UnknownOperator(format!("{:?}", expr), *span)) + Err(ShellError::UnknownOperator(format!("{expr:?}"), *span)) } } } diff --git a/crates/nu-explore/src/commands/config.rs b/crates/nu-explore/src/commands/config.rs index 75afc96321..ebdb71c346 100644 --- a/crates/nu-explore/src/commands/config.rs +++ b/crates/nu-explore/src/commands/config.rs @@ -160,7 +160,7 @@ fn create_default_value() -> Value { let record = |i: usize| Value::Record { cols: vec![String::from("key"), String::from("value")], - vals: vec![nu_str(format!("key-{}", i)), nu_str(format!("{}", i))], + vals: vec![nu_str(format!("key-{i}")), nu_str(format!("{i}"))], span, }; diff --git a/crates/nu-explore/src/commands/mod.rs b/crates/nu-explore/src/commands/mod.rs index fa9e312627..19ac9a13e9 100644 --- a/crates/nu-explore/src/commands/mod.rs +++ b/crates/nu-explore/src/commands/mod.rs @@ -176,6 +176,6 @@ pub fn default_color_list() -> Vec { pub fn default_int_list() -> Vec { (0..20) - .map(|i| HelpExample::new(i.to_string(), format!("A value equal to {}", i))) + .map(|i| HelpExample::new(i.to_string(), format!("A value equal to {i}"))) .collect() } diff --git a/crates/nu-explore/src/nu_common/table.rs b/crates/nu-explore/src/nu_common/table.rs index edc256b44f..3e54c13647 100644 --- a/crates/nu-explore/src/nu_common/table.rs +++ b/crates/nu-explore/src/nu_common/table.rs @@ -882,7 +882,7 @@ fn convert_with_precision(val: &str, precision: usize) -> Result TableTheme { diff --git a/crates/nu-explore/src/pager/mod.rs b/crates/nu-explore/src/pager/mod.rs index 3bb3664eaf..60d02a2b41 100644 --- a/crates/nu-explore/src/pager/mod.rs +++ b/crates/nu-explore/src/pager/mod.rs @@ -393,10 +393,9 @@ fn handle_command( run_command(engine_state, stack, pager, view, view_stack, command, args) } Some(Err(err)) => Err(format!( - "Error: command {:?} was not provided with correct arguments: {}", - args, err + "Error: command {args:?} was not provided with correct arguments: {err}" )), - None => Err(format!("Error: command {:?} was not recognized", args)), + None => Err(format!("Error: command {args:?} was not recognized")), } } @@ -447,7 +446,7 @@ fn run_command( Transition::Exit => Ok(true), Transition::Cmd { .. } => todo!("not used so far"), }, - Err(err) => Err(format!("Error: command {:?} failed: {}", args, err)), + Err(err) => Err(format!("Error: command {args:?} failed: {err}")), } } Command::View { mut cmd, is_light } => { @@ -472,7 +471,7 @@ fn run_command( *view = Some(Page::raw(new_view, is_light)); Ok(false) } - Err(err) => Err(format!("Error: command {:?} failed: {}", args, err)), + Err(err) => Err(format!("Error: command {args:?} failed: {err}")), } } } @@ -581,7 +580,7 @@ fn render_cmd_bar_search(f: &mut Frame, area: Rect, pager: &Pager<'_>, theme: &S } else { let index = pager.search_buf.search_index + 1; let total = pager.search_buf.search_results.len(); - format!("[{}/{}]", index, total) + format!("[{index}/{total}]") }; let bar = CommandBar::new(&text, &info, theme.cmd_bar_text, theme.cmd_bar_background); @@ -604,7 +603,7 @@ fn render_cmd_bar_cmd(f: &mut Frame, area: Rect, pager: &Pager, theme: &StyleCon } let prefix = ':'; - let text = format!("{}{}", prefix, input); + let text = format!("{prefix}{input}"); let bar = CommandBar::new(&text, "", theme.cmd_bar_text, theme.cmd_bar_background); f.render_widget(bar, area); diff --git a/crates/nu-explore/src/views/interactive.rs b/crates/nu-explore/src/views/interactive.rs index 464c48e754..6f2fcac6d2 100644 --- a/crates/nu-explore/src/views/interactive.rs +++ b/crates/nu-explore/src/views/interactive.rs @@ -195,9 +195,7 @@ impl View for InteractiveView<'_> { if self.immediate { match self.try_run(engine_state, stack) { Ok(_) => info.report = Some(Report::default()), - Err(err) => { - info.report = Some(Report::error(format!("Error: {}", err))) - } + Err(err) => info.report = Some(Report::error(format!("Error: {err}"))), } } } @@ -210,7 +208,7 @@ impl View for InteractiveView<'_> { if self.immediate { match self.try_run(engine_state, stack) { Ok(_) => info.report = Some(Report::default()), - Err(err) => info.report = Some(Report::error(format!("Error: {}", err))), + Err(err) => info.report = Some(Report::error(format!("Error: {err}"))), } } @@ -226,7 +224,7 @@ impl View for InteractiveView<'_> { KeyCode::Enter => { match self.try_run(engine_state, stack) { Ok(_) => info.report = Some(Report::default()), - Err(err) => info.report = Some(Report::error(format!("Error: {}", err))), + Err(err) => info.report = Some(Report::error(format!("Error: {err}"))), } Some(Transition::Ok) diff --git a/crates/nu-explore/src/views/record/mod.rs b/crates/nu-explore/src/views/record/mod.rs index fa94678bc5..ac3851cf56 100644 --- a/crates/nu-explore/src/views/record/mod.rs +++ b/crates/nu-explore/src/views/record/mod.rs @@ -691,11 +691,11 @@ fn report_cursor_position(mode: UIMode, cursor: XYCursor) -> String { if mode == UIMode::Cursor { let row = cursor.row(); let column = cursor.column(); - format!("{},{}", row, column) + format!("{row},{column}") } else { let rows_seen = cursor.row_starts_at(); let columns_seen = cursor.column_starts_at(); - format!("{},{}", rows_seen, columns_seen) + format!("{rows_seen},{columns_seen}") } } @@ -707,13 +707,13 @@ fn report_row_position(cursor: XYCursor) -> String { match percent_rows { 100 => String::from("All"), - value => format!("{}%", value), + value => format!("{value}%"), } } } fn get_percentage(value: usize, max: usize) -> usize { - debug_assert!(value <= max, "{:?} {:?}", value, max); + debug_assert!(value <= max, "{value:?} {max:?}"); ((value as f32 / max as f32) * 100.0).floor() as usize } diff --git a/crates/nu-explore/src/views/util.rs b/crates/nu-explore/src/views/util.rs index d117038b86..58e27e917d 100644 --- a/crates/nu-explore/src/views/util.rs +++ b/crates/nu-explore/src/views/util.rs @@ -161,5 +161,5 @@ fn convert_with_precision(val: &str, precision: usize) -> Result write!(f, "{}", msg), + ErrorCode::Custom(ref msg) => write!(f, "{msg}"), ErrorCode::EofWhileParsingList => "EOF while parsing a list".fmt(f), ErrorCode::EofWhileParsingObject => "EOF while parsing an object".fmt(f), ErrorCode::EofWhileParsingString => "EOF while parsing a string".fmt(f), @@ -129,7 +129,7 @@ impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { Error::Syntax(ref code, line, col) => { - write!(fmt, "{:?} at line {} column {}", code, line, col) + write!(fmt, "{code:?} at line {line} column {col}") } Error::Io(ref error) => fmt::Display::fmt(error, fmt), Error::FromUtf8(ref error) => fmt::Display::fmt(error, fmt), diff --git a/crates/nu-json/src/ser.rs b/crates/nu-json/src/ser.rs index b61e481ae8..73967bd7c7 100644 --- a/crates/nu-json/src/ser.rs +++ b/crates/nu-json/src/ser.rs @@ -94,49 +94,49 @@ where #[inline] fn serialize_i8(self, value: i8) -> Result<()> { self.formatter.start_value(&mut self.writer)?; - write!(&mut self.writer, "{}", value).map_err(From::from) + write!(&mut self.writer, "{value}").map_err(From::from) } #[inline] fn serialize_i16(self, value: i16) -> Result<()> { self.formatter.start_value(&mut self.writer)?; - write!(&mut self.writer, "{}", value).map_err(From::from) + write!(&mut self.writer, "{value}").map_err(From::from) } #[inline] fn serialize_i32(self, value: i32) -> Result<()> { self.formatter.start_value(&mut self.writer)?; - write!(&mut self.writer, "{}", value).map_err(From::from) + write!(&mut self.writer, "{value}").map_err(From::from) } #[inline] fn serialize_i64(self, value: i64) -> Result<()> { self.formatter.start_value(&mut self.writer)?; - write!(&mut self.writer, "{}", value).map_err(From::from) + write!(&mut self.writer, "{value}").map_err(From::from) } #[inline] fn serialize_u8(self, value: u8) -> Result<()> { self.formatter.start_value(&mut self.writer)?; - write!(&mut self.writer, "{}", value).map_err(From::from) + write!(&mut self.writer, "{value}").map_err(From::from) } #[inline] fn serialize_u16(self, value: u16) -> Result<()> { self.formatter.start_value(&mut self.writer)?; - write!(&mut self.writer, "{}", value).map_err(From::from) + write!(&mut self.writer, "{value}").map_err(From::from) } #[inline] fn serialize_u32(self, value: u32) -> Result<()> { self.formatter.start_value(&mut self.writer)?; - write!(&mut self.writer, "{}", value).map_err(From::from) + write!(&mut self.writer, "{value}").map_err(From::from) } #[inline] fn serialize_u64(self, value: u64) -> Result<()> { self.formatter.start_value(&mut self.writer)?; - write!(&mut self.writer, "{}", value).map_err(From::from) + write!(&mut self.writer, "{value}").map_err(From::from) } #[inline] @@ -904,7 +904,7 @@ where N: Display + LowerExp, { let f1 = value.to_string(); - let f2 = format!("{:e}", value); + let f2 = format!("{value:e}"); if f1.len() <= f2.len() + 1 { f1 } else if !f2.contains("e-") { diff --git a/crates/nu-parser/src/deparse.rs b/crates/nu-parser/src/deparse.rs index 9e0952b2b1..98404490ad 100644 --- a/crates/nu-parser/src/deparse.rs +++ b/crates/nu-parser/src/deparse.rs @@ -23,18 +23,18 @@ pub fn escape_for_script_arg(input: &str) -> String { if let Some((arg_name, arg_val)) = input.split_once('=') { // only want to escape arg_val. let arg_val = if arg_val.contains(' ') { - format!("`{}`", arg_val) + format!("`{arg_val}`") } else if arg_val.contains('"') || arg_val.contains('\\') { escape_quote_string(arg_val) } else { arg_val.into() }; - return format!("{}={}", arg_name, arg_val); + return format!("{arg_name}={arg_val}"); } } if input.contains(' ') { - format!("`{}`", input) + format!("`{input}`") } else if input.contains('"') || input.contains('\\') { escape_quote_string(input) } else { diff --git a/crates/nu-parser/src/eval.rs b/crates/nu-parser/src/eval.rs index 2bc773ed5e..e46699e8a1 100644 --- a/crates/nu-parser/src/eval.rs +++ b/crates/nu-parser/src/eval.rs @@ -36,7 +36,7 @@ pub fn eval_constant( // TODO: Better error conversion Err(shell_error) => Err(ParseError::LabeledError( "Error when following cell path".to_string(), - format!("{:?}", shell_error), + format!("{shell_error:?}"), expr.span, )), } diff --git a/crates/nu-parser/src/parse_keywords.rs b/crates/nu-parser/src/parse_keywords.rs index 6ae9d5b117..724d1c9203 100644 --- a/crates/nu-parser/src/parse_keywords.rs +++ b/crates/nu-parser/src/parse_keywords.rs @@ -3561,7 +3561,7 @@ pub fn parse_register( Ok(path) } else { Err(ParseError::RegisteredFileNotFound( - format!("{:?}", path), + format!("{path:?}"), expr.span, )) } @@ -3576,7 +3576,7 @@ pub fn parse_register( serde_json::from_slice::(signature).map_err(|e| { ParseError::LabeledError( "Signature deserialization error".into(), - format!("unable to deserialize signature: {}", e), + format!("unable to deserialize signature: {e}"), spans[0], ) }) @@ -3597,7 +3597,7 @@ pub fn parse_register( Ok(path) } else { Err(ParseError::RegisteredFileNotFound( - format!("{:?}", path), + format!("{path:?}"), expr.span, )) } diff --git a/crates/nu-parser/src/parser.rs b/crates/nu-parser/src/parser.rs index 23049cc400..6d40c403dd 100644 --- a/crates/nu-parser/src/parser.rs +++ b/crates/nu-parser/src/parser.rs @@ -237,7 +237,7 @@ pub fn check_name<'a>( Some(( &spans[command_len], ParseError::AssignmentMismatch( - format!("{} missing name", name), + format!("{name} missing name"), "missing name".into(), spans[command_len], ), @@ -251,7 +251,7 @@ pub fn check_name<'a>( Some(( &spans[command_len + 1], ParseError::AssignmentMismatch( - format!("{} missing sign", name), + format!("{name} missing sign"), "missing equal sign".into(), spans[command_len + 1], ), @@ -673,7 +673,7 @@ pub fn parse_multispan_value( ( Expression::garbage(span), Some(ParseError::Expected( - format!("one of a list of accepted shapes: {:?}", shapes), + format!("one of a list of accepted shapes: {shapes:?}"), span, )), ) @@ -3668,7 +3668,7 @@ pub fn parse_signature_helper( error = error.or_else(|| { Some(ParseError::AssignmentMismatch( "Default value wrong type".into(), - format!("default value not {}", t), + format!("default value not {t}"), expression.span, )) }) @@ -3717,8 +3717,7 @@ pub fn parse_signature_helper( "Default value is the wrong type" .into(), format!( - "default value should be {}", - t + "default value should be {t}" ), expression_span, )) @@ -4428,7 +4427,7 @@ pub fn parse_value( return ( Expression::garbage(span), Some(ParseError::Expected( - format!("non-block value: {}", shape), + format!("non-block value: {shape}"), span, )), ); diff --git a/crates/nu-parser/tests/test_parser.rs b/crates/nu-parser/tests/test_parser.rs index 78930a8419..97e9ec4b3e 100644 --- a/crates/nu-parser/tests/test_parser.rs +++ b/crates/nu-parser/tests/test_parser.rs @@ -1595,8 +1595,8 @@ mod input_types { for input in inputs { let (block, err) = parse(&mut working_set, None, input.as_bytes(), true, &[]); - assert!(err.is_none(), "testing: {}", input); - assert_eq!(block.len(), 2, "testing: {}", input); + assert!(err.is_none(), "testing: {input}"); + assert_eq!(block.len(), 2, "testing: {input}"); } } diff --git a/crates/nu-parser/tests/test_parser_unicode_escapes.rs b/crates/nu-parser/tests/test_parser_unicode_escapes.rs index 0cc884b1df..f330c11473 100644 --- a/crates/nu-parser/tests/test_parser_unicode_escapes.rs +++ b/crates/nu-parser/tests/test_parser_unicode_escapes.rs @@ -29,15 +29,13 @@ pub fn do_test(test: &[u8], expected: &str, error_contains: Option<&str>) { } Some(pev) => match error_contains { None => { - panic!("Err:{:#?}", pev); + panic!("Err:{pev:#?}"); } Some(contains_string) => { - let full_err = format!("{:#?}", pev); + let full_err = format!("{pev:#?}"); assert!( full_err.contains(contains_string), - "Expected error containing {}, instead got {}", - contains_string, - full_err + "Expected error containing {contains_string}, instead got {full_err}" ); } }, diff --git a/crates/nu-plugin/src/plugin/declaration.rs b/crates/nu-plugin/src/plugin/declaration.rs index 72182e1ee7..d03e3f15d9 100644 --- a/crates/nu-plugin/src/plugin/declaration.rs +++ b/crates/nu-plugin/src/plugin/declaration.rs @@ -63,7 +63,7 @@ impl Command for PluginDeclaration { let decl = engine_state.get_decl(call.decl_id); ShellError::GenericError( format!("Unable to spawn plugin for {}", decl.name()), - format!("{}", err), + format!("{err}"), Some(call.head), None, Vec::new(), @@ -87,7 +87,7 @@ impl Command for PluginDeclaration { "Plugin {} can not handle the custom value {}", self.name, custom_value_name ), - format!("custom value {}", custom_value_name), + format!("custom value {custom_value_name}"), Some(span), None, Vec::new(), diff --git a/crates/nu-plugin/src/plugin/mod.rs b/crates/nu-plugin/src/plugin/mod.rs index 4fd3e46d0a..9f2d8ea0e6 100644 --- a/crates/nu-plugin/src/plugin/mod.rs +++ b/crates/nu-plugin/src/plugin/mod.rs @@ -130,11 +130,11 @@ pub fn get_signature( format!("Can't find {prog_name}, please make sure that {prog_name} is in PATH.") } _ => { - format!("Error spawning child process: {}", err) + format!("Error spawning child process: {err}") } }, _ => { - format!("Error spawning child process: {}", err) + format!("Error spawning child process: {err}") } }; @@ -173,7 +173,7 @@ pub fn get_signature( match child.wait() { Ok(_) => Ok(signatures), - Err(err) => Err(ShellError::PluginFailedToLoad(format!("{}", err))), + Err(err) => Err(ShellError::PluginFailedToLoad(format!("{err}"))), } } @@ -319,7 +319,7 @@ fn print_help(plugin: &mut impl Plugin, encoder: impl PluginEncoder) { }) .and_then(|_| { let flags = get_flags_section(signature); - write!(help, "{}", flags) + write!(help, "{flags}") }) .and_then(|_| writeln!(help, "\nParameters:")) .and_then(|_| { @@ -360,11 +360,11 @@ fn print_help(plugin: &mut impl Plugin, encoder: impl PluginEncoder) { .and_then(|_| writeln!(help, "======================")); if res.is_err() { - println!("{:?}", res) + println!("{res:?}") } }); - println!("{}", help) + println!("{help}") } pub fn get_plugin_encoding(child_stdout: &mut ChildStdout) -> Result { diff --git a/crates/nu-plugin/src/protocol/mod.rs b/crates/nu-plugin/src/protocol/mod.rs index e80e13e7c4..78bcee1b7c 100644 --- a/crates/nu-plugin/src/protocol/mod.rs +++ b/crates/nu-plugin/src/protocol/mod.rs @@ -60,13 +60,13 @@ impl From for LabeledError { LabeledError { label, msg, span } } ShellError::CantConvert(expected, input, span, _help) => LabeledError { - label: format!("Can't convert to {}", expected), - msg: format!("can't convert {} to {}", expected, input), + label: format!("Can't convert to {expected}"), + msg: format!("can't convert {expected} to {input}"), span: Some(span), }, ShellError::DidYouMean(suggestion, span) => LabeledError { label: "Name not found".into(), - msg: format!("did you mean '{}'", suggestion), + msg: format!("did you mean '{suggestion}'"), span: Some(span), }, ShellError::PluginFailedToLoad(msg) => LabeledError { diff --git a/crates/nu-plugin/src/protocol/plugin_custom_value.rs b/crates/nu-plugin/src/protocol/plugin_custom_value.rs index dbde579909..6bec15b240 100644 --- a/crates/nu-plugin/src/protocol/plugin_custom_value.rs +++ b/crates/nu-plugin/src/protocol/plugin_custom_value.rs @@ -56,7 +56,7 @@ impl CustomValue for PluginCustomValue { "Unable to spawn plugin for {} to get base value", self.source ), - format!("{}", err), + format!("{err}"), Some(span), None, Vec::new(), @@ -85,7 +85,7 @@ impl CustomValue for PluginCustomValue { "Unable to decode call for {} to get base value", self.source ), - format!("{}", err), + format!("{err}"), Some(span), None, Vec::new(), diff --git a/crates/nu-pretty-hex/src/pretty_hex.rs b/crates/nu-pretty-hex/src/pretty_hex.rs index 0aeafc16c3..a61eb3dd24 100644 --- a/crates/nu-pretty-hex/src/pretty_hex.rs +++ b/crates/nu-pretty-hex/src/pretty_hex.rs @@ -246,7 +246,7 @@ where style.suffix() )?; } else { - write!(writer, "{}", replacement_char,)?; + write!(writer, "{replacement_char}",)?; } } } diff --git a/crates/nu-protocol/src/ast/cell_path.rs b/crates/nu-protocol/src/ast/cell_path.rs index 3b0826b786..07d5a14235 100644 --- a/crates/nu-protocol/src/ast/cell_path.rs +++ b/crates/nu-protocol/src/ast/cell_path.rs @@ -34,7 +34,7 @@ impl CellPath { } match elem { PathMember::Int { val, .. } => { - let _ = write!(output, "{}", val); + let _ = write!(output, "{val}"); } PathMember::String { val, .. } => output.push_str(val), } diff --git a/crates/nu-protocol/src/engine/engine_state.rs b/crates/nu-protocol/src/engine/engine_state.rs index 6f744b02da..fca6df1d65 100644 --- a/crates/nu-protocol/src/engine/engine_state.rs +++ b/crates/nu-protocol/src/engine/engine_state.rs @@ -478,7 +478,7 @@ impl EngineState { || file_name.contains('"') || file_name.contains(' ') { - file_name = format!("`{}`", file_name); + file_name = format!("`{file_name}`"); } serde_json::to_string_pretty(&decl.signature()) @@ -499,7 +499,7 @@ impl EngineState { // Each signature is stored in the plugin file with the shell and signature // This information will be used when loading the plugin // information when nushell starts - format!("register {} {} {}\n\n", file_name, shell_str, signature) + format!("register {file_name} {shell_str} {signature}\n\n") }) .map_err(|err| ShellError::PluginFailedToLoad(err.to_string())) .and_then(|line| { @@ -511,7 +511,7 @@ impl EngineState { plugin_file.flush().map_err(|err| { ShellError::GenericError( "Error flushing plugin file".to_string(), - format! {"{}", err}, + format! {"{err}"}, None, None, Vec::new(), @@ -567,7 +567,7 @@ impl EngineState { pub fn print_contents(&self) { for (contents, _, _) in self.file_contents.iter() { let string = String::from_utf8_lossy(contents); - println!("{}", string); + println!("{string}"); } } diff --git a/crates/nu-protocol/src/shell_error.rs b/crates/nu-protocol/src/shell_error.rs index 65637b674c..89c3d6f49f 100644 --- a/crates/nu-protocol/src/shell_error.rs +++ b/crates/nu-protocol/src/shell_error.rs @@ -944,7 +944,7 @@ Either make sure {0} is a string, or add a 'to_string' entry for it in ENV_CONVE impl From for ShellError { fn from(input: std::io::Error) -> ShellError { - ShellError::IOError(format!("{:?}", input)) + ShellError::IOError(format!("{input:?}")) } } @@ -956,7 +956,7 @@ impl std::convert::From> for ShellError { impl From> for ShellError { fn from(input: Box) -> ShellError { - ShellError::IOError(format!("{:?}", input)) + ShellError::IOError(format!("{input:?}")) } } @@ -1046,8 +1046,7 @@ mod tests { assert_eq!( suggestion.as_deref(), expected_suggestion, - "Expected the following reasoning to hold but it did not: '{}'", - discussion + "Expected the following reasoning to hold but it did not: '{discussion}'" ); } } diff --git a/crates/nu-protocol/src/signature.rs b/crates/nu-protocol/src/signature.rs index 1ac3c3d32e..964e0ae045 100644 --- a/crates/nu-protocol/src/signature.rs +++ b/crates/nu-protocol/src/signature.rs @@ -97,7 +97,7 @@ impl std::fmt::Display for Category { Category::Bits => "bits", }; - write!(f, "{}", msg) + write!(f, "{msg}") } } diff --git a/crates/nu-protocol/src/span.rs b/crates/nu-protocol/src/span.rs index 3daf272134..432452bb17 100644 --- a/crates/nu-protocol/src/span.rs +++ b/crates/nu-protocol/src/span.rs @@ -31,9 +31,7 @@ impl Span { pub fn new(start: usize, end: usize) -> Span { debug_assert!( end >= start, - "Can't create a Span whose end < start, start={}, end={}", - start, - end + "Can't create a Span whose end < start, start={start}, end={end}" ); Span { start, end } diff --git a/crates/nu-protocol/src/syntax_shape.rs b/crates/nu-protocol/src/syntax_shape.rs index 61cb93b5b2..fb96d45e66 100644 --- a/crates/nu-protocol/src/syntax_shape.rs +++ b/crates/nu-protocol/src/syntax_shape.rs @@ -178,14 +178,14 @@ impl Display for SyntaxShape { if let Some(args) = args { let arg_vec: Vec<_> = args.iter().map(|x| x.to_string()).collect(); let arg_string = arg_vec.join(", "); - write!(f, "closure({})", arg_string) + write!(f, "closure({arg_string})") } else { write!(f, "closure()") } } SyntaxShape::Binary => write!(f, "binary"), SyntaxShape::Table => write!(f, "table"), - SyntaxShape::List(x) => write!(f, "list<{}>", x), + SyntaxShape::List(x) => write!(f, "list<{x}>"), SyntaxShape::Record => write!(f, "record"), SyntaxShape::Filesize => write!(f, "filesize"), SyntaxShape::Duration => write!(f, "duration"), @@ -199,11 +199,11 @@ impl Display for SyntaxShape { SyntaxShape::Expression => write!(f, "expression"), SyntaxShape::Boolean => write!(f, "bool"), SyntaxShape::Error => write!(f, "error"), - SyntaxShape::Custom(x, _) => write!(f, "custom<{}>", x), + SyntaxShape::Custom(x, _) => write!(f, "custom<{x}>"), SyntaxShape::OneOf(list) => { let arg_vec: Vec<_> = list.iter().map(|x| x.to_string()).collect(); let arg_string = arg_vec.join(", "); - write!(f, "one_of({})", arg_string) + write!(f, "one_of({arg_string})") } SyntaxShape::Nothing => write!(f, "nothing"), } diff --git a/crates/nu-protocol/src/ty.rs b/crates/nu-protocol/src/ty.rs index d607662e1e..f3865b2254 100644 --- a/crates/nu-protocol/src/ty.rs +++ b/crates/nu-protocol/src/ty.rs @@ -116,7 +116,7 @@ impl Display for Type { "record<{}>", fields .iter() - .map(|(x, y)| format!("{}: {}", x, y)) + .map(|(x, y)| format!("{x}: {y}")) .collect::>() .join(", "), ) @@ -131,13 +131,13 @@ impl Display for Type { "table<{}>", columns .iter() - .map(|(x, y)| format!("{}: {}", x, y)) + .map(|(x, y)| format!("{x}: {y}")) .collect::>() .join(", ") ) } } - Type::List(l) => write!(f, "list<{}>", l), + Type::List(l) => write!(f, "list<{l}>"), Type::Nothing => write!(f, "nothing"), Type::Number => write!(f, "number"), Type::String => write!(f, "string"), @@ -145,7 +145,7 @@ impl Display for Type { Type::Any => write!(f, "any"), Type::Error => write!(f, "error"), Type::Binary => write!(f, "binary"), - Type::Custom(custom) => write!(f, "{}", custom), + Type::Custom(custom) => write!(f, "{custom}"), Type::Signature => write!(f, "signature"), } } diff --git a/crates/nu-protocol/src/value/mod.rs b/crates/nu-protocol/src/value/mod.rs index 7939d45fa0..07c45015d8 100644 --- a/crates/nu-protocol/src/value/mod.rs +++ b/crates/nu-protocol/src/value/mod.rs @@ -538,11 +538,11 @@ impl Value { }; collected.into_string(separator, config) } - Value::Block { val, .. } => format!("", val), - Value::Closure { val, .. } => format!("", val), + Value::Block { val, .. } => format!(""), + Value::Closure { val, .. } => format!(""), Value::Nothing { .. } => String::new(), - Value::Error { error } => format!("{:?}", error), - Value::Binary { val, .. } => format!("{:?}", val), + Value::Error { error } => format!("{error:?}"), + Value::Binary { val, .. } => format!("{val:?}"), Value::CellPath { val, .. } => val.into_string(), Value::CustomValue { val, .. } => val.value_string(), } @@ -584,13 +584,13 @@ impl Value { ), Value::LazyRecord { val, .. } => match val.collect() { Ok(val) => val.into_abbreviated_string(config), - Err(error) => format!("{:?}", error), + Err(error) => format!("{error:?}"), }, - Value::Block { val, .. } => format!("", val), - Value::Closure { val, .. } => format!("", val), + Value::Block { val, .. } => format!(""), + Value::Closure { val, .. } => format!(""), Value::Nothing { .. } => String::new(), - Value::Error { error } => format!("{:?}", error), - Value::Binary { val, .. } => format!("{:?}", val), + Value::Error { error } => format!("{error:?}"), + Value::Binary { val, .. } => format!("{val:?}"), Value::CellPath { val, .. } => val.into_string(), Value::CustomValue { val, .. } => val.value_string(), } @@ -598,7 +598,7 @@ impl Value { /// Convert Value into a debug string pub fn debug_value(&self) -> String { - format!("{:#?}", self) + format!("{self:#?}") } /// Convert Value into string. Note that Streams will be consumed. @@ -609,7 +609,7 @@ impl Value { Value::Float { val, .. } => val.to_string(), Value::Filesize { val, .. } => format_filesize_from_conf(*val, config), Value::Duration { val, .. } => format_duration(*val), - Value::Date { val, .. } => format!("{:?}", val), + Value::Date { val, .. } => format!("{val:?}"), Value::Range { val, .. } => { format!( "{}..{}", @@ -635,13 +635,13 @@ impl Value { ), Value::LazyRecord { val, .. } => match val.collect() { Ok(val) => val.debug_string(separator, config), - Err(error) => format!("{:?}", error), + Err(error) => format!("{error:?}"), }, - Value::Block { val, .. } => format!("", val), - Value::Closure { val, .. } => format!("", val), + Value::Block { val, .. } => format!(""), + Value::Closure { val, .. } => format!(""), Value::Nothing { .. } => String::new(), - Value::Error { error } => format!("{:?}", error), - Value::Binary { val, .. } => format!("{:?}", val), + Value::Error { error } => format!("{error:?}"), + Value::Binary { val, .. } => format!("{val:?}"), Value::CellPath { val, .. } => val.into_string(), Value::CustomValue { val, .. } => val.value_string(), } @@ -3266,16 +3266,16 @@ pub enum TimePeriod { impl TimePeriod { pub fn to_text(self) -> Cow<'static, str> { match self { - Self::Nanos(n) => format!("{} ns", n).into(), - Self::Micros(n) => format!("{} µs", n).into(), - Self::Millis(n) => format!("{} ms", n).into(), - Self::Seconds(n) => format!("{} sec", n).into(), - Self::Minutes(n) => format!("{} min", n).into(), - Self::Hours(n) => format!("{} hr", n).into(), - Self::Days(n) => format!("{} day", n).into(), - Self::Weeks(n) => format!("{} wk", n).into(), - Self::Months(n) => format!("{} month", n).into(), - Self::Years(n) => format!("{} yr", n).into(), + Self::Nanos(n) => format!("{n} ns").into(), + Self::Micros(n) => format!("{n} µs").into(), + Self::Millis(n) => format!("{n} ms").into(), + Self::Seconds(n) => format!("{n} sec").into(), + Self::Minutes(n) => format!("{n} min").into(), + Self::Hours(n) => format!("{n} hr").into(), + Self::Days(n) => format!("{n} day").into(), + Self::Weeks(n) => format!("{n} wk").into(), + Self::Months(n) => format!("{n} month").into(), + Self::Years(n) => format!("{n} yr").into(), } } } @@ -3489,13 +3489,13 @@ pub fn format_filesize( let locale_byte = adj_byte.get_value() as u64; let locale_byte_string = locale_byte.to_formatted_string(&locale); let locale_signed_byte_string = if num_bytes.is_negative() { - format!("-{}", locale_byte_string) + format!("-{locale_byte_string}") } else { locale_byte_string }; if filesize_format_var.1 == "auto" { - format!("{} B", locale_signed_byte_string) + format!("{locale_signed_byte_string} B") } else { locale_signed_byte_string } diff --git a/crates/nu-table/examples/table_demo.rs b/crates/nu-table/examples/table_demo.rs index a420eb6e02..46d9b68cc2 100644 --- a/crates/nu-table/examples/table_demo.rs +++ b/crates/nu-table/examples/table_demo.rs @@ -38,10 +38,10 @@ fn main() { // Capture the table as a string let output_table = table .draw(table_cfg, width) - .unwrap_or_else(|| format!("Couldn't fit table into {} columns!", width)); + .unwrap_or_else(|| format!("Couldn't fit table into {width} columns!")); // Draw the table - println!("{}", output_table) + println!("{output_table}") } fn make_table_data() -> (Vec<&'static str>, Vec<&'static str>) { diff --git a/crates/nu-term-grid/examples/grid_demo.rs b/crates/nu-term-grid/examples/grid_demo.rs index a9ef426790..4f346d888b 100644 --- a/crates/nu-term-grid/examples/grid_demo.rs +++ b/crates/nu-term-grid/examples/grid_demo.rs @@ -23,7 +23,7 @@ fn main() { } if let Some(grid_display) = grid.fit_into_width(80) { - println!("{}", grid_display); + println!("{grid_display}"); } else { println!("Couldn't fit grid into 80 columns!"); } diff --git a/crates/nu-test-support/src/commands.rs b/crates/nu-test-support/src/commands.rs index bdc7808b4a..61930da1b6 100644 --- a/crates/nu-test-support/src/commands.rs +++ b/crates/nu-test-support/src/commands.rs @@ -33,7 +33,7 @@ pub fn ensure_binary_present(package: &str) { .read_to_string(&mut buffer) .expect("failed to read cargo build stderr"); if !buffer.is_empty() { - println!("=== cargo build stderr\n{}", buffer); + println!("=== cargo build stderr\n{buffer}"); } } diff --git a/crates/nu-test-support/src/playground/director.rs b/crates/nu-test-support/src/playground/director.rs index 5c5554bf7f..d70b00316a 100644 --- a/crates/nu-test-support/src/playground/director.rs +++ b/crates/nu-test-support/src/playground/director.rs @@ -95,7 +95,7 @@ impl Executable for Director { if !commands.is_empty() { commands.push_str("| "); } - let _ = writeln!(commands, "{}", pipeline); + let _ = writeln!(commands, "{pipeline}"); } } @@ -104,7 +104,7 @@ impl Executable for Director { .stdout(Stdio::piped()) // .stdin(Stdio::piped()) .stderr(Stdio::piped()) - .arg(format!("-c '{}'", commands)) + .arg(format!("-c '{commands}'")) .spawn() .expect("It should be possible to run tests"); diff --git a/crates/nu-test-support/src/playground/matchers.rs b/crates/nu-test-support/src/playground/matchers.rs index d167a8e41c..3071a9a20f 100644 --- a/crates/nu-test-support/src/playground/matchers.rs +++ b/crates/nu-test-support/src/playground/matchers.rs @@ -49,12 +49,11 @@ impl CheckerMatchers for Play { None => return Ok(()), }; let actual = - str::from_utf8(actual).map_err(|_| format!("{} was not utf8 encoded", description))?; + str::from_utf8(actual).map_err(|_| format!("{description} was not utf8 encoded"))?; if actual != *out { return Err(format!( - "not equal:\n actual: {}\n expected: {}\n\n", - actual, out + "not equal:\n actual: {actual}\n expected: {out}\n\n" )); } @@ -77,7 +76,7 @@ impl Matcher for Play { impl<'a> Matcher<&'a mut Director> for Play { fn matches(&self, director: &'a mut Director) -> MatchResult { if director.executable().is_none() { - return Err(format!("no such process {}", director)); + return Err(format!("no such process {director}")); } let res = director.execute(); @@ -89,7 +88,7 @@ impl<'a> Matcher<&'a mut Director> for Play { return self.output(out); } - Err(format!("could not exec process {}: {:?}", director, err)) + Err(format!("could not exec process {director}: {err:?}")) } } } diff --git a/crates/nu_plugin_example/src/example.rs b/crates/nu_plugin_example/src/example.rs index bc97c862de..75df43f4d7 100644 --- a/crates/nu_plugin_example/src/example.rs +++ b/crates/nu_plugin_example/src/example.rs @@ -12,8 +12,8 @@ impl Example { // Note. When debugging your plugin, you may want to print something to the console // Use the eprintln macro to print your messages. Trying to print to stdout will // cause a decoding error for your message - eprintln!("Calling test {} signature", index); - eprintln!("value received {:?}", input); + eprintln!("Calling test {index} signature"); + eprintln!("value received {input:?}"); // To extract the arguments from the Call object you can use the functions req, has_flag, // opt, rest, and get_flag @@ -30,19 +30,19 @@ impl Example { let rest: Vec = call.rest(3)?; eprintln!("Required values"); - eprintln!("a: {:}", a); - eprintln!("b: {:}", b); - eprintln!("flag: {:}", flag); - eprintln!("rest: {:?}", rest); + eprintln!("a: {a:}"); + eprintln!("b: {b:}"); + eprintln!("flag: {flag:}"); + eprintln!("rest: {rest:?}"); if let Some(v) = opt { - eprintln!("Found optional value opt: {:}", v) + eprintln!("Found optional value opt: {v:}") } else { eprintln!("No optional value found") } if let Some(v) = named { - eprintln!("Named value: {:?}", v) + eprintln!("Named value: {v:?}") } else { eprintln!("No named value found") } diff --git a/crates/nu_plugin_gstat/src/gstat.rs b/crates/nu_plugin_gstat/src/gstat.rs index c6333af306..f54d141b5a 100644 --- a/crates/nu_plugin_gstat/src/gstat.rs +++ b/crates/nu_plugin_gstat/src/gstat.rs @@ -385,7 +385,7 @@ impl Stats { if let Ok(commit) = head.peel_to_commit() { let mut id = String::new(); for byte in &commit.id().as_bytes()[..4] { - write!(&mut id, "{:x}", byte).unwrap(); + write!(&mut id, "{byte:x}").unwrap(); } id } else { diff --git a/crates/nu_plugin_inc/src/inc.rs b/crates/nu_plugin_inc/src/inc.rs index a8c1c749c9..1955782b1c 100644 --- a/crates/nu_plugin_inc/src/inc.rs +++ b/crates/nu_plugin_inc/src/inc.rs @@ -121,7 +121,7 @@ impl Inc { x => { let msg = x.as_string().map_err(|e| LabeledError { label: "Unable to extract string".into(), - msg: format!("value cannot be converted to string {:?} - {}", x, e), + msg: format!("value cannot be converted to string {x:?} - {e}"), span: Some(head), })?; diff --git a/crates/nu_plugin_query/src/query_web.rs b/crates/nu_plugin_query/src/query_web.rs index af35b0b7a4..60e14e2d6b 100644 --- a/crates/nu_plugin_query/src/query_web.rs +++ b/crates/nu_plugin_query/src/query_web.rs @@ -174,7 +174,7 @@ fn retrieve_table(mut table: WebTable, columns: &Value, span: Span) -> Value { let mut vals = vec![]; for row in &table_with_no_empties { for (counter, cell) in row.iter().enumerate() { - cols.push(format!("column{}", counter)); + cols.push(format!("column{counter}")); vals.push(Value::string(cell.to_string(), span)) } } @@ -258,7 +258,7 @@ fn execute_selector_query( Value::string( selection .text() - .fold("".to_string(), |acc, x| format!("{}{}", acc, x)), + .fold("".to_string(), |acc, x| format!("{acc}{x}")), span, ) }) diff --git a/crates/nu_plugin_query/src/web_tables.rs b/crates/nu_plugin_query/src/web_tables.rs index f38091c623..db175c6b8c 100644 --- a/crates/nu_plugin_query/src/web_tables.rs +++ b/crates/nu_plugin_query/src/web_tables.rs @@ -32,7 +32,7 @@ impl WebTable { /// Finds the table in `html` with an id of `id`. pub fn find_by_id(html: &str, id: &str) -> Option { let html = Html::parse_fragment(html); - let selector = format!("table#{}", id); + let selector = format!("table#{id}"); ScraperSelector::parse(&selector) .ok() .as_ref() diff --git a/src/command.rs b/src/command.rs index 29accfd519..59660c06ed 100644 --- a/src/command.rs +++ b/src/command.rs @@ -157,7 +157,7 @@ pub(crate) fn parse_commandline_args( if call.has_flag("version") { let version = env!("CARGO_PKG_VERSION").to_string(); let _ = std::panic::catch_unwind(move || { - stdout_write_all_and_flush(format!("{}\n", version)) + stdout_write_all_and_flush(format!("{version}\n")) }); std::process::exit(0); @@ -190,7 +190,7 @@ pub(crate) fn parse_commandline_args( &mut stack, true, ); - print!("{}", full_help); + print!("{full_help}"); std::process::exit(1); } diff --git a/src/config_files.rs b/src/config_files.rs index 15dd03f576..6b1e2bbd05 100644 --- a/src/config_files.rs +++ b/src/config_files.rs @@ -39,7 +39,7 @@ pub(crate) fn read_config_file( // Create config directory if it does not exist if !config_path.exists() { if let Err(err) = std::fs::create_dir_all(&config_path) { - eprintln!("Failed to create config directory: {}", err); + eprintln!("Failed to create config directory: {err}"); return; } } @@ -73,7 +73,7 @@ pub(crate) fn read_config_file( match answer.to_lowercase().trim() { "y" | "" => { if let Ok(mut output) = File::create(&config_path) { - if write!(output, "{}", config_file).is_ok() { + if write!(output, "{config_file}").is_ok() { let config_type = if is_env_config { "Environment config" } else { @@ -93,10 +93,7 @@ pub(crate) fn read_config_file( return; } } else { - eprintln!( - "Unable to create {}, sourcing default file instead", - config_file - ); + eprintln!("Unable to create {config_file}, sourcing default file instead"); eval_default_config(engine_state, stack, config_file, is_env_config); return; } diff --git a/src/logger.rs b/src/logger.rs index 7ab043a0ae..9a1c040503 100644 --- a/src/logger.rs +++ b/src/logger.rs @@ -40,7 +40,7 @@ pub fn logger( LogTarget::File => { let pid = std::process::id(); let mut path = std::env::temp_dir(); - path.push(format!("nu-{}.log", pid)); + path.push(format!("nu-{pid}.log")); set_write_logger(level, config, &path) } diff --git a/src/test_bins.rs b/src/test_bins.rs index abae51966e..fa5cb0050f 100644 --- a/src/test_bins.rs +++ b/src/test_bins.rs @@ -16,9 +16,9 @@ pub fn echo_env(to_stdout: bool) { for arg in args { if let Ok(v) = std::env::var(arg) { if to_stdout { - println!("{}", v); + println!("{v}"); } else { - eprintln!("{}", v); + eprintln!("{v}"); } } } @@ -42,7 +42,7 @@ pub fn meow() { for arg in args.iter().skip(1) { let contents = std::fs::read_to_string(arg).expect("Expected a filepath"); - println!("{}", contents); + println!("{contents}"); } } @@ -66,7 +66,7 @@ pub fn relay() { } pub fn nonu() { - args().iter().skip(1).for_each(|arg| print!("{}", arg)); + args().iter().skip(1).for_each(|arg| print!("{arg}")); } pub fn repeater() { @@ -79,7 +79,7 @@ pub fn repeater() { let count: u64 = count.parse().expect("can't convert count to number"); for _ in 0..count { - let _ = write!(stdout, "{}", letter); + let _ = write!(stdout, "{letter}"); } let _ = stdout.flush(); } @@ -91,7 +91,7 @@ pub fn iecho() { .iter() .skip(1) .cycle() - .try_for_each(|v| writeln!(stdout, "{}", v)); + .try_for_each(|v| writeln!(stdout, "{v}")); } pub fn fail() { @@ -116,7 +116,7 @@ pub fn chop() { &given[..to] }; - if let Err(_e) = writeln!(stdout, "{}", chopped) { + if let Err(_e) = writeln!(stdout, "{chopped}") { break; } } @@ -136,7 +136,7 @@ fn outcome_err( } fn outcome_ok(msg: String) -> ! { - println!("{}", msg); + println!("{msg}"); std::process::exit(0); } @@ -194,7 +194,7 @@ pub fn nu_repl() { let mut working_set = StateWorkingSet::new(&engine_state); let (block, err) = parse( &mut working_set, - Some(&format!("line{}", i)), + Some(&format!("line{i}")), line.as_bytes(), false, &[], @@ -248,7 +248,7 @@ fn did_chop_arguments() -> bool { &arg[..to] }; - println!("{}", chopped); + println!("{chopped}"); } return true; diff --git a/src/tests.rs b/src/tests.rs index 125ce12f1b..2d14157085 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -34,7 +34,7 @@ pub fn run_test_with_env(input: &str, expected: &str, env: &HashMap<&str, &str>) let mut cmd = Command::cargo_bin("nu")?; cmd.arg(name).envs(env); - writeln!(file, "{}", input)?; + writeln!(file, "{input}")?; run_cmd_and_assert(cmd, expected) } @@ -51,7 +51,7 @@ pub fn run_test(input: &str, expected: &str) -> TestResult { std::env::current_dir().expect("Can't get current dir"), ); - writeln!(file, "{}", input)?; + writeln!(file, "{input}")?; run_cmd_and_assert(cmd, expected) } @@ -63,8 +63,8 @@ fn run_cmd_and_assert(mut cmd: Command, expected: &str) -> TestResult { let stderr = String::from_utf8_lossy(&output.stderr).to_string(); let stdout = String::from_utf8_lossy(&output.stdout).to_string(); - println!("stdout: {}", stdout); - println!("stderr: {}", stderr); + println!("stdout: {stdout}"); + println!("stderr: {stderr}"); assert!(output.status.success()); @@ -81,15 +81,15 @@ pub fn run_test_contains(input: &str, expected: &str) -> TestResult { let mut cmd = Command::cargo_bin("nu")?; cmd.arg(name); - writeln!(file, "{}", input)?; + writeln!(file, "{input}")?; let output = cmd.output()?; let stderr = String::from_utf8_lossy(&output.stderr).to_string(); let stdout = String::from_utf8_lossy(&output.stdout).to_string(); - println!("stdout: {}", stdout); - println!("stderr: {}", stderr); + println!("stdout: {stdout}"); + println!("stderr: {stderr}"); assert!(output.status.success()); @@ -110,15 +110,15 @@ pub fn fail_test(input: &str, expected: &str) -> TestResult { std::env::current_dir().expect("Can't get current dir"), ); - writeln!(file, "{}", input)?; + writeln!(file, "{input}")?; let output = cmd.output()?; let stderr = String::from_utf8_lossy(&output.stderr).to_string(); let stdout = String::from_utf8_lossy(&output.stdout).to_string(); - println!("stdout: {}", stdout); - println!("stderr: {}", stderr); + println!("stdout: {stdout}"); + println!("stderr: {stderr}"); assert!(!stderr.is_empty() && stderr.contains(expected)); diff --git a/src/tests/test_config_path.rs b/src/tests/test_config_path.rs index da661a476b..4553408d09 100644 --- a/src/tests/test_config_path.rs +++ b/src/tests/test_config_path.rs @@ -25,14 +25,14 @@ fn test_alternate_config_path() { nu_path::canonicalize_with(config_file, &cwd).expect("Could not get config path"); let actual = nu!( cwd: &cwd, - format!("nu --config {:?} -c '$nu.config-path'", config_path) + format!("nu --config {config_path:?} -c '$nu.config-path'") ); assert_eq!(actual.out, config_path.to_string_lossy().to_string()); let env_path = nu_path::canonicalize_with(env_file, &cwd).expect("Could not get env path"); let actual = nu!( cwd: &cwd, - format!("nu --env-config {:?} -c '$nu.env-path'", env_path) + format!("nu --env-config {env_path:?} -c '$nu.env-path'") ); assert_eq!(actual.out, env_path.to_string_lossy().to_string()); } diff --git a/tests/shell/pipeline/commands/external.rs b/tests/shell/pipeline/commands/external.rs index 64cd742607..da23439b2f 100644 --- a/tests/shell/pipeline/commands/external.rs +++ b/tests/shell/pipeline/commands/external.rs @@ -309,8 +309,8 @@ mod external_words { let actual = nu!( cwd: dirs.test(), pipeline( &format!(r#" - nu --testbin meow {} | from toml | get nu_party_venue - "#, nu_path_argument) + nu --testbin meow {nu_path_argument} | from toml | get nu_party_venue + "#) )); assert_eq!(actual.out, "zion");