Fix easy clippy lints from latest stable (#16053)

1.88.0 was released today, clippy now lints (machine-applicable)
against:
- format strings with empty braces that could be inlined
  - easy win
- `manual_abs_diff`
- returning of a stored result of the last expression.
  - this can be somewhat contentious but touched only a few places
This commit is contained in:
Stefan Holderbach
2025-06-29 17:37:17 +02:00
committed by GitHub
parent 372d576846
commit 9da0f41ebb
102 changed files with 258 additions and 339 deletions

View File

@ -199,7 +199,7 @@ fn bench_record_nested_access(n: usize) -> impl IntoBenchmarks {
let nested_access = ".col".repeat(n); let nested_access = ".col".repeat(n);
bench_command( bench_command(
format!("record_nested_access_{n}"), format!("record_nested_access_{n}"),
format!("$record{} | ignore", nested_access), format!("$record{nested_access} | ignore"),
stack, stack,
engine, engine,
) )
@ -319,7 +319,7 @@ fn bench_eval_par_each(n: usize) -> impl IntoBenchmarks {
let stack = Stack::new(); let stack = Stack::new();
bench_command( bench_command(
format!("eval_par_each_{n}"), format!("eval_par_each_{n}"),
format!("(1..{}) | par-each -t 2 {{|_| 1 }} | ignore", n), format!("(1..{n}) | par-each -t 2 {{|_| 1 }} | ignore"),
stack, stack,
engine, engine,
) )
@ -357,7 +357,7 @@ fn encode_json(row_cnt: usize, col_cnt: usize) -> impl IntoBenchmarks {
let encoder = Rc::new(EncodingType::try_from_bytes(b"json").unwrap()); let encoder = Rc::new(EncodingType::try_from_bytes(b"json").unwrap());
[benchmark_fn( [benchmark_fn(
format!("encode_json_{}_{}", row_cnt, col_cnt), format!("encode_json_{row_cnt}_{col_cnt}"),
move |b| { move |b| {
let encoder = encoder.clone(); let encoder = encoder.clone();
let test_data = test_data.clone(); let test_data = test_data.clone();
@ -377,7 +377,7 @@ fn encode_msgpack(row_cnt: usize, col_cnt: usize) -> impl IntoBenchmarks {
let encoder = Rc::new(EncodingType::try_from_bytes(b"msgpack").unwrap()); let encoder = Rc::new(EncodingType::try_from_bytes(b"msgpack").unwrap());
[benchmark_fn( [benchmark_fn(
format!("encode_msgpack_{}_{}", row_cnt, col_cnt), format!("encode_msgpack_{row_cnt}_{col_cnt}"),
move |b| { move |b| {
let encoder = encoder.clone(); let encoder = encoder.clone();
let test_data = test_data.clone(); let test_data = test_data.clone();
@ -399,7 +399,7 @@ fn decode_json(row_cnt: usize, col_cnt: usize) -> impl IntoBenchmarks {
encoder.encode(&test_data, &mut res).unwrap(); encoder.encode(&test_data, &mut res).unwrap();
[benchmark_fn( [benchmark_fn(
format!("decode_json_{}_{}", row_cnt, col_cnt), format!("decode_json_{row_cnt}_{col_cnt}"),
move |b| { move |b| {
let res = res.clone(); let res = res.clone();
b.iter(move || { b.iter(move || {
@ -422,7 +422,7 @@ fn decode_msgpack(row_cnt: usize, col_cnt: usize) -> impl IntoBenchmarks {
encoder.encode(&test_data, &mut res).unwrap(); encoder.encode(&test_data, &mut res).unwrap();
[benchmark_fn( [benchmark_fn(
format!("decode_msgpack_{}_{}", row_cnt, col_cnt), format!("decode_msgpack_{row_cnt}_{col_cnt}"),
move |b| { move |b| {
let res = res.clone(); let res = res.clone();
b.iter(move || { b.iter(move || {

View File

@ -118,7 +118,7 @@ fn get_suggestions_by_value(
|| s.chars() || s.chars()
.any(|c: char| !(c.is_ascii_alphabetic() || ['_', '-'].contains(&c))) .any(|c: char| !(c.is_ascii_alphabetic() || ['_', '-'].contains(&c)))
{ {
format!("{:?}", s) format!("{s:?}")
} else { } else {
s s
}; };

View File

@ -52,7 +52,7 @@ impl CommandCompletion {
continue; continue;
}; };
let value = if matched_internal(&name) { let value = if matched_internal(&name) {
format!("^{}", name) format!("^{name}")
} else { } else {
name.clone() name.clone()
}; };

View File

@ -176,7 +176,7 @@ impl NuCompleter {
&mut working_set, &mut working_set,
Some("completer"), Some("completer"),
// Add a placeholder `a` to the end // Add a placeholder `a` to the end
format!("{}a", line).as_bytes(), format!("{line}a").as_bytes(),
false, false,
); );
self.fetch_completions_by_block(block, &working_set, pos, offset, line, true) self.fetch_completions_by_block(block, &working_set, pos, offset, line, true)
@ -850,7 +850,7 @@ mod completer_tests {
for (line, has_result, begins_with, expected_values) in dataset { for (line, has_result, begins_with, expected_values) in dataset {
let result = completer.fetch_completions_at(line, line.len()); let result = completer.fetch_completions_at(line, line.len());
// Test whether the result is empty or not // Test whether the result is empty or not
assert_eq!(!result.is_empty(), has_result, "line: {}", line); assert_eq!(!result.is_empty(), has_result, "line: {line}");
// Test whether the result begins with the expected value // Test whether the result begins with the expected value
result result
@ -865,8 +865,7 @@ mod completer_tests {
.filter(|x| *x) .filter(|x| *x)
.count(), .count(),
expected_values.len(), expected_values.len(),
"line: {}", "line: {line}"
line
); );
} }
} }

View File

@ -314,7 +314,7 @@ pub fn escape_path(path: String) -> String {
if path.contains('\'') { if path.contains('\'') {
// decide to use double quotes // decide to use double quotes
// Path as Debug will do the escaping for `"`, `\` // Path as Debug will do the escaping for `"`, `\`
format!("{:?}", path) format!("{path:?}")
} else { } else {
format!("'{path}'") format!("'{path}'")
} }

View File

@ -129,7 +129,7 @@ impl Completer for DotNuCompletion {
.take_while(|c| "`'\"".contains(*c)) .take_while(|c| "`'\"".contains(*c))
.collect::<String>(); .collect::<String>();
for path in ["std", "std-rfc"] { for path in ["std", "std-rfc"] {
let path = format!("{}{}", surround_prefix, path); let path = format!("{surround_prefix}{path}");
matcher.add( matcher.add(
path.clone(), path.clone(),
FileSuggestion { FileSuggestion {
@ -146,7 +146,7 @@ impl Completer for DotNuCompletion {
for sub_vp_id in sub_paths { for sub_vp_id in sub_paths {
let (path, sub_vp) = working_set.get_virtual_path(*sub_vp_id); let (path, sub_vp) = working_set.get_virtual_path(*sub_vp_id);
let path = path let path = path
.strip_prefix(&format!("{}/", base_dir)) .strip_prefix(&format!("{base_dir}/"))
.unwrap_or(path) .unwrap_or(path)
.to_string(); .to_string();
matcher.add( matcher.add(

View File

@ -239,7 +239,7 @@ fn escape_special_vscode_bytes(input: &str) -> Result<String, ShellError> {
match byte { match byte {
// Escape bytes below 0x20 // Escape bytes below 0x20
b if b < 0x20 => format!("\\x{:02X}", byte).into_bytes(), b if b < 0x20 => format!("\\x{byte:02X}").into_bytes(),
// Escape semicolon as \x3B // Escape semicolon as \x3B
b';' => "\\x3B".to_string().into_bytes(), b';' => "\\x3B".to_string().into_bytes(),
// Escape backslash as \\ // Escape backslash as \\
@ -1097,8 +1097,7 @@ fn run_shell_integration_osc633(
// If we're in vscode, run their specific ansi escape sequence. // If we're in vscode, run their specific ansi escape sequence.
// This is helpful for ctrl+g to change directories in the terminal. // This is helpful for ctrl+g to change directories in the terminal.
run_ansi_sequence(&format!( run_ansi_sequence(&format!(
"{}{}{}", "{VSCODE_CWD_PROPERTY_MARKER_PREFIX}{path}{VSCODE_CWD_PROPERTY_MARKER_SUFFIX}"
VSCODE_CWD_PROPERTY_MARKER_PREFIX, path, VSCODE_CWD_PROPERTY_MARKER_SUFFIX
)); ));
perf!( perf!(
@ -1114,10 +1113,7 @@ fn run_shell_integration_osc633(
//OSC 633 ; E ; <commandline> [; <nonce] ST - Explicitly set the command line with an optional nonce. //OSC 633 ; E ; <commandline> [; <nonce] ST - Explicitly set the command line with an optional nonce.
run_ansi_sequence(&format!( run_ansi_sequence(&format!(
"{}{}{}", "{VSCODE_COMMANDLINE_MARKER_PREFIX}{replaced_cmd_text}{VSCODE_COMMANDLINE_MARKER_SUFFIX}"
VSCODE_COMMANDLINE_MARKER_PREFIX,
replaced_cmd_text,
VSCODE_COMMANDLINE_MARKER_SUFFIX
)); ));
} }
} }
@ -1493,7 +1489,7 @@ mod test_auto_cd {
// Parse the input. It must be an auto-cd operation. // Parse the input. It must be an auto-cd operation.
let op = parse_operation(input.to_string(), &engine_state, &stack).unwrap(); let op = parse_operation(input.to_string(), &engine_state, &stack).unwrap();
let ReplOperation::AutoCd { cwd, target, span } = op else { let ReplOperation::AutoCd { cwd, target, span } = op else {
panic!("'{}' was not parsed into an auto-cd operation", input) panic!("'{input}' was not parsed into an auto-cd operation")
}; };
// Perform the auto-cd operation. // Perform the auto-cd operation.

View File

@ -125,7 +125,7 @@ fn custom_completer_with_options(
global_opts, global_opts,
completions completions
.iter() .iter()
.map(|comp| format!("'{}'", comp)) .map(|comp| format!("'{comp}'"))
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", "), .join(", "),
completer_opts, completer_opts,

View File

@ -188,7 +188,7 @@ fn get_theme_from_asset_file(
Some(t) => t, Some(t) => t,
None => { None => {
return Err(ShellError::TypeMismatch { return Err(ShellError::TypeMismatch {
err_message: format!("Unknown HTML theme '{}'", theme_name), err_message: format!("Unknown HTML theme '{theme_name}'"),
span: theme_span, span: theme_span,
}); });
} }
@ -774,8 +774,7 @@ mod tests {
for key in required_keys { for key in required_keys {
assert!( assert!(
theme_map.contains_key(key), theme_map.contains_key(key),
"Expected theme to contain key '{}'", "Expected theme to contain key '{key}'"
key
); );
} }
} }
@ -792,15 +791,13 @@ mod tests {
if let Err(err) = result { if let Err(err) = result {
assert!( assert!(
matches!(err, ShellError::TypeMismatch { .. }), matches!(err, ShellError::TypeMismatch { .. }),
"Expected TypeMismatch error, got: {:?}", "Expected TypeMismatch error, got: {err:?}"
err
); );
if let ShellError::TypeMismatch { err_message, span } = err { if let ShellError::TypeMismatch { err_message, span } = err {
assert!( assert!(
err_message.contains("doesnt-exist"), err_message.contains("doesnt-exist"),
"Error message should mention theme name, got: {}", "Error message should mention theme name, got: {err_message}"
err_message
); );
assert_eq!(span.start, 0); assert_eq!(span.start, 0);
assert_eq!(span.end, 13); assert_eq!(span.end, 13);

View File

@ -161,28 +161,28 @@ fn convert_to_smallest_number_type(num: i64, span: Span) -> Value {
let bytes = v.to_ne_bytes(); let bytes = v.to_ne_bytes();
let mut raw_string = "".to_string(); let mut raw_string = "".to_string();
for ch in bytes { for ch in bytes {
raw_string.push_str(&format!("{:08b} ", ch)); raw_string.push_str(&format!("{ch:08b} "));
} }
Value::string(raw_string.trim(), span) Value::string(raw_string.trim(), span)
} else if let Some(v) = num.to_i16() { } else if let Some(v) = num.to_i16() {
let bytes = v.to_ne_bytes(); let bytes = v.to_ne_bytes();
let mut raw_string = "".to_string(); let mut raw_string = "".to_string();
for ch in bytes { for ch in bytes {
raw_string.push_str(&format!("{:08b} ", ch)); raw_string.push_str(&format!("{ch:08b} "));
} }
Value::string(raw_string.trim(), span) Value::string(raw_string.trim(), span)
} else if let Some(v) = num.to_i32() { } else if let Some(v) = num.to_i32() {
let bytes = v.to_ne_bytes(); let bytes = v.to_ne_bytes();
let mut raw_string = "".to_string(); let mut raw_string = "".to_string();
for ch in bytes { for ch in bytes {
raw_string.push_str(&format!("{:08b} ", ch)); raw_string.push_str(&format!("{ch:08b} "));
} }
Value::string(raw_string.trim(), span) Value::string(raw_string.trim(), span)
} else { } else {
let bytes = num.to_ne_bytes(); let bytes = num.to_ne_bytes();
let mut raw_string = "".to_string(); let mut raw_string = "".to_string();
for ch in bytes { for ch in bytes {
raw_string.push_str(&format!("{:08b} ", ch)); raw_string.push_str(&format!("{ch:08b} "));
} }
Value::string(raw_string.trim(), span) Value::string(raw_string.trim(), span)
} }
@ -193,7 +193,7 @@ fn action(input: &Value, _args: &Arguments, span: Span) -> Value {
Value::Binary { val, .. } => { Value::Binary { val, .. } => {
let mut raw_string = "".to_string(); let mut raw_string = "".to_string();
for ch in val { for ch in val {
raw_string.push_str(&format!("{:08b} ", ch)); raw_string.push_str(&format!("{ch:08b} "));
} }
Value::string(raw_string.trim(), span) Value::string(raw_string.trim(), span)
} }
@ -204,7 +204,7 @@ fn action(input: &Value, _args: &Arguments, span: Span) -> Value {
let raw_bytes = val.as_bytes(); let raw_bytes = val.as_bytes();
let mut raw_string = "".to_string(); let mut raw_string = "".to_string();
for ch in raw_bytes { for ch in raw_bytes {
raw_string.push_str(&format!("{:08b} ", ch)); raw_string.push_str(&format!("{ch:08b} "));
} }
Value::string(raw_string.trim(), span) Value::string(raw_string.trim(), span)
} }

View File

@ -296,7 +296,7 @@ fn run(
} else { } else {
let value = stream.into_value(); let value = stream.into_value();
let base_description = value.get_type().to_string(); let base_description = value.get_type().to_string();
Value::string(format!("{} (stream)", base_description), head) Value::string(format!("{base_description} (stream)"), head)
} }
} }
PipelineData::Value(value, ..) => { PipelineData::Value(value, ..) => {

View File

@ -229,7 +229,7 @@ fn make_other_error(value: &Value, throw_span: Option<Span>) -> ShellError {
error: "invalid error format.".into(), error: "invalid error format.".into(),
msg: "`$.label.start` should be smaller than `$.label.end`".into(), msg: "`$.label.start` should be smaller than `$.label.end`".into(),
span: Some(label_span), span: Some(label_span),
help: Some(format!("{} > {}", span_start, span_end)), help: Some(format!("{span_start} > {span_end}")),
inner: vec![], inner: vec![],
}; };
} }

View File

@ -221,23 +221,23 @@ impl std::fmt::Debug for DebuggableValue<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.0 { match self.0 {
Value::Bool { val, .. } => { Value::Bool { val, .. } => {
write!(f, "{:?}", val) write!(f, "{val:?}")
} }
Value::Int { val, .. } => { Value::Int { val, .. } => {
write!(f, "{:?}", val) write!(f, "{val:?}")
} }
Value::Float { val, .. } => { Value::Float { val, .. } => {
write!(f, "{:?}f", val) write!(f, "{val:?}f")
} }
Value::Filesize { val, .. } => { Value::Filesize { val, .. } => {
write!(f, "Filesize({:?})", val) write!(f, "Filesize({val:?})")
} }
Value::Duration { val, .. } => { Value::Duration { val, .. } => {
let duration = std::time::Duration::from_nanos(*val as u64); let duration = std::time::Duration::from_nanos(*val as u64);
write!(f, "Duration({:?})", duration) write!(f, "Duration({duration:?})")
} }
Value::Date { val, .. } => { Value::Date { val, .. } => {
write!(f, "Date({:?})", val) write!(f, "Date({val:?})")
} }
Value::Range { val, .. } => match **val { Value::Range { val, .. } => match **val {
Range::IntRange(range) => match range.end() { Range::IntRange(range) => match range.end() {
@ -280,7 +280,7 @@ impl std::fmt::Debug for DebuggableValue<'_> {
}, },
}, },
Value::String { val, .. } | Value::Glob { val, .. } => { Value::String { val, .. } | Value::Glob { val, .. } => {
write!(f, "{:?}", val) write!(f, "{val:?}")
} }
Value::Record { val, .. } => { Value::Record { val, .. } => {
write!(f, "{{")?; write!(f, "{{")?;
@ -305,22 +305,22 @@ impl std::fmt::Debug for DebuggableValue<'_> {
write!(f, "]") write!(f, "]")
} }
Value::Closure { val, .. } => { Value::Closure { val, .. } => {
write!(f, "Closure({:?})", val) write!(f, "Closure({val:?})")
} }
Value::Nothing { .. } => { Value::Nothing { .. } => {
write!(f, "Nothing") write!(f, "Nothing")
} }
Value::Error { error, .. } => { Value::Error { error, .. } => {
write!(f, "Error({:?})", error) write!(f, "Error({error:?})")
} }
Value::Binary { val, .. } => { Value::Binary { val, .. } => {
write!(f, "Binary({:?})", val) write!(f, "Binary({val:?})")
} }
Value::CellPath { val, .. } => { Value::CellPath { val, .. } => {
write!(f, "CellPath({:?})", val.to_string()) write!(f, "CellPath({:?})", val.to_string())
} }
Value::Custom { val, .. } => { Value::Custom { val, .. } => {
write!(f, "CustomValue({:?})", val) write!(f, "CustomValue({val:?})")
} }
} }
} }

View File

@ -89,7 +89,7 @@ impl Command for Histogram {
"frequency-column-name can't be {}", "frequency-column-name can't be {}",
forbidden_column_names forbidden_column_names
.iter() .iter()
.map(|val| format!("'{}'", val)) .map(|val| format!("'{val}'"))
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", ") .join(", ")
), ),

View File

@ -678,7 +678,7 @@ fn parse_value_from_record_as_u32(
Value::Int { val, .. } => { Value::Int { val, .. } => {
if *val < 0 || *val > u32::MAX as i64 { if *val < 0 || *val > u32::MAX as i64 {
return Err(ShellError::IncorrectValue { return Err(ShellError::IncorrectValue {
msg: format!("incorrect value for {}", col), msg: format!("incorrect value for {col}"),
val_span: *head, val_span: *head,
call_span: *span, call_span: *span,
}); });

View File

@ -368,8 +368,7 @@ fn merge_record(record: &Record, head: Span, span: Span) -> Result<Value, ShellE
if !ALLOWED_SIGNS.contains(&val.as_str()) { if !ALLOWED_SIGNS.contains(&val.as_str()) {
let allowed_signs = ALLOWED_SIGNS.join(", "); let allowed_signs = ALLOWED_SIGNS.join(", ");
return Err(ShellError::IncorrectValue { return Err(ShellError::IncorrectValue {
msg: format!("Invalid sign. Allowed signs are {}", allowed_signs) msg: format!("Invalid sign. Allowed signs are {allowed_signs}").to_string(),
.to_string(),
val_span: sign.span(), val_span: sign.span(),
call_span: head, call_span: head,
}); });

View File

@ -122,8 +122,8 @@ impl Table {
.conn .conn
.query_row(&table_exists_query, [], |row| row.get(0)) .query_row(&table_exists_query, [], |row| row.get(0))
.map_err(|err| ShellError::GenericError { .map_err(|err| ShellError::GenericError {
error: format!("{:#?}", err), error: format!("{err:#?}"),
msg: format!("{:#?}", err), msg: format!("{err:#?}"),
span: None, span: None,
help: None, help: None,
inner: Vec::new(), inner: Vec::new(),
@ -257,7 +257,7 @@ fn insert_in_transaction(
let insert_statement = format!( let insert_statement = format!(
"INSERT INTO [{}] ({}) VALUES ({})", "INSERT INTO [{}] ({}) VALUES ({})",
table_name, table_name,
Itertools::intersperse(val.columns().map(|c| format!("`{}`", c)), ", ".to_string()) Itertools::intersperse(val.columns().map(|c| format!("`{c}`")), ", ".to_string())
.collect::<String>(), .collect::<String>(),
Itertools::intersperse(itertools::repeat_n("?", val.len()), ", ").collect::<String>(), Itertools::intersperse(itertools::repeat_n("?", val.len()), ", ").collect::<String>(),
); );
@ -381,7 +381,7 @@ fn get_columns_with_sqlite_types(
.map(|name| (format!("`{}`", name.0), name.1)) .map(|name| (format!("`{}`", name.0), name.1))
.any(|(name, _)| name == *c) .any(|(name, _)| name == *c)
{ {
columns.push((format!("`{}`", c), nu_value_to_sqlite_type(v)?)); columns.push((format!("`{c}`"), nu_value_to_sqlite_type(v)?));
} }
} }

View File

@ -173,7 +173,7 @@ impl SQLiteDatabase {
filename: String, filename: String,
) -> Result<(), SqliteError> { ) -> Result<(), SqliteError> {
//vacuum main into 'c:\\temp\\foo.db' //vacuum main into 'c:\\temp\\foo.db'
conn.execute(&format!("vacuum main into '{}'", filename), [])?; conn.execute(&format!("vacuum main into '{filename}'"), [])?;
Ok(()) Ok(())
} }

View File

@ -126,10 +126,10 @@ impl Command for ViewSource {
} }
let _ = write!(&mut final_contents, "--{}", n.long); let _ = write!(&mut final_contents, "--{}", n.long);
if let Some(short) = n.short { if let Some(short) = n.short {
let _ = write!(&mut final_contents, "(-{})", short); let _ = write!(&mut final_contents, "(-{short})");
} }
if let Some(arg) = &n.arg { if let Some(arg) = &n.arg {
let _ = write!(&mut final_contents, ": {}", arg); let _ = write!(&mut final_contents, ": {arg}");
} }
final_contents.push(' '); final_contents.push(' ');
} }
@ -146,7 +146,7 @@ impl Command for ViewSource {
let mut c = 0; let mut c = 0;
for (insig, outsig) in type_signatures { for (insig, outsig) in type_signatures {
c += 1; c += 1;
let s = format!("{} -> {}", insig, outsig); let s = format!("{insig} -> {outsig}");
final_contents.push_str(&s); final_contents.push_str(&s);
if c != len { if c != len {
final_contents.push_str(", ") final_contents.push_str(", ")

View File

@ -112,8 +112,8 @@ impl Command for Mktemp {
.map_err(|_| ShellError::NonUtf8 { span })?, .map_err(|_| ShellError::NonUtf8 { span })?,
Err(e) => { Err(e) => {
return Err(ShellError::GenericError { return Err(ShellError::GenericError {
error: format!("{}", e), error: format!("{e}"),
msg: format!("{}", e), msg: format!("{e}"),
span: None, span: None,
help: None, help: None,
inner: vec![], inner: vec![],

View File

@ -198,7 +198,7 @@ impl Command for Open {
let converter = exts_opt.and_then(|exts| { let converter = exts_opt.and_then(|exts| {
exts.iter().find_map(|ext| { exts.iter().find_map(|ext| {
engine_state engine_state
.find_decl(format!("from {}", ext).as_bytes(), &[]) .find_decl(format!("from {ext}").as_bytes(), &[])
.map(|id| (id, ext.to_string())) .map(|id| (id, ext.to_string()))
}) })
}); });
@ -314,7 +314,7 @@ fn extract_extensions(filename: &str) -> Vec<String> {
if current_extension.is_empty() { if current_extension.is_empty() {
current_extension.push_str(part); current_extension.push_str(part);
} else { } else {
current_extension = format!("{}.{}", part, current_extension); current_extension = format!("{part}.{current_extension}");
} }
extensions.push(current_extension.clone()); extensions.push(current_extension.clone());
} }

View File

@ -272,8 +272,8 @@ impl Command for UCp {
uu_cp::Error::NotAllFilesCopied => {} uu_cp::Error::NotAllFilesCopied => {}
_ => { _ => {
return Err(ShellError::GenericError { return Err(ShellError::GenericError {
error: format!("{}", error), error: format!("{error}"),
msg: format!("{}", error), msg: format!("{error}"),
span: None, span: None,
help: None, help: None,
inner: vec![], inner: vec![],
@ -373,7 +373,7 @@ fn parse_and_set_attribute(
"xattr" => &mut attribute.xattr, "xattr" => &mut attribute.xattr,
_ => { _ => {
return Err(ShellError::IncompatibleParametersSingle { return Err(ShellError::IncompatibleParametersSingle {
msg: format!("--preserve flag got an unexpected attribute \"{}\"", val), msg: format!("--preserve flag got an unexpected attribute \"{val}\""),
span: value.span(), span: value.span(),
}); });
} }

View File

@ -77,8 +77,8 @@ impl Command for UMkdir {
for dir in directories { for dir in directories {
if let Err(error) = mkdir(&dir, IS_RECURSIVE, get_mode(), is_verbose) { if let Err(error) = mkdir(&dir, IS_RECURSIVE, get_mode(), is_verbose) {
return Err(ShellError::GenericError { return Err(ShellError::GenericError {
error: format!("{}", error), error: format!("{error}"),
msg: format!("{}", error), msg: format!("{error}"),
span: None, span: None,
help: None, help: None,
inner: vec![], inner: vec![],

View File

@ -195,8 +195,8 @@ impl Command for UMv {
}; };
if let Err(error) = uu_mv::mv(&files, &options) { if let Err(error) = uu_mv::mv(&files, &options) {
return Err(ShellError::GenericError { return Err(ShellError::GenericError {
error: format!("{}", error), error: format!("{error}"),
msg: format!("{}", error), msg: format!("{error}"),
span: None, span: None,
help: None, help: None,
inner: Vec::new(), inner: Vec::new(),

View File

@ -220,7 +220,7 @@ impl Command for UTouch {
inner: Vec::new(), inner: Vec::new(),
}, },
TouchError::InvalidDateFormat(date) => ShellError::IncorrectValue { TouchError::InvalidDateFormat(date) => ShellError::IncorrectValue {
msg: format!("Invalid date: {}", date), msg: format!("Invalid date: {date}"),
val_span: date_span.expect("touch should've been given a date"), val_span: date_span.expect("touch should've been given a date"),
call_span: call.head, call_span: call.head,
}, },

View File

@ -334,7 +334,7 @@ fn closure_variable_warning(
Cow::Owned(s) if s.deref() == "$carapace_completer" => { Cow::Owned(s) if s.deref() == "$carapace_completer" => {
carapace_suggestion.to_string() carapace_suggestion.to_string()
} }
_ => format!("change this to {{ {} }}", span_contents).to_string(), _ => format!("change this to {{ {span_contents} }}").to_string(),
}; };
report_shell_warning( report_shell_warning(

View File

@ -379,10 +379,7 @@ fn merge_records(left: &Record, right: &Record, shared_key: Option<&str>) -> Rec
let k_shared = shared_key == Some(k.as_str()); let k_shared = shared_key == Some(k.as_str());
// Do not output shared join key twice // Do not output shared join key twice
if !(k_seen && k_shared) { if !(k_seen && k_shared) {
record.push( record.push(if k_seen { format!("{k}_") } else { k.clone() }, v.clone());
if k_seen { format!("{}_", k) } else { k.clone() },
v.clone(),
);
} }
} }
record record

View File

@ -212,7 +212,7 @@ impl From<ReadError> for ShellError {
}, },
ReadError::TypeMismatch(marker, span) => ShellError::GenericError { ReadError::TypeMismatch(marker, span) => ShellError::GenericError {
error: "Invalid marker while reading MessagePack data".into(), error: "Invalid marker while reading MessagePack data".into(),
msg: format!("unexpected {:?} in data", marker), msg: format!("unexpected {marker:?} in data"),
span: Some(span), span: Some(span),
help: None, help: None,
inner: vec![], inner: vec![],

View File

@ -167,7 +167,7 @@ fn parse_aligned_columns<'a>(
let headers: Vec<(String, usize)> = indices let headers: Vec<(String, usize)> = indices
.iter() .iter()
.enumerate() .enumerate()
.map(|(i, position)| (format!("column{}", i), *position)) .map(|(i, position)| (format!("column{i}"), *position))
.collect(); .collect();
construct(ls.iter().map(|s| s.to_owned()), headers) construct(ls.iter().map(|s| s.to_owned()), headers)

View File

@ -252,7 +252,7 @@ fn process_xml_parse_error(source: String, err: roxmltree::Error, span: Span) ->
pos, pos,
), ),
roxmltree::Error::UnknownNamespace(prefix, pos) => { roxmltree::Error::UnknownNamespace(prefix, pos) => {
make_xml_error_spanned(format!("Unknown prefix {}", prefix), source, pos) make_xml_error_spanned(format!("Unknown prefix {prefix}"), source, pos)
} }
roxmltree::Error::UnexpectedCloseTag(expected, actual, pos) => make_xml_error_spanned( roxmltree::Error::UnexpectedCloseTag(expected, actual, pos) => make_xml_error_spanned(
format!("Unexpected close tag {actual}, expected {expected}"), format!("Unexpected close tag {actual}, expected {expected}"),

View File

@ -158,27 +158,26 @@ fn convert_yaml_value_to_nu_value(
} }
serde_yaml::Value::Tagged(t) => { serde_yaml::Value::Tagged(t) => {
let tag = &t.tag; let tag = &t.tag;
let value = match &t.value {
match &t.value {
serde_yaml::Value::String(s) => { serde_yaml::Value::String(s) => {
let val = format!("{} {}", tag, s).trim().to_string(); let val = format!("{tag} {s}").trim().to_string();
Value::string(val, span) Value::string(val, span)
} }
serde_yaml::Value::Number(n) => { serde_yaml::Value::Number(n) => {
let val = format!("{} {}", tag, n).trim().to_string(); let val = format!("{tag} {n}").trim().to_string();
Value::string(val, span) Value::string(val, span)
} }
serde_yaml::Value::Bool(b) => { serde_yaml::Value::Bool(b) => {
let val = format!("{} {}", tag, b).trim().to_string(); let val = format!("{tag} {b}").trim().to_string();
Value::string(val, span) Value::string(val, span)
} }
serde_yaml::Value::Null => { serde_yaml::Value::Null => {
let val = format!("{}", tag).trim().to_string(); let val = format!("{tag}").trim().to_string();
Value::string(val, span) Value::string(val, span)
} }
v => convert_yaml_value_to_nu_value(v, span, val_span)?, v => convert_yaml_value_to_nu_value(v, span, val_span)?,
}; }
value
} }
serde_yaml::Value::Null => Value::nothing(span), serde_yaml::Value::Null => Value::nothing(span),
x => unimplemented!("Unsupported YAML case: {:?}", x), x => unimplemented!("Unsupported YAML case: {:?}", x),

View File

@ -50,7 +50,7 @@ fn make_unsupported_input_error(
) -> ShellError { ) -> ShellError {
ShellError::UnsupportedInput { ShellError::UnsupportedInput {
msg: "expected table or record".to_string(), msg: "expected table or record".to_string(),
input: format!("input type: {}", r#type), input: format!("input type: {type}"),
msg_span: head, msg_span: head,
input_span: span, input_span: span,
} }

View File

@ -246,7 +246,7 @@ fn table(
escaped_rows.push(escaped_row); escaped_rows.push(escaped_row);
} }
let output_string = if (column_widths.is_empty() || column_widths.iter().all(|x| *x == 0)) if (column_widths.is_empty() || column_widths.iter().all(|x| *x == 0))
&& escaped_rows.is_empty() && escaped_rows.is_empty()
{ {
String::from("") String::from("")
@ -260,9 +260,7 @@ fn table(
) )
.trim() .trim()
.to_string() .to_string()
}; }
output_string
} }
pub fn group_by(values: PipelineData, head: Span, config: &Config) -> (PipelineData, bool) { pub fn group_by(values: PipelineData, head: Span, config: &Config) -> (PipelineData, bool) {

View File

@ -210,8 +210,7 @@ impl Job {
from_type: "record".into(), from_type: "record".into(),
span: entry_span, span: entry_span,
help: Some(format!( help: Some(format!(
"Invalid column \"{}\" in xml entry. Only \"{}\", \"{}\" and \"{}\" are permitted", "Invalid column \"{bad_column}\" in xml entry. Only \"{COLUMN_TAG_NAME}\", \"{COLUMN_ATTRS_NAME}\" and \"{COLUMN_CONTENT_NAME}\" are permitted"
bad_column, COLUMN_TAG_NAME, COLUMN_ATTRS_NAME, COLUMN_CONTENT_NAME
)), )),
}); });
} }
@ -399,7 +398,7 @@ impl Job {
}); });
} }
let content_text = format!("{} {}", tag, content); let content_text = format!("{tag} {content}");
// PI content must NOT be escaped // PI content must NOT be escaped
// https://www.w3.org/TR/xml/#sec-pi // https://www.w3.org/TR/xml/#sec-pi
let pi_content = BytesPI::new(content_text.as_str()); let pi_content = BytesPI::new(content_text.as_str());
@ -428,8 +427,7 @@ impl Job {
from_type: Type::record().to_string(), from_type: Type::record().to_string(),
span: tag_span, span: tag_span,
help: Some(format!( help: Some(format!(
"Incorrect tag name {}, tag name can not start with ! or ?", "Incorrect tag name {tag}, tag name can not start with ! or ?"
tag
)), )),
}); });
} }

View File

@ -211,7 +211,7 @@ fn parse_closure_result(
} else { } else {
let error = ShellError::GenericError { let error = ShellError::GenericError {
error: "Invalid block return".into(), error: "Invalid block return".into(),
msg: format!("Unexpected record key '{}'", k), msg: format!("Unexpected record key '{k}'"),
span: Some(span), span: Some(span),
help: None, help: None,
inner: vec![], inner: vec![],

View File

@ -144,7 +144,7 @@ fn build_help_commands(engine_state: &EngineState, span: Span) -> PipelineData {
for named_param in &sig.named { for named_param in &sig.named {
let name = if let Some(short) = named_param.short { let name = if let Some(short) = named_param.short {
if named_param.long.is_empty() { if named_param.long.is_empty() {
format!("-{}", short) format!("-{short}")
} else { } else {
format!("--{}(-{})", named_param.long, short) format!("--{}(-{})", named_param.long, short)
} }

View File

@ -80,9 +80,9 @@ pub fn http_parse_url(
) -> Result<(String, Url), ShellError> { ) -> Result<(String, Url), ShellError> {
let mut requested_url = raw_url.coerce_into_string()?; let mut requested_url = raw_url.coerce_into_string()?;
if requested_url.starts_with(':') { if requested_url.starts_with(':') {
requested_url = format!("http://localhost{}", requested_url); requested_url = format!("http://localhost{requested_url}");
} else if !requested_url.contains("://") { } else if !requested_url.contains("://") {
requested_url = format!("http://{}", requested_url); requested_url = format!("http://{requested_url}");
} }
let url = match url::Url::parse(&requested_url) { let url = match url::Url::parse(&requested_url) {
@ -382,8 +382,7 @@ fn send_multipart_request(
"Content-Type: application/octet-stream".to_string(), "Content-Type: application/octet-stream".to_string(),
"Content-Transfer-Encoding: binary".to_string(), "Content-Transfer-Encoding: binary".to_string(),
format!( format!(
"Content-Disposition: form-data; name=\"{}\"; filename=\"{}\"", "Content-Disposition: form-data; name=\"{col}\"; filename=\"{col}\""
col, col
), ),
format!("Content-Length: {}", val.len()), format!("Content-Length: {}", val.len()),
]; ];
@ -391,7 +390,7 @@ fn send_multipart_request(
.add(&mut Cursor::new(val), &headers.join("\r\n")) .add(&mut Cursor::new(val), &headers.join("\r\n"))
.map_err(err)?; .map_err(err)?;
} else { } else {
let headers = format!(r#"Content-Disposition: form-data; name="{}""#, col); let headers = format!(r#"Content-Disposition: form-data; name="{col}""#);
builder builder
.add(val.coerce_into_string()?.as_bytes(), &headers) .add(val.coerce_into_string()?.as_bytes(), &headers)
.map_err(err)?; .map_err(err)?;
@ -400,7 +399,7 @@ fn send_multipart_request(
builder.finish(); builder.finish();
let (boundary, data) = (builder.boundary, builder.data); let (boundary, data) = (builder.boundary, builder.data);
let content_type = format!("multipart/form-data; boundary={}", boundary); let content_type = format!("multipart/form-data; boundary={boundary}");
move || req.set("Content-Type", &content_type).send_bytes(&data) move || req.set("Content-Type", &content_type).send_bytes(&data)
} }
@ -703,26 +702,23 @@ fn transform_response_using_content_type(
.expect("Failed to parse content type, and failed to default to text/plain"); .expect("Failed to parse content type, and failed to default to text/plain");
let ext = match (content_type.type_(), content_type.subtype()) { let ext = match (content_type.type_(), content_type.subtype()) {
(mime::TEXT, mime::PLAIN) => { (mime::TEXT, mime::PLAIN) => url::Url::parse(requested_url)
let path_extension = url::Url::parse(requested_url) .map_err(|err| {
.map_err(|err| { LabeledError::new(err.to_string())
LabeledError::new(err.to_string()) .with_help("cannot parse")
.with_help("cannot parse") .with_label(
.with_label( format!("Cannot parse URL: {requested_url}"),
format!("Cannot parse URL: {requested_url}"), Span::unknown(),
Span::unknown(), )
) })?
})? .path_segments()
.path_segments() .and_then(|mut segments| segments.next_back())
.and_then(|mut segments| segments.next_back()) .and_then(|name| if name.is_empty() { None } else { Some(name) })
.and_then(|name| if name.is_empty() { None } else { Some(name) }) .and_then(|name| {
.and_then(|name| { PathBuf::from(name)
PathBuf::from(name) .extension()
.extension() .map(|name| name.to_string_lossy().to_string())
.map(|name| name.to_string_lossy().to_string()) }),
});
path_extension
}
_ => Some(content_type.subtype().to_string()), _ => Some(content_type.subtype().to_string()),
}; };

View File

@ -64,7 +64,7 @@ impl Registry for NuShellNightly {
tag_name: String, tag_name: String,
} }
let url = format!("https://api.github.com/repos/{}/releases", pkg); let url = format!("https://api.github.com/repos/{pkg}/releases");
let versions = http_client let versions = http_client
.add_header("Accept", "application/vnd.github.v3+json") .add_header("Accept", "application/vnd.github.v3+json")
.add_header("User-Agent", "update-informer") .add_header("User-Agent", "update-informer")
@ -128,7 +128,7 @@ pub fn check_for_latest_nushell_version() -> Value {
if let Ok(Some(new_version)) = informer.check_version() { if let Ok(Some(new_version)) = informer.check_version() {
rec.push("current", Value::test_bool(false)); rec.push("current", Value::test_bool(false));
rec.push("latest", Value::test_string(format!("{}", new_version))); rec.push("latest", Value::test_string(format!("{new_version}")));
Value::test_record(rec) Value::test_record(rec)
} else { } else {
rec.push("current", Value::test_bool(true)); rec.push("current", Value::test_bool(true));
@ -148,7 +148,7 @@ pub fn check_for_latest_nushell_version() -> Value {
if let Ok(Some(new_version)) = informer.check_version() { if let Ok(Some(new_version)) = informer.check_version() {
rec.push("current", Value::test_bool(false)); rec.push("current", Value::test_bool(false));
rec.push("latest", Value::test_string(format!("{}", new_version))); rec.push("latest", Value::test_string(format!("{new_version}")));
Value::test_record(rec) Value::test_record(rec)
} else { } else {
rec.push("current", Value::test_bool(true)); rec.push("current", Value::test_bool(true));

View File

@ -208,7 +208,7 @@ impl EventTypeFilter {
fn wrong_type_error(head: Span, val: &str, val_span: Span) -> ShellError { fn wrong_type_error(head: Span, val: &str, val_span: Span) -> ShellError {
ShellError::UnsupportedInput { ShellError::UnsupportedInput {
msg: format!("{} is not a valid event type", val), msg: format!("{val} is not a valid event type"),
input: "value originates from here".into(), input: "value originates from here".into(),
msg_span: head, msg_span: head,
input_span: val_span, input_span: val_span,

View File

@ -135,8 +135,7 @@ fn uuid(
_ => { _ => {
return Err(ShellError::IncorrectValue { return Err(ShellError::IncorrectValue {
msg: format!( msg: format!(
"Unsupported UUID version: {}. Supported versions are 1, 3, 4, 5, and 7.", "Unsupported UUID version: {version}. Supported versions are 1, 3, 4, 5, and 7."
version
), ),
val_span: span, val_span: span,
call_span: span, call_span: span,
@ -190,8 +189,7 @@ fn validate_flags(
if v != 4 && v != 7 { if v != 4 && v != 7 {
return Err(ShellError::IncorrectValue { return Err(ShellError::IncorrectValue {
msg: format!( msg: format!(
"Unsupported UUID version: {}. Supported versions are 1, 3, 4, 5, and 7.", "Unsupported UUID version: {v}. Supported versions are 1, 3, 4, 5, and 7."
v
), ),
val_span: span, val_span: span,
call_span: span, call_span: span,
@ -202,7 +200,7 @@ fn validate_flags(
.is_some() .is_some()
{ {
return Err(ShellError::IncompatibleParametersSingle { return Err(ShellError::IncompatibleParametersSingle {
msg: format!("version {} uuid does not take mac as a parameter", v), msg: format!("version {v} uuid does not take mac as a parameter"),
span, span,
}); });
} }
@ -211,7 +209,7 @@ fn validate_flags(
.is_some() .is_some()
{ {
return Err(ShellError::IncompatibleParametersSingle { return Err(ShellError::IncompatibleParametersSingle {
msg: format!("version {} uuid does not take namespace as a parameter", v), msg: format!("version {v} uuid does not take namespace as a parameter"),
span, span,
}); });
} }
@ -220,7 +218,7 @@ fn validate_flags(
.is_some() .is_some()
{ {
return Err(ShellError::IncompatibleParametersSingle { return Err(ShellError::IncompatibleParametersSingle {
msg: format!("version {} uuid does not take name as a parameter", v), msg: format!("version {v} uuid does not take name as a parameter"),
span, span,
}); });
} }

View File

@ -81,33 +81,32 @@ fn process(
if let Ok(conn) = db.open_connection() { if let Ok(conn) = db.open_connection() {
match columns { match columns {
Some(record) => { Some(record) => {
let mut create_stmt = format!("CREATE TABLE {} ( ", new_table_name); let mut create_stmt = format!("CREATE TABLE {new_table_name} ( ");
for (column_name, column_datatype) in record { for (column_name, column_datatype) in record {
match column_datatype.coerce_str()?.as_ref() { match column_datatype.coerce_str()?.as_ref() {
"int" => { "int" => {
create_stmt.push_str(&format!("{} INTEGER, ", column_name)); create_stmt.push_str(&format!("{column_name} INTEGER, "));
} }
"float" => { "float" => {
create_stmt.push_str(&format!("{} REAL, ", column_name)); create_stmt.push_str(&format!("{column_name} REAL, "));
} }
"str" => { "str" => {
create_stmt.push_str(&format!("{} VARCHAR(255), ", column_name)); create_stmt.push_str(&format!("{column_name} VARCHAR(255), "));
} }
"bool" => { "bool" => {
create_stmt.push_str(&format!("{} BOOLEAN, ", column_name)); create_stmt.push_str(&format!("{column_name} BOOLEAN, "));
} }
"datetime" => { "datetime" => {
create_stmt.push_str(&format!( create_stmt.push_str(&format!(
"{} DATETIME DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')), ", "{column_name} DATETIME DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')), "
column_name
)); ));
} }
_ => { _ => {
return Err(ShellError::UnsupportedInput { return Err(ShellError::UnsupportedInput {
msg: "unsupported column data type".into(), msg: "unsupported column data type".into(),
input: format!("{:?}", column_datatype), input: format!("{column_datatype:?}"),
msg_span: column_datatype.span(), msg_span: column_datatype.span(),
input_span: column_datatype.span(), input_span: column_datatype.span(),
}); });

View File

@ -92,16 +92,16 @@ impl Command for StorDelete {
let sql_stmt = match where_clause_opt { let sql_stmt = match where_clause_opt {
None => { None => {
// We're deleting an entire table // We're deleting an entire table
format!("DROP TABLE {}", new_table_name) format!("DROP TABLE {new_table_name}")
} }
Some(where_clause) => { Some(where_clause) => {
// We're just deleting some rows // We're just deleting some rows
let mut delete_stmt = format!("DELETE FROM {} ", new_table_name); let mut delete_stmt = format!("DELETE FROM {new_table_name} ");
// Yup, this is a bit janky, but I'm not sure a better way to do this without having // Yup, this is a bit janky, but I'm not sure a better way to do this without having
// --and and --or flags as well as supporting ==, !=, <>, is null, is not null, etc. // --and and --or flags as well as supporting ==, !=, <>, is null, is not null, etc.
// and other sql syntax. So, for now, just type a sql where clause as a string. // and other sql syntax. So, for now, just type a sql where clause as a string.
delete_stmt.push_str(&format!("WHERE {}", where_clause)); delete_stmt.push_str(&format!("WHERE {where_clause}"));
delete_stmt delete_stmt
} }
}; };

View File

@ -164,7 +164,7 @@ fn process(
} }
let new_table_name = table_name.unwrap_or("table".into()); let new_table_name = table_name.unwrap_or("table".into());
let mut create_stmt = format!("INSERT INTO {} (", new_table_name); let mut create_stmt = format!("INSERT INTO {new_table_name} (");
let mut column_placeholders: Vec<String> = Vec::new(); let mut column_placeholders: Vec<String> = Vec::new();
let cols = record.columns(); let cols = record.columns();

View File

@ -164,7 +164,7 @@ fn process(
} }
let new_table_name = table_name.unwrap_or("table".into()); let new_table_name = table_name.unwrap_or("table".into());
if let Ok(conn) = db.open_connection() { if let Ok(conn) = db.open_connection() {
let mut update_stmt = format!("UPDATE {} ", new_table_name); let mut update_stmt = format!("UPDATE {new_table_name} ");
update_stmt.push_str("SET "); update_stmt.push_str("SET ");
let mut placeholders: Vec<String> = Vec::new(); let mut placeholders: Vec<String> = Vec::new();

View File

@ -936,8 +936,7 @@ mod tests {
assert!( assert!(
duplicates.is_empty(), duplicates.is_empty(),
"Duplicate short_names found: {:?}", "Duplicate short_names found: {duplicates:?}"
duplicates
); );
} }
@ -958,8 +957,7 @@ mod tests {
assert!( assert!(
duplicates.is_empty(), duplicates.is_empty(),
"Duplicate long_names found: {:?}", "Duplicate long_names found: {duplicates:?}"
duplicates
); );
} }
} }

View File

@ -155,9 +155,9 @@ fn format_value_impl(val: &Value, arg: &Arguments, span: Span) -> Value {
&arg.format_value.item &arg.format_value.item
}; };
if d.fract() == 0.0 { if d.fract() == 0.0 {
Value::string(format!("{} {}", d, unit), inner_span) Value::string(format!("{d} {unit}"), inner_span)
} else { } else {
Value::string(format!("{:.float_precision$} {}", d, unit), inner_span) Value::string(format!("{d:.float_precision$} {unit}"), inner_span)
} }
} }
Err(e) => Value::error(e, inner_span), Err(e) => Value::error(e, inner_span),

View File

@ -103,7 +103,7 @@ fn run(
if first { if first {
first = false; first = false;
} else if let Some(separator) = &separator { } else if let Some(separator) = &separator {
write!(buffer, "{}", separator).map_err(&from_io_error)?; write!(buffer, "{separator}").map_err(&from_io_error)?;
} }
match value { match value {

View File

@ -292,7 +292,7 @@ mod tests {
]; ];
for expectation in &cases { for expectation in &cases {
println!("{:?}", expectation); println!("{expectation:?}");
let expected = expectation.expected; let expected = expectation.expected;
let actual = action( let actual = action(
&word, &word,

View File

@ -106,7 +106,7 @@ impl Command for NuCheck {
Err(err) => return Err(err), Err(err) => return Err(err),
}; };
let result = if as_module || path.is_dir() { if as_module || path.is_dir() {
parse_file_or_dir_module( parse_file_or_dir_module(
path.to_string_lossy().as_bytes(), path.to_string_lossy().as_bytes(),
&mut working_set, &mut working_set,
@ -120,9 +120,7 @@ impl Command for NuCheck {
working_set.files = FileStack::with_file(path.clone()); working_set.files = FileStack::with_file(path.clone());
parse_file_script(&path, &mut working_set, is_debug, path_span, call.head) parse_file_script(&path, &mut working_set, is_debug, path_span, call.head)
// The working set is not merged, so no need to pop the file from the stack. // The working set is not merged, so no need to pop the file from the stack.
}; }
result
} else { } else {
Err(ShellError::GenericError { Err(ShellError::GenericError {
error: "Failed to execute command".into(), error: "Failed to execute command".into(),

View File

@ -45,8 +45,8 @@ impl Command for UName {
os: false, os: false,
}; };
let output = uu_uname::UNameOutput::new(&opts).map_err(|e| ShellError::GenericError { let output = uu_uname::UNameOutput::new(&opts).map_err(|e| ShellError::GenericError {
error: format!("{}", e), error: format!("{e}"),
msg: format!("{}", e), msg: format!("{e}"),
span: None, span: None,
help: None, help: None,
inner: Vec::new(), inner: Vec::new(),

View File

@ -379,7 +379,7 @@ fn get_theme_flag(
to_type: String::from("theme"), to_type: String::from("theme"),
from_type: String::from("string"), from_type: String::from("string"),
span: call.span(), span: call.span(),
help: Some(format!("{}, but found '{}'.", err, theme)), help: Some(format!("{err}, but found '{theme}'.")),
}) })
}) })
.transpose() .transpose()
@ -1117,7 +1117,7 @@ fn create_empty_placeholder(
return String::new(); return String::new();
} }
let cell = format!("empty {}", value_type_name); let cell = format!("empty {value_type_name}");
let mut table = NuTable::new(1, 1); let mut table = NuTable::new(1, 1);
table.insert((0, 0), cell); table.insert((0, 0), cell);
table.set_data_style(TextStyle::default().dimmed()); table.set_data_style(TextStyle::default().dimmed());
@ -1156,7 +1156,7 @@ fn convert_table_to_output(
} else { } else {
// assume this failed because the table was too wide // assume this failed because the table was too wide
// TODO: more robust error classification // TODO: more robust error classification
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())) Some(Ok(msg.as_bytes().to_vec()))

View File

@ -170,7 +170,7 @@ fn glob_files_in_parent(
let expected = expected let expected = expected
.join(" ") .join(" ")
.replace('/', std::path::MAIN_SEPARATOR_STR); .replace('/', std::path::MAIN_SEPARATOR_STR);
assert_eq!(actual.out, expected, "\n test: {}", tag); assert_eq!(actual.out, expected, "\n test: {tag}");
}); });
} }

View File

@ -70,7 +70,7 @@ fn into_int_binary_signed_empty() {
#[ignore] #[ignore]
fn into_int_datetime1() { fn into_int_datetime1() {
let dt = DateTime::parse_from_rfc3339("1983-04-13T12:09:14.123456789+00:00"); let dt = DateTime::parse_from_rfc3339("1983-04-13T12:09:14.123456789+00:00");
eprintln!("dt debug {:?}", dt); eprintln!("dt debug {dt:?}");
assert_eq!( assert_eq!(
dt, dt,
Ok(FixedOffset::east_opt(0) Ok(FixedOffset::east_opt(0)

View File

@ -83,16 +83,13 @@ fn do_cases_where_result_is_same_between_join_types(join_type: &str) {
), ),
(("[{a: 1}]", "[{a: 1 b: 1}]", "a"), "[[a, b]; [1, 1]]"), (("[{a: 1}]", "[{a: 1 b: 1}]", "a"), "[[a, b]; [1, 1]]"),
] { ] {
let expr = format!("{} | join {} {} {} | to nuon", left, right, join_type, on); let expr = format!("{left} | join {right} {join_type} {on} | to nuon");
let actual = nu!(expr).out; let actual = nu!(expr).out;
assert_eq!(actual, expected); assert_eq!(actual, expected);
// Test again with streaming input (using `each` to convert the input into a ListStream) // Test again with streaming input (using `each` to convert the input into a ListStream)
let to_list_stream = "each { |i| $i } | "; let to_list_stream = "each { |i| $i } | ";
let expr = format!( let expr = format!("{left} | {to_list_stream} join {right} {join_type} {on} | to nuon");
"{} | {} join {} {} {} | to nuon",
left, to_list_stream, right, join_type, on
);
let actual = nu!(expr).out; let actual = nu!(expr).out;
assert_eq!(actual, expected); assert_eq!(actual, expected);
} }
@ -244,16 +241,14 @@ fn do_cases_where_result_differs_between_join_types(join_type: &str) {
] { ] {
for (join_type_, expected) in join_types { for (join_type_, expected) in join_types {
if join_type_ == join_type { if join_type_ == join_type {
let expr = format!("{} | join {} {} {} | to nuon", left, right, join_type, on); let expr = format!("{left} | join {right} {join_type} {on} | to nuon");
let actual = nu!(expr).out; let actual = nu!(expr).out;
assert_eq!(actual, expected); assert_eq!(actual, expected);
// Test again with streaming input (using `each` to convert the input into a ListStream) // Test again with streaming input (using `each` to convert the input into a ListStream)
let to_list_stream = "each { |i| $i } | "; let to_list_stream = "each { |i| $i } | ";
let expr = format!( let expr =
"{} | {} join {} {} {} | to nuon", format!("{left} | {to_list_stream} join {right} {join_type} {on} | to nuon");
left, to_list_stream, right, join_type, on
);
let actual = nu!(expr).out; let actual = nu!(expr).out;
assert_eq!(actual, expected); assert_eq!(actual, expected);
} }
@ -384,18 +379,15 @@ fn do_cases_where_result_differs_between_join_types_with_different_join_keys(joi
] { ] {
for (join_type_, expected) in join_types { for (join_type_, expected) in join_types {
if join_type_ == join_type { if join_type_ == join_type {
let expr = format!( let expr =
"{} | join {} {} {} {} | to nuon", format!("{left} | join {right} {join_type} {left_on} {right_on} | to nuon");
left, right, join_type, left_on, right_on
);
let actual = nu!(expr).out; let actual = nu!(expr).out;
assert_eq!(actual, expected); assert_eq!(actual, expected);
// Test again with streaming input (using `each` to convert the input into a ListStream) // Test again with streaming input (using `each` to convert the input into a ListStream)
let to_list_stream = "each { |i| $i } | "; let to_list_stream = "each { |i| $i } | ";
let expr = format!( let expr = format!(
"{} | {} join {} {} {} {} | to nuon", "{left} | {to_list_stream} join {right} {join_type} {left_on} {right_on} | to nuon"
left, to_list_stream, right, join_type, left_on, right_on
); );
let actual = nu!(expr).out; let actual = nu!(expr).out;
assert_eq!(actual, expected); assert_eq!(actual, expected);
@ -413,7 +405,7 @@ fn test_alternative_table_syntax() {
(("[[a]; [1]]", "[{a: 1}]", "a"), "[[a]; [1]]"), (("[[a]; [1]]", "[{a: 1}]", "a"), "[[a]; [1]]"),
(("[[a]; [1]]", "[[a]; [1]]", "a"), "[[a]; [1]]"), (("[[a]; [1]]", "[[a]; [1]]", "a"), "[[a]; [1]]"),
] { ] {
let expr = format!("{} | join {} {} {} | to nuon", left, right, join_type, on); let expr = format!("{left} | join {right} {join_type} {on} | to nuon");
let actual = nu!(&expr).out; let actual = nu!(&expr).out;
assert_eq!(actual, expected, "Expression was {}", &expr); assert_eq!(actual, expected, "Expression was {}", &expr);
} }

View File

@ -10,7 +10,7 @@ fn creates_temp_file() {
"mktemp" "mktemp"
); );
let loc = AbsolutePath::try_new(&output.out).unwrap(); let loc = AbsolutePath::try_new(&output.out).unwrap();
println!("{:?}", loc); println!("{loc:?}");
assert!(loc.exists()); assert!(loc.exists());
}) })
} }

View File

@ -3698,11 +3698,10 @@ fn table_footer_inheritance() {
field0: [ [ y1, y2, y3 ]; [ 1 2 3 ] [ 79 79 79 ] [ {{ f1: 'a string', f2: 1000 }}, 1, 2 ] ],\ field0: [ [ y1, y2, y3 ]; [ 1 2 3 ] [ 79 79 79 ] [ {{ f1: 'a string', f2: 1000 }}, 1, 2 ] ],\
field1: [ a, b, c ],\ field1: [ a, b, c ],\
field2: [ 123, 234, 345 ],\ field2: [ 123, 234, 345 ],\
field3: {},\ field3: {table1},\
field4: {{ f1: 1, f2: 3, f3: {{ f1: f1, f2: f2, f3: f3 }} }},\ field4: {{ f1: 1, f2: 3, f3: {{ f1: f1, f2: f2, f3: f3 }} }},\
field5: [ [ x1, x2, x3 ]; [ 1 2 3 ] [ 79 79 79 ] [ {{ f1: 'a string', f2: 1000 }}, 1, 2 ] ],\ field5: [ [ x1, x2, x3 ]; [ 1 2 3 ] [ 79 79 79 ] [ {{ f1: 'a string', f2: 1000 }}, 1, 2 ] ],\
}}", }}"
table1
); );
let actual = nu!(format!( let actual = nu!(format!(
"$env.config.table.footer_inheritance = true; {structure} | table --width=80 --expand" "$env.config.table.footer_inheritance = true; {structure} | table --width=80 --expand"

View File

@ -24,7 +24,7 @@ fn row_but_all() {
#[test] #[test]
fn throw_inner_error() { fn throw_inner_error() {
let error_msg = "This message should show up"; let error_msg = "This message should show up";
let error = format!("(error make {{ msg: \"{}\" }})", error_msg); let error = format!("(error make {{ msg: \"{error_msg}\" }})");
let actual = nu!(format!( let actual = nu!(format!(
"[[key value]; [foo 1] [foo 2] [{} 3]] | transpose", "[[key value]; [foo 1] [foo 2] [{} 3]] | transpose",
error error

View File

@ -540,10 +540,7 @@ fn change_file_times_to_date() {
assert!( assert!(
got_atime.signed_duration_since(expected).lt(&threshold) got_atime.signed_duration_since(expected).lt(&threshold)
&& got_mtime.signed_duration_since(expected).lt(&threshold), && got_mtime.signed_duration_since(expected).lt(&threshold),
"Expected: {}. Got: atime={}, mtime={}", "Expected: {expected}. Got: atime={got_atime}, mtime={got_mtime}"
expected,
got_atime,
got_mtime
); );
assert!(got_mtime.signed_duration_since(expected).lt(&threshold)); assert!(got_mtime.signed_duration_since(expected).lt(&threshold));
}) })

View File

@ -8,7 +8,7 @@ fn msgpack_test(fixture_name: &str, commands: Option<&str>) -> nu_test_support::
.join("generate.nu"); .join("generate.nu");
let mut outcome = None; let mut outcome = None;
Playground::setup(&format!("msgpack test {}", fixture_name), |dirs, _| { Playground::setup(&format!("msgpack test {fixture_name}"), |dirs, _| {
assert!( assert!(
nu!( nu!(
cwd: dirs.test(), cwd: dirs.test(),

View File

@ -19,15 +19,13 @@ fn unsupported_unions() {
let from_res = derive_from_value(input.clone()); let from_res = derive_from_value(input.clone());
assert!( assert!(
matches!(from_res, Err(DeriveError::UnsupportedUnions)), matches!(from_res, Err(DeriveError::UnsupportedUnions)),
"expected `DeriveError::UnsupportedUnions`, got {:?}", "expected `DeriveError::UnsupportedUnions`, got {from_res:?}"
from_res
); );
let into_res = derive_into_value(input); let into_res = derive_into_value(input);
assert!( assert!(
matches!(into_res, Err(DeriveError::UnsupportedUnions)), matches!(into_res, Err(DeriveError::UnsupportedUnions)),
"expected `DeriveError::UnsupportedUnions`, got {:?}", "expected `DeriveError::UnsupportedUnions`, got {into_res:?}"
into_res
); );
} }
@ -48,15 +46,13 @@ fn unsupported_enums() {
let from_res = derive_from_value(input.clone()); let from_res = derive_from_value(input.clone());
assert!( assert!(
matches!(from_res, Err(DeriveError::UnsupportedEnums { .. })), matches!(from_res, Err(DeriveError::UnsupportedEnums { .. })),
"expected `DeriveError::UnsupportedEnums`, got {:?}", "expected `DeriveError::UnsupportedEnums`, got {from_res:?}"
from_res
); );
let into_res = derive_into_value(input); let into_res = derive_into_value(input);
assert!( assert!(
matches!(into_res, Err(DeriveError::UnsupportedEnums { .. })), matches!(into_res, Err(DeriveError::UnsupportedEnums { .. })),
"expected `DeriveError::UnsupportedEnums`, got {:?}", "expected `DeriveError::UnsupportedEnums`, got {into_res:?}"
into_res
); );
} }
@ -73,15 +69,13 @@ fn unexpected_attribute() {
let from_res = derive_from_value(input.clone()); let from_res = derive_from_value(input.clone());
assert!( assert!(
matches!(from_res, Err(DeriveError::UnexpectedAttribute { .. })), matches!(from_res, Err(DeriveError::UnexpectedAttribute { .. })),
"expected `DeriveError::UnexpectedAttribute`, got {:?}", "expected `DeriveError::UnexpectedAttribute`, got {from_res:?}"
from_res
); );
let into_res = derive_into_value(input); let into_res = derive_into_value(input);
assert!( assert!(
matches!(into_res, Err(DeriveError::UnexpectedAttribute { .. })), matches!(into_res, Err(DeriveError::UnexpectedAttribute { .. })),
"expected `DeriveError::UnexpectedAttribute`, got {:?}", "expected `DeriveError::UnexpectedAttribute`, got {into_res:?}"
into_res
); );
} }
@ -98,15 +92,13 @@ fn unexpected_attribute_on_struct_field() {
let from_res = derive_from_value(input.clone()); let from_res = derive_from_value(input.clone());
assert!( assert!(
matches!(from_res, Err(DeriveError::UnexpectedAttribute { .. })), matches!(from_res, Err(DeriveError::UnexpectedAttribute { .. })),
"expected `DeriveError::UnexpectedAttribute`, got {:?}", "expected `DeriveError::UnexpectedAttribute`, got {from_res:?}"
from_res
); );
let into_res = derive_into_value(input); let into_res = derive_into_value(input);
assert!( assert!(
matches!(into_res, Err(DeriveError::UnexpectedAttribute { .. })), matches!(into_res, Err(DeriveError::UnexpectedAttribute { .. })),
"expected `DeriveError::UnexpectedAttribute`, got {:?}", "expected `DeriveError::UnexpectedAttribute`, got {into_res:?}"
into_res
); );
} }
@ -123,15 +115,13 @@ fn unexpected_attribute_on_enum_variant() {
let from_res = derive_from_value(input.clone()); let from_res = derive_from_value(input.clone());
assert!( assert!(
matches!(from_res, Err(DeriveError::UnexpectedAttribute { .. })), matches!(from_res, Err(DeriveError::UnexpectedAttribute { .. })),
"expected `DeriveError::UnexpectedAttribute`, got {:?}", "expected `DeriveError::UnexpectedAttribute`, got {from_res:?}"
from_res
); );
let into_res = derive_into_value(input); let into_res = derive_into_value(input);
assert!( assert!(
matches!(into_res, Err(DeriveError::UnexpectedAttribute { .. })), matches!(into_res, Err(DeriveError::UnexpectedAttribute { .. })),
"expected `DeriveError::UnexpectedAttribute`, got {:?}", "expected `DeriveError::UnexpectedAttribute`, got {into_res:?}"
into_res
); );
} }
@ -151,8 +141,7 @@ fn invalid_attribute_position_in_tuple_struct() {
from_res, from_res,
Err(DeriveError::InvalidAttributePosition { attribute_span: _ }) Err(DeriveError::InvalidAttributePosition { attribute_span: _ })
), ),
"expected `DeriveError::InvalidAttributePosition`, got {:?}", "expected `DeriveError::InvalidAttributePosition`, got {from_res:?}"
from_res
); );
let into_res = derive_into_value(input); let into_res = derive_into_value(input);
@ -161,8 +150,7 @@ fn invalid_attribute_position_in_tuple_struct() {
into_res, into_res,
Err(DeriveError::InvalidAttributePosition { attribute_span: _ }) Err(DeriveError::InvalidAttributePosition { attribute_span: _ })
), ),
"expected `DeriveError::InvalidAttributePosition`, got {:?}", "expected `DeriveError::InvalidAttributePosition`, got {into_res:?}"
into_res
); );
} }
@ -179,15 +167,13 @@ fn invalid_attribute_value() {
let from_res = derive_from_value(input.clone()); let from_res = derive_from_value(input.clone());
assert!( assert!(
matches!(from_res, Err(DeriveError::InvalidAttributeValue { .. })), matches!(from_res, Err(DeriveError::InvalidAttributeValue { .. })),
"expected `DeriveError::InvalidAttributeValue`, got {:?}", "expected `DeriveError::InvalidAttributeValue`, got {from_res:?}"
from_res
); );
let into_res = derive_into_value(input); let into_res = derive_into_value(input);
assert!( assert!(
matches!(into_res, Err(DeriveError::InvalidAttributeValue { .. })), matches!(into_res, Err(DeriveError::InvalidAttributeValue { .. })),
"expected `DeriveError::InvalidAttributeValue`, got {:?}", "expected `DeriveError::InvalidAttributeValue`, got {into_res:?}"
into_res
); );
} }
@ -204,15 +190,13 @@ fn non_unique_struct_keys() {
let from_res = derive_from_value(input.clone()); let from_res = derive_from_value(input.clone());
assert!( assert!(
matches!(from_res, Err(DeriveError::NonUniqueName { .. })), matches!(from_res, Err(DeriveError::NonUniqueName { .. })),
"expected `DeriveError::NonUniqueName`, got {:?}", "expected `DeriveError::NonUniqueName`, got {from_res:?}"
from_res
); );
let into_res = derive_into_value(input); let into_res = derive_into_value(input);
assert!( assert!(
matches!(into_res, Err(DeriveError::NonUniqueName { .. })), matches!(into_res, Err(DeriveError::NonUniqueName { .. })),
"expected `DeriveError::NonUniqueName`, got {:?}", "expected `DeriveError::NonUniqueName`, got {into_res:?}"
into_res
); );
} }
@ -229,14 +213,12 @@ fn non_unique_enum_variants() {
let from_res = derive_from_value(input.clone()); let from_res = derive_from_value(input.clone());
assert!( assert!(
matches!(from_res, Err(DeriveError::NonUniqueName { .. })), matches!(from_res, Err(DeriveError::NonUniqueName { .. })),
"expected `DeriveError::NonUniqueName`, got {:?}", "expected `DeriveError::NonUniqueName`, got {from_res:?}"
from_res
); );
let into_res = derive_into_value(input); let into_res = derive_into_value(input);
assert!( assert!(
matches!(into_res, Err(DeriveError::NonUniqueName { .. })), matches!(into_res, Err(DeriveError::NonUniqueName { .. })),
"expected `DeriveError::NonUniqueName`, got {:?}", "expected `DeriveError::NonUniqueName`, got {into_res:?}"
into_res
); );
} }

View File

@ -556,7 +556,7 @@ impl BlockBuilder {
); );
instruction.set_branch_target(target_index).map_err(|_| { instruction.set_branch_target(target_index).map_err(|_| {
CompileError::SetBranchTargetOfNonBranchInstruction { CompileError::SetBranchTargetOfNonBranchInstruction {
instruction: format!("{:?}", instruction), instruction: format!("{instruction:?}"),
span: *span, span: *span,
} }
})?; })?;

View File

@ -754,7 +754,7 @@ where
long_desc.push_str(" "); long_desc.push_str(" ");
// Short flag shown before long flag // Short flag shown before long flag
if let Some(short) = flag.short { if let Some(short) = flag.short {
let _ = write!(long_desc, "{help_subcolor_one}-{}{RESET}", short); let _ = write!(long_desc, "{help_subcolor_one}-{short}{RESET}");
if !flag.long.is_empty() { if !flag.long.is_empty() {
let _ = write!(long_desc, "{DEFAULT_COLOR},{RESET} "); let _ = write!(long_desc, "{DEFAULT_COLOR},{RESET} ");
} }

View File

@ -18,7 +18,7 @@ pub fn cleanup_exit<T>(tag: T, engine_state: &EngineState, exit_code: i32) -> T
{ {
let job_count = jobs.iter().count(); let job_count = jobs.iter().count();
println!("There are still background jobs running ({}).", job_count); println!("There are still background jobs running ({job_count}).");
println!("Running `exit` a second time will kill all of them."); println!("Running `exit` a second time will kill all of them.");

View File

@ -46,7 +46,7 @@ fn get_path_style(path: &str, cwd: &str, ls_colors: &LsColors) -> Option<Style>
let mut expanded_path = expand_to_real_path(path); let mut expanded_path = expand_to_real_path(path);
let try_cwd = expanded_path.as_path() == Path::new(path); let try_cwd = expanded_path.as_path() == Path::new(path);
if try_cwd { if try_cwd {
let cwd_path = format!("./{}", path); let cwd_path = format!("./{path}");
expanded_path = expand_path_with(cwd_path, cwd, false); expanded_path = expand_path_with(cwd_path, cwd, false);
} }

View File

@ -373,9 +373,9 @@ fn get_widget_width(w: &BinaryWidget) -> usize {
fn usize_to_hex(n: usize, width: usize) -> String { fn usize_to_hex(n: usize, width: usize) -> String {
if width == 0 { if width == 0 {
format!("{:x}", n) format!("{n:x}")
} else { } else {
format!("{:0>width$x}", n, width = width) format!("{n:0>width$x}")
} }
} }

View File

@ -1359,13 +1359,13 @@ mod test {
fn test_range_pattern() { fn test_range_pattern() {
let pat = Pattern::new("a[0-9]b").unwrap(); let pat = Pattern::new("a[0-9]b").unwrap();
for i in 0..10 { for i in 0..10 {
assert!(pat.matches(&format!("a{}b", i)), "a{i}b =~ a[0-9]b"); assert!(pat.matches(&format!("a{i}b")), "a{i}b =~ a[0-9]b");
} }
assert!(!pat.matches("a_b")); assert!(!pat.matches("a_b"));
let pat = Pattern::new("a[!0-9]b").unwrap(); let pat = Pattern::new("a[!0-9]b").unwrap();
for i in 0..10 { for i in 0..10 {
assert!(!pat.matches(&format!("a{}b", i))); assert!(!pat.matches(&format!("a{i}b")));
} }
assert!(pat.matches("a_b")); assert!(pat.matches("a_b"));

View File

@ -84,7 +84,7 @@ impl LanguageServer {
idx += 1; idx += 1;
match &arg.shape { match &arg.shape {
SyntaxShape::Block | SyntaxShape::MatchBlock => { SyntaxShape::Block | SyntaxShape::MatchBlock => {
format!("{{ ${{{}:{}}} }}", idx, text) format!("{{ ${{{idx}:{text}}} }}")
} }
SyntaxShape::Keyword(kwd, _) => { SyntaxShape::Keyword(kwd, _) => {
// NOTE: If optional, the keyword should also be in a placeholder so that it can be removed easily. // NOTE: If optional, the keyword should also be in a placeholder so that it can be removed easily.
@ -103,7 +103,7 @@ impl LanguageServer {
format!("{} ${{{}:{}}}", String::from_utf8_lossy(kwd), idx, text) format!("{} ${{{}:{}}}", String::from_utf8_lossy(kwd), idx, text)
} }
} }
_ => format!("${{{}:{}}}", idx, text), _ => format!("${{{idx}:{text}}}"),
} }
}; };

View File

@ -40,7 +40,7 @@ fn extract_inlay_hints_from_expression(
}; };
vec![InlayHint { vec![InlayHint {
kind: Some(InlayHintKind::TYPE), kind: Some(InlayHintKind::TYPE),
label: InlayHintLabel::String(format!(": {}", type_string)), label: InlayHintLabel::String(format!(": {type_string}")),
position, position,
text_edits: None, text_edits: None,
tooltip: None, tooltip: None,
@ -71,7 +71,7 @@ fn extract_inlay_hints_from_expression(
let type_string = type_short_name(&var.ty); let type_string = type_short_name(&var.ty);
vec![InlayHint { vec![InlayHint {
kind: Some(InlayHintKind::TYPE), kind: Some(InlayHintKind::TYPE),
label: InlayHintLabel::String(format!(": {}", type_string)), label: InlayHintLabel::String(format!(": {type_string}")),
position, position,
text_edits: None, text_edits: None,
tooltip: None, tooltip: None,

View File

@ -165,9 +165,9 @@ impl LanguageServer {
.map(|val| { .map(|val| {
let ty = val.get_type(); let ty = val.get_type();
if let Ok(s) = val.coerce_str() { if let Ok(s) = val.coerce_str() {
format!("```\n{}\n```\n---\n{}", ty, s) format!("```\n{ty}\n```\n---\n{s}")
} else { } else {
format!("```\n{}\n```", ty) format!("```\n{ty}\n```")
} }
}) })
.unwrap_or("`unknown`".into()), .unwrap_or("`unknown`".into()),
@ -186,7 +186,7 @@ impl LanguageServer {
.join("\n"); .join("\n");
markdown_hover(description) markdown_hover(description)
} }
Id::Value(t) => markdown_hover(format!("`{}`", t)), Id::Value(t) => markdown_hover(format!("`{t}`")),
Id::External(cmd) => { Id::External(cmd) => {
let command_output = if cfg!(windows) { let command_output = if cfg!(windows) {
std::process::Command::new("powershell.exe") std::process::Command::new("powershell.exe")

View File

@ -61,13 +61,13 @@ pub(crate) fn doc_for_arg(
if let SyntaxShape::Keyword(_, inner_shape) = shape { if let SyntaxShape::Keyword(_, inner_shape) = shape {
shape = *inner_shape; shape = *inner_shape;
} }
text.push_str(&format!(": `<{}>`", shape)); text.push_str(&format!(": `<{shape}>`"));
} }
if !(desc.is_empty() && default_value.is_none()) || optional { if !(desc.is_empty() && default_value.is_none()) || optional {
text.push_str(" -") text.push_str(" -")
}; };
if !desc.is_empty() { if !desc.is_empty() {
text.push_str(&format!(" {}", desc)); text.push_str(&format!(" {desc}"));
}; };
if let Some(value) = default_value.as_ref().and_then(|v| v.coerce_str().ok()) { if let Some(value) = default_value.as_ref().and_then(|v| v.coerce_str().ok()) {
text.push_str(&format!( text.push_str(&format!(

View File

@ -2160,12 +2160,10 @@ fn module_needs_reloading(working_set: &StateWorkingSet, module_id: ModuleId) ->
return true; return true;
} }
let private_submodule_changed = module module
.imported_modules .imported_modules
.iter() .iter()
.any(|submodule_id| submodule_need_reloading(working_set, *submodule_id)); .any(|submodule_id| submodule_need_reloading(working_set, *submodule_id))
private_submodule_changed
} }
/// Parse a module from a file. /// Parse a module from a file.
@ -4052,7 +4050,7 @@ pub fn parse_plugin_use(working_set: &mut StateWorkingSet, call: Box<Call>) -> P
pub fn find_dirs_var(working_set: &StateWorkingSet, var_name: &str) -> Option<VarId> { pub fn find_dirs_var(working_set: &StateWorkingSet, var_name: &str) -> Option<VarId> {
working_set working_set
.find_variable(format!("${}", var_name).as_bytes()) .find_variable(format!("${var_name}").as_bytes())
.filter(|var_id| working_set.get_variable(*var_id).const_val.is_some()) .filter(|var_id| working_set.get_variable(*var_id).const_val.is_some())
} }

View File

@ -37,7 +37,7 @@ pub fn parse_shape_name(
span: Span, span: Span,
use_loc: ShapeDescriptorUse, use_loc: ShapeDescriptorUse,
) -> SyntaxShape { ) -> SyntaxShape {
let result = match bytes { match bytes {
b"any" => SyntaxShape::Any, b"any" => SyntaxShape::Any,
b"binary" => SyntaxShape::Binary, b"binary" => SyntaxShape::Binary,
b"block" => { b"block" => {
@ -106,20 +106,18 @@ pub fn parse_shape_name(
} }
if let Some(decl_id) = working_set.find_decl(cmd_name) { if let Some(decl_id) = working_set.find_decl(cmd_name) {
return SyntaxShape::CompleterWrapper(Box::new(shape), decl_id); SyntaxShape::CompleterWrapper(Box::new(shape), decl_id)
} else { } else {
working_set.error(ParseError::UnknownCommand(cmd_span)); working_set.error(ParseError::UnknownCommand(cmd_span));
return shape; shape
} }
} else { } else {
//TODO: Handle error case for unknown shapes //TODO: Handle error case for unknown shapes
working_set.error(ParseError::UnknownType(span)); working_set.error(ParseError::UnknownType(span));
return SyntaxShape::Any; SyntaxShape::Any
} }
} }
}; }
result
} }
fn parse_generic_shape( fn parse_generic_shape(

View File

@ -1688,7 +1688,7 @@ pub fn parse_int(working_set: &mut StateWorkingSet, span: Span) -> Expression {
Expression::new(working_set, Expr::Int(num), span, Type::Int) Expression::new(working_set, Expr::Int(num), span, Type::Int)
} else { } else {
working_set.error(ParseError::InvalidLiteral( working_set.error(ParseError::InvalidLiteral(
format!("invalid digits for radix {}", radix), format!("invalid digits for radix {radix}"),
"int".into(), "int".into(),
span, span,
)); ));
@ -3387,10 +3387,7 @@ pub fn parse_import_pattern(working_set: &mut StateWorkingSet, spans: &[Span]) -
"list" "list"
}; };
working_set.error(ParseError::WrongImportPattern( working_set.error(ParseError::WrongImportPattern(
format!( format!("{what} member can be only at the end of an import pattern"),
"{} member can be only at the end of an import pattern",
what
),
prev_span, prev_span,
)); ));
return Expression::new( return Expression::new(
@ -6116,7 +6113,7 @@ fn check_record_key_or_value(
let colon_position = i + string_value.span.start; let colon_position = i + string_value.span.start;
ParseError::InvalidLiteral( ParseError::InvalidLiteral(
"colon".to_string(), "colon".to_string(),
format!("bare word specifying record {}", position), format!("bare word specifying record {position}"),
Span::new(colon_position, colon_position + 1), Span::new(colon_position, colon_position + 1),
) )
}) })

View File

@ -24,7 +24,7 @@ fn test_int(
if let Some(err_pat) = expected_err { if let Some(err_pat) = expected_err {
if let Some(parse_err) = err { if let Some(parse_err) = err {
let act_err = format!("{:?}", parse_err); let act_err = format!("{parse_err:?}");
assert!( assert!(
act_err.contains(err_pat), act_err.contains(err_pat),
"{test_tag}: expected err to contain {err_pat}, but actual error was {act_err}" "{test_tag}: expected err to contain {err_pat}, but actual error was {act_err}"
@ -2770,10 +2770,9 @@ mod input_types {
for prefix in ["let ", "mut ", "mut foo = 1; $"] { for prefix in ["let ", "mut ", "mut foo = 1; $"] {
let input = format!( let input = format!(
r#"{}foo = 1 | r#"{prefix}foo = 1 |
# comment # comment
dummy"#, dummy"#
prefix
); );
let block = parse(&mut working_set, None, input.as_bytes(), true); let block = parse(&mut working_set, None, input.as_bytes(), true);
let last_expr = &block.pipelines.last().unwrap().elements[0].expr.expr; let last_expr = &block.pipelines.last().unwrap().elements[0].expr.expr;
@ -2783,11 +2782,11 @@ mod input_types {
call.arguments[1].expr().unwrap() call.arguments[1].expr().unwrap()
} }
Expr::BinaryOp(_, _, rhs) => rhs.as_ref(), Expr::BinaryOp(_, _, rhs) => rhs.as_ref(),
_ => panic!("Unexpected expression: {:?}", last_expr), _ => panic!("Unexpected expression: {last_expr:?}"),
}; };
let block_id = match block_expr.expr { let block_id = match block_expr.expr {
Expr::Block(block_id) | Expr::Subexpression(block_id) => block_id, Expr::Block(block_id) | Expr::Subexpression(block_id) => block_id,
_ => panic!("Unexpected expression: {:?}", block_expr), _ => panic!("Unexpected expression: {block_expr:?}"),
}; };
let rhs_expr = working_set.get_block(block_id); let rhs_expr = working_set.get_block(block_id);
assert_eq!(rhs_expr.pipelines.len(), 1); assert_eq!(rhs_expr.pipelines.len(), 1);

View File

@ -5,7 +5,7 @@ fn local_socket_path_contains_pid() {
let name = make_local_socket_name("test-string") let name = make_local_socket_name("test-string")
.to_string_lossy() .to_string_lossy()
.into_owned(); .into_owned();
println!("{}", name); println!("{name}");
assert!(name.to_string().contains(&std::process::id().to_string())); assert!(name.to_string().contains(&std::process::id().to_string()));
} }
@ -14,6 +14,6 @@ fn local_socket_path_contains_provided_name() {
let name = make_local_socket_name("test-string") let name = make_local_socket_name("test-string")
.to_string_lossy() .to_string_lossy()
.into_owned(); .into_owned();
println!("{}", name); println!("{name}");
assert!(name.to_string().contains("test-string")); assert!(name.to_string().contains("test-string"));
} }

View File

@ -201,7 +201,7 @@ fn reader_drop() {
impl WriteStreamMessage for Check { impl WriteStreamMessage for Check {
fn write_stream_message(&mut self, msg: StreamMessage) -> Result<(), ShellError> { fn write_stream_message(&mut self, msg: StreamMessage) -> Result<(), ShellError> {
assert!(matches!(msg, StreamMessage::Drop(1)), "got {:?}", msg); assert!(matches!(msg, StreamMessage::Drop(1)), "got {msg:?}");
self.0.store(true, Relaxed); self.0.store(true, Relaxed);
Ok(()) Ok(())
} }

View File

@ -122,8 +122,7 @@ mod tests {
let string = std::str::from_utf8(&out).expect("utf-8 error"); let string = std::str::from_utf8(&out).expect("utf-8 error");
assert!( assert!(
string.ends_with('\n'), string.ends_with('\n'),
"doesn't end with newline: {:?}", "doesn't end with newline: {string:?}"
string
); );
} }

View File

@ -1261,10 +1261,7 @@ pub(crate) fn handle_engine_call(
let context = context.ok_or_else(|| ShellError::GenericError { let context = context.ok_or_else(|| ShellError::GenericError {
error: "A plugin execution context is required for this engine call".into(), error: "A plugin execution context is required for this engine call".into(),
msg: format!( msg: format!("attempted to call {call_name} outside of a command invocation"),
"attempted to call {} outside of a command invocation",
call_name
),
span: None, span: None,
help: Some("this is probably a bug with the plugin".into()), help: Some("this is probably a bug with the plugin".into()),
inner: vec![], inner: vec![],

View File

@ -276,11 +276,11 @@ impl PluginTest {
)?; )?;
( (
format!("{:#?}", expectation_base), format!("{expectation_base:#?}"),
format!("{:#?}", value_base), format!("{value_base:#?}"),
) )
} }
_ => (format!("{:#?}", expectation), format!("{:#?}", value)), _ => (format!("{expectation:#?}"), format!("{value:#?}")),
}; };
let diff = diff_by_line(&expectation_formatted, &value_formatted); let diff = diff_by_line(&expectation_formatted, &value_formatted);

View File

@ -663,7 +663,7 @@ fn print_help(plugin: &impl Plugin, encoder: impl PluginEncoder) {
.as_ref() .as_ref()
.map(|stem| stem.to_string_lossy().into_owned()) .map(|stem| stem.to_string_lossy().into_owned())
.unwrap_or_else(|| "(unknown)".into()); .unwrap_or_else(|| "(unknown)".into());
println!("Plugin file path: {}", plugin_name); println!("Plugin file path: {plugin_name}");
let mut help = String::new(); let mut help = String::new();
let help_style = HelpStyle::default(); let help_style = HelpStyle::default();
@ -685,7 +685,7 @@ fn print_help(plugin: &impl Plugin, encoder: impl PluginEncoder) {
}) })
.and_then(|_| { .and_then(|_| {
let flags = get_flags_section(&signature, &help_style, |v| match v { let flags = get_flags_section(&signature, &help_style, |v| match v {
FormatterValue::DefaultValue(value) => format!("{:#?}", value), FormatterValue::DefaultValue(value) => format!("{value:#?}"),
FormatterValue::CodeString(text) => text.to_string(), FormatterValue::CodeString(text) => text.to_string(),
}); });
write!(help, "{flags}") write!(help, "{flags}")

View File

@ -1032,10 +1032,7 @@ impl EngineState {
cwd.into_os_string() cwd.into_os_string()
.into_string() .into_string()
.map_err(|err| ShellError::NonUtf8Custom { .map_err(|err| ShellError::NonUtf8Custom {
msg: format!( msg: format!("The current working directory is not a valid utf-8 string: {err:?}"),
"The current working directory is not a valid utf-8 string: {:?}",
err
),
span: Span::unknown(), span: Span::unknown(),
}) })
} }

View File

@ -685,7 +685,7 @@ impl From<Option<String>> for DidYouMean {
impl Display for DidYouMean { impl Display for DidYouMean {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(suggestion) = &self.0 { if let Some(suggestion) = &self.0 {
write!(f, "Did you mean '{}'?", suggestion) write!(f, "Did you mean '{suggestion}'?")
} else { } else {
write!(f, "") write!(f, "")
} }

View File

@ -1511,15 +1511,15 @@ fn shell_error_serialize_roundtrip() {
from_type: "Bar".into(), from_type: "Bar".into(),
help: Some("this is a test".into()), help: Some("this is a test".into()),
}; };
println!("orig_error = {:#?}", original_error); println!("orig_error = {original_error:#?}");
let serialized = let serialized =
serde_json::to_string_pretty(&original_error).expect("serde_json::to_string_pretty failed"); serde_json::to_string_pretty(&original_error).expect("serde_json::to_string_pretty failed");
println!("serialized = {}", serialized); println!("serialized = {serialized}");
let deserialized: ShellError = let deserialized: ShellError =
serde_json::from_str(&serialized).expect("serde_json::from_str failed"); serde_json::from_str(&serialized).expect("serde_json::from_str failed");
println!("deserialized = {:#?}", deserialized); println!("deserialized = {deserialized:#?}");
// We don't expect the deserialized error to be the same as the original error, but its miette // We don't expect the deserialized error to be the same as the original error, but its miette
// properties should be comparable // properties should be comparable

View File

@ -429,7 +429,7 @@ impl fmt::Display for FmtPattern<'_> {
} }
Pattern::Variable(var_id) => { Pattern::Variable(var_id) => {
let variable = FmtVar::new(self.engine_state, *var_id); let variable = FmtVar::new(self.engine_state, *var_id);
write!(f, "{}", variable) write!(f, "{variable}")
} }
Pattern::Or(patterns) => { Pattern::Or(patterns) => {
for (index, pattern) in patterns.iter().enumerate() { for (index, pattern) in patterns.iter().enumerate() {
@ -449,7 +449,7 @@ impl fmt::Display for FmtPattern<'_> {
} }
Pattern::Rest(var_id) => { Pattern::Rest(var_id) => {
let variable = FmtVar::new(self.engine_state, *var_id); let variable = FmtVar::new(self.engine_state, *var_id);
write!(f, "..{}", variable) write!(f, "..{variable}")
} }
Pattern::IgnoreRest => f.write_str(".."), Pattern::IgnoreRest => f.write_str(".."),
Pattern::IgnoreValue => f.write_str("_"), Pattern::IgnoreValue => f.write_str("_"),

View File

@ -19,7 +19,7 @@ use std::cmp;
pub fn lev_distance(a: &str, b: &str, limit: usize) -> Option<usize> { pub fn lev_distance(a: &str, b: &str, limit: usize) -> Option<usize> {
let n = a.chars().count(); let n = a.chars().count();
let m = b.chars().count(); let m = b.chars().count();
let min_dist = if n < m { m - n } else { n - m }; let min_dist = m.abs_diff(n);
if min_dist > limit { if min_dist > limit {
return None; return None;
@ -76,7 +76,7 @@ pub fn lev_distance_with_substrings(a: &str, b: &str, limit: usize) -> Option<us
// Check one isn't less than half the length of the other. If this is true then there is a // Check one isn't less than half the length of the other. If this is true then there is a
// big difference in length. // big difference in length.
let big_len_diff = (n * 2) < m || (m * 2) < n; let big_len_diff = (n * 2) < m || (m * 2) < n;
let len_diff = if n < m { m - n } else { n - m }; let len_diff = m.abs_diff(n);
let lev = lev_distance(a, b, limit + len_diff)?; let lev = lev_distance(a, b, limit + len_diff)?;
// This is the crux, subtracting length difference means exact substring matches will now be 0 // This is the crux, subtracting length difference means exact substring matches will now be 0

View File

@ -1427,7 +1427,7 @@ mod tests {
match value { match value {
Ok(value) => string.push_str(&value.into_string().expect("not a string")), Ok(value) => string.push_str(&value.into_string().expect("not a string")),
Err(err) => { Err(err) => {
println!("string so far: {:?}", string); println!("string so far: {string:?}");
println!("got error: {err:?}"); println!("got error: {err:?}");
assert!(!string.is_empty()); assert!(!string.is_empty());
assert!(matches!(err, ShellError::NonUtf8Custom { .. })); assert!(matches!(err, ShellError::NonUtf8Custom { .. }));

View File

@ -773,7 +773,7 @@ where
T: AsRef<[u8]>, T: AsRef<[u8]>,
{ {
let io_error_map = |err: std::io::Error, location: Location| { let io_error_map = |err: std::io::Error, location: Location| {
let context = format!("Writing to {} failed", destination_name); let context = format!("Writing to {destination_name} failed");
match span { match span {
None => IoError::new_internal(err, context, location), None => IoError::new_internal(err, context, location),
Some(span) if span == Span::unknown() => IoError::new_internal(err, context, location), Some(span) if span == Span::unknown() => IoError::new_internal(err, context, location),

View File

@ -521,8 +521,7 @@ impl Signature {
let s = short.inspect(|c| { let s = short.inspect(|c| {
assert!( assert!(
!self.get_shorts().contains(c), !self.get_shorts().contains(c),
"There may be duplicate short flags for '-{}'", "There may be duplicate short flags for '-{c}'"
c
); );
}); });
@ -530,8 +529,7 @@ impl Signature {
let name: String = name.into(); let name: String = name.into();
assert!( assert!(
!self.get_names().contains(&name.as_str()), !self.get_names().contains(&name.as_str()),
"There may be duplicate name flags for '--{}'", "There may be duplicate name flags for '--{name}'"
name
); );
name name
}; };

View File

@ -924,7 +924,7 @@ impl Value {
match formatter_buf.write_fmt(format_args!("{format}")) { match formatter_buf.write_fmt(format_args!("{format}")) {
Ok(_) => (), Ok(_) => (),
Err(_) => formatter_buf = format!("Invalid format string {}", formatter), Err(_) => formatter_buf = format!("Invalid format string {formatter}"),
} }
formatter_buf formatter_buf
} }
@ -1035,7 +1035,7 @@ impl Value {
pub fn to_parsable_string(&self, separator: &str, config: &Config) -> String { pub fn to_parsable_string(&self, separator: &str, config: &Config) -> String {
match self { match self {
// give special treatment to the simple types to make them parsable // give special treatment to the simple types to make them parsable
Value::String { val, .. } => format!("'{}'", val), Value::String { val, .. } => format!("'{val}'"),
// recurse back into this function for recursive formatting // recurse back into this function for recursive formatting
Value::List { vals: val, .. } => format!( Value::List { vals: val, .. } => format!(
"[{}]", "[{}]",

View File

@ -39,7 +39,7 @@ pub fn build_kill_command(
} else { } else {
let mut cmd = CommandSys::new("kill"); let mut cmd = CommandSys::new("kill");
if let Some(signal_value) = signal { if let Some(signal_value) = signal {
cmd.arg(format!("-{}", signal_value)); cmd.arg(format!("-{signal_value}"));
} else if force { } else if force {
cmd.arg("-9"); cmd.arg("-9");
} }

View File

@ -321,7 +321,7 @@ pub fn nu_run_test(opts: NuOpts, commands: impl AsRef<str>, with_std: bool) -> O
out.into_owned() out.into_owned()
}; };
println!("=== stderr\n{}", err); println!("=== stderr\n{err}");
Outcome::new(out, err.into_owned(), output.status) Outcome::new(out, err.into_owned(), output.status)
} }
@ -397,7 +397,7 @@ where
.spawn() .spawn()
{ {
Ok(child) => child, Ok(child) => child,
Err(why) => panic!("Can't run test {}", why), Err(why) => panic!("Can't run test {why}"),
}; };
let output = process let output = process
@ -407,7 +407,7 @@ where
let out = collapse_output(&String::from_utf8_lossy(&output.stdout)); let out = collapse_output(&String::from_utf8_lossy(&output.stdout));
let err = String::from_utf8_lossy(&output.stderr); let err = String::from_utf8_lossy(&output.stderr);
println!("=== stderr\n{}", err); println!("=== stderr\n{err}");
Outcome::new(out, err.into_owned(), output.status) Outcome::new(out, err.into_owned(), output.status)
} }

View File

@ -77,12 +77,11 @@ where
T: AsRef<[u8]>, T: AsRef<[u8]>,
{ {
let stderr = std::io::stderr(); let stderr = std::io::stderr();
let ret = match stderr.lock().write_all(output.as_ref()) {
match stderr.lock().write_all(output.as_ref()) {
Ok(_) => Ok(stderr.lock().flush()?), Ok(_) => Ok(stderr.lock().flush()?),
Err(err) => Err(err), Err(err) => Err(err),
}; }
ret
} }
// See default_files/README.md for a description of these files // See default_files/README.md for a description of these files

View File

@ -51,18 +51,18 @@ impl SimplePluginCommand for FromPlist {
match input { match input {
NuValue::String { val, .. } => { NuValue::String { val, .. } => {
let plist = plist::from_bytes(val.as_bytes()) let plist = plist::from_bytes(val.as_bytes())
.map_err(|e| build_label_error(format!("{}", e), input.span()))?; .map_err(|e| build_label_error(format!("{e}"), input.span()))?;
let converted = convert_plist_value(&plist, call.head)?; let converted = convert_plist_value(&plist, call.head)?;
Ok(converted) Ok(converted)
} }
NuValue::Binary { val, .. } => { NuValue::Binary { val, .. } => {
let plist = plist::from_bytes(val) let plist = plist::from_bytes(val)
.map_err(|e| build_label_error(format!("{}", e), input.span()))?; .map_err(|e| build_label_error(format!("{e}"), input.span()))?;
let converted = convert_plist_value(&plist, call.head)?; let converted = convert_plist_value(&plist, call.head)?;
Ok(converted) Ok(converted)
} }
_ => Err(build_label_error( _ => Err(build_label_error(
format!("Invalid input, must be string not: {:?}", input), format!("Invalid input, must be string not: {input:?}"),
call.head, call.head,
)), )),
} }

View File

@ -42,14 +42,14 @@ impl SimplePluginCommand for IntoPlist {
let mut out = Vec::new(); let mut out = Vec::new();
if call.has_flag("binary")? { if call.has_flag("binary")? {
plist::to_writer_binary(&mut out, &plist_val) plist::to_writer_binary(&mut out, &plist_val)
.map_err(|e| build_label_error(format!("{}", e), input.span()))?; .map_err(|e| build_label_error(format!("{e}"), input.span()))?;
Ok(NuValue::binary(out, input.span())) Ok(NuValue::binary(out, input.span()))
} else { } else {
plist::to_writer_xml(&mut out, &plist_val) plist::to_writer_xml(&mut out, &plist_val)
.map_err(|e| build_label_error(format!("{}", e), input.span()))?; .map_err(|e| build_label_error(format!("{e}"), input.span()))?;
Ok(NuValue::string( Ok(NuValue::string(
String::from_utf8(out) String::from_utf8(out)
.map_err(|e| build_label_error(format!("{}", e), input.span()))?, .map_err(|e| build_label_error(format!("{e}"), input.span()))?,
input.span(), input.span(),
)) ))
} }
@ -77,7 +77,7 @@ fn convert_nu_value(nu_val: &NuValue) -> Result<PlistValue, LabeledError> {
NuValue::Date { val, .. } => Ok(PlistValue::Date(SystemTime::from(val.to_owned()).into())), NuValue::Date { val, .. } => Ok(PlistValue::Date(SystemTime::from(val.to_owned()).into())),
NuValue::Filesize { val, .. } => Ok(PlistValue::Integer(val.get().into())), NuValue::Filesize { val, .. } => Ok(PlistValue::Integer(val.get().into())),
_ => Err(build_label_error( _ => Err(build_label_error(
format!("{:?} is not convertible", nu_val), format!("{nu_val:?} is not convertible"),
span, span,
)), )),
} }

View File

@ -19,9 +19,7 @@ async fn aws_creds(aws_config: &SdkConfig) -> Result<Option<Credentials>, ShellE
error: format!( error: format!(
"Could not fetch AWS credentials: {} - {}", "Could not fetch AWS credentials: {} - {}",
e, e,
e.source() e.source().map(|e| format!("{e}")).unwrap_or("".to_string())
.map(|e| format!("{}", e))
.unwrap_or("".to_string())
), ),
msg: "".into(), msg: "".into(),
span: None, span: None,

View File

@ -97,7 +97,7 @@ fn dataframe_command(
input: Value, input: Value,
) -> Result<PipelineData, ShellError> { ) -> Result<PipelineData, ShellError> {
let df = NuDataFrame::try_from_value_coerce(plugin, &input, call.head)?; let df = NuDataFrame::try_from_value_coerce(plugin, &input, call.head)?;
let value = Value::string(format!("{}", df), call.head); let value = Value::string(format!("{df}"), call.head);
Ok(PipelineData::Value(value, None)) Ok(PipelineData::Value(value, None))
} }

View File

@ -64,14 +64,14 @@ pub(crate) fn datetime_commands() -> Vec<Box<dyn PluginCommand<Plugin = PolarsPl
pub fn timezone_from_str(zone_str: &str, span: Option<Span>) -> Result<TimeZone, ShellError> { pub fn timezone_from_str(zone_str: &str, span: Option<Span>) -> Result<TimeZone, ShellError> {
TimeZone::opt_try_new(Some(PlSmallStr::from_str(zone_str))) TimeZone::opt_try_new(Some(PlSmallStr::from_str(zone_str)))
.map_err(|e| ShellError::GenericError { .map_err(|e| ShellError::GenericError {
error: format!("Invalid timezone: {} : {}", zone_str, e), error: format!("Invalid timezone: {zone_str} : {e}"),
msg: "".into(), msg: "".into(),
span, span,
help: None, help: None,
inner: vec![], inner: vec![],
})? })?
.ok_or(ShellError::GenericError { .ok_or(ShellError::GenericError {
error: format!("Invalid timezone {}", zone_str), error: format!("Invalid timezone {zone_str}"),
msg: "".into(), msg: "".into(),
span, span,
help: None, help: None,

View File

@ -14,7 +14,7 @@ fn main() {
match PolarsPlugin::new() { match PolarsPlugin::new() {
Ok(ref plugin) => serve_plugin(plugin, MsgPackSerializer {}), Ok(ref plugin) => serve_plugin(plugin, MsgPackSerializer {}),
Err(e) => { Err(e) => {
eprintln!("{}", e); eprintln!("{e}");
std::process::exit(1); std::process::exit(1);
} }
} }

View File

@ -247,7 +247,7 @@ pub fn hover(engine_state: &mut EngineState, file_path: &str, location: &Value)
} }
description.push_str(" "); description.push_str(" ");
if let Some(short_flag) = &named.short { if let Some(short_flag) = &named.short {
description.push_str(&format!("`-{}`", short_flag)); description.push_str(&format!("`-{short_flag}`"));
} }
if !named.long.is_empty() { if !named.long.is_empty() {

View File

@ -360,7 +360,7 @@ pub fn input_bytes_length() {
let stdin = io::stdin(); let stdin = io::stdin();
let count = stdin.lock().bytes().count(); let count = stdin.lock().bytes().count();
println!("{}", count); println!("{count}");
} }
fn args() -> Vec<String> { fn args() -> Vec<String> {

Some files were not shown because too many files have changed in this diff Show More