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);
bench_command(
format!("record_nested_access_{n}"),
format!("$record{} | ignore", nested_access),
format!("$record{nested_access} | ignore"),
stack,
engine,
)
@ -319,7 +319,7 @@ fn bench_eval_par_each(n: usize) -> impl IntoBenchmarks {
let stack = Stack::new();
bench_command(
format!("eval_par_each_{n}"),
format!("(1..{}) | par-each -t 2 {{|_| 1 }} | ignore", n),
format!("(1..{n}) | par-each -t 2 {{|_| 1 }} | ignore"),
stack,
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());
[benchmark_fn(
format!("encode_json_{}_{}", row_cnt, col_cnt),
format!("encode_json_{row_cnt}_{col_cnt}"),
move |b| {
let encoder = encoder.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());
[benchmark_fn(
format!("encode_msgpack_{}_{}", row_cnt, col_cnt),
format!("encode_msgpack_{row_cnt}_{col_cnt}"),
move |b| {
let encoder = encoder.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();
[benchmark_fn(
format!("decode_json_{}_{}", row_cnt, col_cnt),
format!("decode_json_{row_cnt}_{col_cnt}"),
move |b| {
let res = res.clone();
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();
[benchmark_fn(
format!("decode_msgpack_{}_{}", row_cnt, col_cnt),
format!("decode_msgpack_{row_cnt}_{col_cnt}"),
move |b| {
let res = res.clone();
b.iter(move || {

View File

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

View File

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

View File

@ -176,7 +176,7 @@ impl NuCompleter {
&mut working_set,
Some("completer"),
// Add a placeholder `a` to the end
format!("{}a", line).as_bytes(),
format!("{line}a").as_bytes(),
false,
);
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 {
let result = completer.fetch_completions_at(line, line.len());
// 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
result
@ -865,8 +865,7 @@ mod completer_tests {
.filter(|x| *x)
.count(),
expected_values.len(),
"line: {}",
line
"line: {line}"
);
}
}

View File

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

View File

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

View File

@ -239,7 +239,7 @@ fn escape_special_vscode_bytes(input: &str) -> Result<String, ShellError> {
match byte {
// 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
b';' => "\\x3B".to_string().into_bytes(),
// Escape backslash as \\
@ -1097,8 +1097,7 @@ fn run_shell_integration_osc633(
// If we're in vscode, run their specific ansi escape sequence.
// This is helpful for ctrl+g to change directories in the terminal.
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!(
@ -1114,10 +1113,7 @@ fn run_shell_integration_osc633(
//OSC 633 ; E ; <commandline> [; <nonce] ST - Explicitly set the command line with an optional nonce.
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.
let op = parse_operation(input.to_string(), &engine_state, &stack).unwrap();
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.

View File

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

View File

@ -188,7 +188,7 @@ fn get_theme_from_asset_file(
Some(t) => t,
None => {
return Err(ShellError::TypeMismatch {
err_message: format!("Unknown HTML theme '{}'", theme_name),
err_message: format!("Unknown HTML theme '{theme_name}'"),
span: theme_span,
});
}
@ -774,8 +774,7 @@ mod tests {
for key in required_keys {
assert!(
theme_map.contains_key(key),
"Expected theme to contain key '{}'",
key
"Expected theme to contain key '{key}'"
);
}
}
@ -792,15 +791,13 @@ mod tests {
if let Err(err) = result {
assert!(
matches!(err, ShellError::TypeMismatch { .. }),
"Expected TypeMismatch error, got: {:?}",
err
"Expected TypeMismatch error, got: {err:?}"
);
if let ShellError::TypeMismatch { err_message, span } = err {
assert!(
err_message.contains("doesnt-exist"),
"Error message should mention theme name, got: {}",
err_message
"Error message should mention theme name, got: {err_message}"
);
assert_eq!(span.start, 0);
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 mut raw_string = "".to_string();
for ch in bytes {
raw_string.push_str(&format!("{:08b} ", ch));
raw_string.push_str(&format!("{ch:08b} "));
}
Value::string(raw_string.trim(), span)
} else if let Some(v) = num.to_i16() {
let bytes = v.to_ne_bytes();
let mut raw_string = "".to_string();
for ch in bytes {
raw_string.push_str(&format!("{:08b} ", ch));
raw_string.push_str(&format!("{ch:08b} "));
}
Value::string(raw_string.trim(), span)
} else if let Some(v) = num.to_i32() {
let bytes = v.to_ne_bytes();
let mut raw_string = "".to_string();
for ch in bytes {
raw_string.push_str(&format!("{:08b} ", ch));
raw_string.push_str(&format!("{ch:08b} "));
}
Value::string(raw_string.trim(), span)
} else {
let bytes = num.to_ne_bytes();
let mut raw_string = "".to_string();
for ch in bytes {
raw_string.push_str(&format!("{:08b} ", ch));
raw_string.push_str(&format!("{ch:08b} "));
}
Value::string(raw_string.trim(), span)
}
@ -193,7 +193,7 @@ fn action(input: &Value, _args: &Arguments, span: Span) -> Value {
Value::Binary { val, .. } => {
let mut raw_string = "".to_string();
for ch in val {
raw_string.push_str(&format!("{:08b} ", ch));
raw_string.push_str(&format!("{ch:08b} "));
}
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 mut raw_string = "".to_string();
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)
}

View File

@ -296,7 +296,7 @@ fn run(
} else {
let value = stream.into_value();
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, ..) => {

View File

@ -229,7 +229,7 @@ fn make_other_error(value: &Value, throw_span: Option<Span>) -> ShellError {
error: "invalid error format.".into(),
msg: "`$.label.start` should be smaller than `$.label.end`".into(),
span: Some(label_span),
help: Some(format!("{} > {}", span_start, span_end)),
help: Some(format!("{span_start} > {span_end}")),
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 {
match self.0 {
Value::Bool { val, .. } => {
write!(f, "{:?}", val)
write!(f, "{val:?}")
}
Value::Int { val, .. } => {
write!(f, "{:?}", val)
write!(f, "{val:?}")
}
Value::Float { val, .. } => {
write!(f, "{:?}f", val)
write!(f, "{val:?}f")
}
Value::Filesize { val, .. } => {
write!(f, "Filesize({:?})", val)
write!(f, "Filesize({val:?})")
}
Value::Duration { val, .. } => {
let duration = std::time::Duration::from_nanos(*val as u64);
write!(f, "Duration({:?})", duration)
write!(f, "Duration({duration:?})")
}
Value::Date { val, .. } => {
write!(f, "Date({:?})", val)
write!(f, "Date({val:?})")
}
Value::Range { val, .. } => match **val {
Range::IntRange(range) => match range.end() {
@ -280,7 +280,7 @@ impl std::fmt::Debug for DebuggableValue<'_> {
},
},
Value::String { val, .. } | Value::Glob { val, .. } => {
write!(f, "{:?}", val)
write!(f, "{val:?}")
}
Value::Record { val, .. } => {
write!(f, "{{")?;
@ -305,22 +305,22 @@ impl std::fmt::Debug for DebuggableValue<'_> {
write!(f, "]")
}
Value::Closure { val, .. } => {
write!(f, "Closure({:?})", val)
write!(f, "Closure({val:?})")
}
Value::Nothing { .. } => {
write!(f, "Nothing")
}
Value::Error { error, .. } => {
write!(f, "Error({:?})", error)
write!(f, "Error({error:?})")
}
Value::Binary { val, .. } => {
write!(f, "Binary({:?})", val)
write!(f, "Binary({val:?})")
}
Value::CellPath { val, .. } => {
write!(f, "CellPath({:?})", val.to_string())
}
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 {}",
forbidden_column_names
.iter()
.map(|val| format!("'{}'", val))
.map(|val| format!("'{val}'"))
.collect::<Vec<_>>()
.join(", ")
),

View File

@ -678,7 +678,7 @@ fn parse_value_from_record_as_u32(
Value::Int { val, .. } => {
if *val < 0 || *val > u32::MAX as i64 {
return Err(ShellError::IncorrectValue {
msg: format!("incorrect value for {}", col),
msg: format!("incorrect value for {col}"),
val_span: *head,
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()) {
let allowed_signs = ALLOWED_SIGNS.join(", ");
return Err(ShellError::IncorrectValue {
msg: format!("Invalid sign. Allowed signs are {}", allowed_signs)
.to_string(),
msg: format!("Invalid sign. Allowed signs are {allowed_signs}").to_string(),
val_span: sign.span(),
call_span: head,
});

View File

@ -122,8 +122,8 @@ impl Table {
.conn
.query_row(&table_exists_query, [], |row| row.get(0))
.map_err(|err| ShellError::GenericError {
error: format!("{:#?}", err),
msg: format!("{:#?}", err),
error: format!("{err:#?}"),
msg: format!("{err:#?}"),
span: None,
help: None,
inner: Vec::new(),
@ -257,7 +257,7 @@ fn insert_in_transaction(
let insert_statement = format!(
"INSERT INTO [{}] ({}) VALUES ({})",
table_name,
Itertools::intersperse(val.columns().map(|c| format!("`{}`", c)), ", ".to_string())
Itertools::intersperse(val.columns().map(|c| format!("`{c}`")), ", ".to_string())
.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))
.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,
) -> Result<(), SqliteError> {
//vacuum main into 'c:\\temp\\foo.db'
conn.execute(&format!("vacuum main into '{}'", filename), [])?;
conn.execute(&format!("vacuum main into '{filename}'"), [])?;
Ok(())
}

View File

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

View File

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

View File

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

View File

@ -272,8 +272,8 @@ impl Command for UCp {
uu_cp::Error::NotAllFilesCopied => {}
_ => {
return Err(ShellError::GenericError {
error: format!("{}", error),
msg: format!("{}", error),
error: format!("{error}"),
msg: format!("{error}"),
span: None,
help: None,
inner: vec![],
@ -373,7 +373,7 @@ fn parse_and_set_attribute(
"xattr" => &mut attribute.xattr,
_ => {
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(),
});
}

View File

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

View File

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

View File

@ -220,7 +220,7 @@ impl Command for UTouch {
inner: Vec::new(),
},
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"),
call_span: call.head,
},

View File

@ -334,7 +334,7 @@ fn closure_variable_warning(
Cow::Owned(s) if s.deref() == "$carapace_completer" => {
carapace_suggestion.to_string()
}
_ => format!("change this to {{ {} }}", span_contents).to_string(),
_ => format!("change this to {{ {span_contents} }}").to_string(),
};
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());
// Do not output shared join key twice
if !(k_seen && k_shared) {
record.push(
if k_seen { format!("{}_", k) } else { k.clone() },
v.clone(),
);
record.push(if k_seen { format!("{k}_") } else { k.clone() }, v.clone());
}
}
record

View File

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

View File

@ -167,7 +167,7 @@ fn parse_aligned_columns<'a>(
let headers: Vec<(String, usize)> = indices
.iter()
.enumerate()
.map(|(i, position)| (format!("column{}", i), *position))
.map(|(i, position)| (format!("column{i}"), *position))
.collect();
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,
),
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(
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) => {
let tag = &t.tag;
let value = match &t.value {
match &t.value {
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)
}
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)
}
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)
}
serde_yaml::Value::Null => {
let val = format!("{}", tag).trim().to_string();
let val = format!("{tag}").trim().to_string();
Value::string(val, span)
}
v => convert_yaml_value_to_nu_value(v, span, val_span)?,
};
value
}
}
serde_yaml::Value::Null => Value::nothing(span),
x => unimplemented!("Unsupported YAML case: {:?}", x),

View File

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

View File

@ -246,7 +246,7 @@ fn table(
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()
{
String::from("")
@ -260,9 +260,7 @@ fn table(
)
.trim()
.to_string()
};
output_string
}
}
pub fn group_by(values: PipelineData, head: Span, config: &Config) -> (PipelineData, bool) {

View File

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

View File

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

View File

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

View File

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

View File

@ -64,7 +64,7 @@ impl Registry for NuShellNightly {
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
.add_header("Accept", "application/vnd.github.v3+json")
.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() {
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)
} else {
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() {
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)
} else {
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 {
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(),
msg_span: head,
input_span: val_span,

View File

@ -135,8 +135,7 @@ fn uuid(
_ => {
return Err(ShellError::IncorrectValue {
msg: format!(
"Unsupported UUID version: {}. Supported versions are 1, 3, 4, 5, and 7.",
version
"Unsupported UUID version: {version}. Supported versions are 1, 3, 4, 5, and 7."
),
val_span: span,
call_span: span,
@ -190,8 +189,7 @@ fn validate_flags(
if v != 4 && v != 7 {
return Err(ShellError::IncorrectValue {
msg: format!(
"Unsupported UUID version: {}. Supported versions are 1, 3, 4, 5, and 7.",
v
"Unsupported UUID version: {v}. Supported versions are 1, 3, 4, 5, and 7."
),
val_span: span,
call_span: span,
@ -202,7 +200,7 @@ fn validate_flags(
.is_some()
{
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,
});
}
@ -211,7 +209,7 @@ fn validate_flags(
.is_some()
{
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,
});
}
@ -220,7 +218,7 @@ fn validate_flags(
.is_some()
{
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,
});
}

View File

@ -81,33 +81,32 @@ fn process(
if let Ok(conn) = db.open_connection() {
match columns {
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 {
match column_datatype.coerce_str()?.as_ref() {
"int" => {
create_stmt.push_str(&format!("{} INTEGER, ", column_name));
create_stmt.push_str(&format!("{column_name} INTEGER, "));
}
"float" => {
create_stmt.push_str(&format!("{} REAL, ", column_name));
create_stmt.push_str(&format!("{column_name} REAL, "));
}
"str" => {
create_stmt.push_str(&format!("{} VARCHAR(255), ", column_name));
create_stmt.push_str(&format!("{column_name} VARCHAR(255), "));
}
"bool" => {
create_stmt.push_str(&format!("{} BOOLEAN, ", column_name));
create_stmt.push_str(&format!("{column_name} BOOLEAN, "));
}
"datetime" => {
create_stmt.push_str(&format!(
"{} DATETIME DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')), ",
column_name
"{column_name} DATETIME DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')), "
));
}
_ => {
return Err(ShellError::UnsupportedInput {
msg: "unsupported column data type".into(),
input: format!("{:?}", column_datatype),
input: format!("{column_datatype:?}"),
msg_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 {
None => {
// We're deleting an entire table
format!("DROP TABLE {}", new_table_name)
format!("DROP TABLE {new_table_name}")
}
Some(where_clause) => {
// 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
// --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.
delete_stmt.push_str(&format!("WHERE {}", where_clause));
delete_stmt.push_str(&format!("WHERE {where_clause}"));
delete_stmt
}
};

View File

@ -164,7 +164,7 @@ fn process(
}
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 cols = record.columns();

View File

@ -164,7 +164,7 @@ fn process(
}
let new_table_name = table_name.unwrap_or("table".into());
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 ");
let mut placeholders: Vec<String> = Vec::new();

View File

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

View File

@ -155,9 +155,9 @@ fn format_value_impl(val: &Value, arg: &Arguments, span: Span) -> Value {
&arg.format_value.item
};
if d.fract() == 0.0 {
Value::string(format!("{} {}", d, unit), inner_span)
Value::string(format!("{d} {unit}"), inner_span)
} 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),

View File

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

View File

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

View File

@ -106,7 +106,7 @@ impl Command for NuCheck {
Err(err) => return Err(err),
};
let result = if as_module || path.is_dir() {
if as_module || path.is_dir() {
parse_file_or_dir_module(
path.to_string_lossy().as_bytes(),
&mut working_set,
@ -120,9 +120,7 @@ impl Command for NuCheck {
working_set.files = FileStack::with_file(path.clone());
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.
};
result
}
} else {
Err(ShellError::GenericError {
error: "Failed to execute command".into(),

View File

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

View File

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

View File

@ -170,7 +170,7 @@ fn glob_files_in_parent(
let expected = expected
.join(" ")
.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]
fn into_int_datetime1() {
let dt = DateTime::parse_from_rfc3339("1983-04-13T12:09:14.123456789+00:00");
eprintln!("dt debug {:?}", dt);
eprintln!("dt debug {dt:?}");
assert_eq!(
dt,
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]]"),
] {
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;
assert_eq!(actual, expected);
// Test again with streaming input (using `each` to convert the input into a ListStream)
let to_list_stream = "each { |i| $i } | ";
let expr = format!(
"{} | {} join {} {} {} | to nuon",
left, to_list_stream, right, join_type, on
);
let expr = format!("{left} | {to_list_stream} join {right} {join_type} {on} | to nuon");
let actual = nu!(expr).out;
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 {
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;
assert_eq!(actual, expected);
// Test again with streaming input (using `each` to convert the input into a ListStream)
let to_list_stream = "each { |i| $i } | ";
let expr = format!(
"{} | {} join {} {} {} | to nuon",
left, to_list_stream, right, join_type, on
);
let expr =
format!("{left} | {to_list_stream} join {right} {join_type} {on} | to nuon");
let actual = nu!(expr).out;
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 {
if join_type_ == join_type {
let expr = format!(
"{} | join {} {} {} {} | to nuon",
left, right, join_type, left_on, right_on
);
let expr =
format!("{left} | join {right} {join_type} {left_on} {right_on} | to nuon");
let actual = nu!(expr).out;
assert_eq!(actual, expected);
// Test again with streaming input (using `each` to convert the input into a ListStream)
let to_list_stream = "each { |i| $i } | ";
let expr = format!(
"{} | {} join {} {} {} {} | to nuon",
left, to_list_stream, right, join_type, left_on, right_on
"{left} | {to_list_stream} join {right} {join_type} {left_on} {right_on} | to nuon"
);
let actual = nu!(expr).out;
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]]"),
] {
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;
assert_eq!(actual, expected, "Expression was {}", &expr);
}

View File

@ -10,7 +10,7 @@ fn creates_temp_file() {
"mktemp"
);
let loc = AbsolutePath::try_new(&output.out).unwrap();
println!("{:?}", loc);
println!("{loc:?}");
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 ] ],\
field1: [ a, b, c ],\
field2: [ 123, 234, 345 ],\
field3: {},\
field3: {table1},\
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 ] ],\
}}",
table1
}}"
);
let actual = nu!(format!(
"$env.config.table.footer_inheritance = true; {structure} | table --width=80 --expand"

View File

@ -24,7 +24,7 @@ fn row_but_all() {
#[test]
fn throw_inner_error() {
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!(
"[[key value]; [foo 1] [foo 2] [{} 3]] | transpose",
error

View File

@ -540,10 +540,7 @@ fn change_file_times_to_date() {
assert!(
got_atime.signed_duration_since(expected).lt(&threshold)
&& got_mtime.signed_duration_since(expected).lt(&threshold),
"Expected: {}. Got: atime={}, mtime={}",
expected,
got_atime,
got_mtime
"Expected: {expected}. Got: atime={got_atime}, mtime={got_mtime}"
);
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");
let mut outcome = None;
Playground::setup(&format!("msgpack test {}", fixture_name), |dirs, _| {
Playground::setup(&format!("msgpack test {fixture_name}"), |dirs, _| {
assert!(
nu!(
cwd: dirs.test(),

View File

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

View File

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

View File

@ -754,7 +754,7 @@ where
long_desc.push_str(" ");
// Short flag shown before long flag
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() {
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();
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.");

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 try_cwd = expanded_path.as_path() == Path::new(path);
if try_cwd {
let cwd_path = format!("./{}", path);
let cwd_path = format!("./{path}");
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 {
if width == 0 {
format!("{:x}", n)
format!("{n:x}")
} 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() {
let pat = Pattern::new("a[0-9]b").unwrap();
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"));
let pat = Pattern::new("a[!0-9]b").unwrap();
for i in 0..10 {
assert!(!pat.matches(&format!("a{}b", i)));
assert!(!pat.matches(&format!("a{i}b")));
}
assert!(pat.matches("a_b"));

View File

@ -84,7 +84,7 @@ impl LanguageServer {
idx += 1;
match &arg.shape {
SyntaxShape::Block | SyntaxShape::MatchBlock => {
format!("{{ ${{{}:{}}} }}", idx, text)
format!("{{ ${{{idx}:{text}}} }}")
}
SyntaxShape::Keyword(kwd, _) => {
// 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!("${{{}:{}}}", idx, text),
_ => format!("${{{idx}:{text}}}"),
}
};

View File

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

View File

@ -165,9 +165,9 @@ impl LanguageServer {
.map(|val| {
let ty = val.get_type();
if let Ok(s) = val.coerce_str() {
format!("```\n{}\n```\n---\n{}", ty, s)
format!("```\n{ty}\n```\n---\n{s}")
} else {
format!("```\n{}\n```", ty)
format!("```\n{ty}\n```")
}
})
.unwrap_or("`unknown`".into()),
@ -186,7 +186,7 @@ impl LanguageServer {
.join("\n");
markdown_hover(description)
}
Id::Value(t) => markdown_hover(format!("`{}`", t)),
Id::Value(t) => markdown_hover(format!("`{t}`")),
Id::External(cmd) => {
let command_output = if cfg!(windows) {
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 {
shape = *inner_shape;
}
text.push_str(&format!(": `<{}>`", shape));
text.push_str(&format!(": `<{shape}>`"));
}
if !(desc.is_empty() && default_value.is_none()) || optional {
text.push_str(" -")
};
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()) {
text.push_str(&format!(

View File

@ -2160,12 +2160,10 @@ fn module_needs_reloading(working_set: &StateWorkingSet, module_id: ModuleId) ->
return true;
}
let private_submodule_changed = module
module
.imported_modules
.iter()
.any(|submodule_id| submodule_need_reloading(working_set, *submodule_id));
private_submodule_changed
.any(|submodule_id| submodule_need_reloading(working_set, *submodule_id))
}
/// 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> {
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())
}

View File

@ -37,7 +37,7 @@ pub fn parse_shape_name(
span: Span,
use_loc: ShapeDescriptorUse,
) -> SyntaxShape {
let result = match bytes {
match bytes {
b"any" => SyntaxShape::Any,
b"binary" => SyntaxShape::Binary,
b"block" => {
@ -106,20 +106,18 @@ pub fn parse_shape_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 {
working_set.error(ParseError::UnknownCommand(cmd_span));
return shape;
shape
}
} else {
//TODO: Handle error case for unknown shapes
working_set.error(ParseError::UnknownType(span));
return SyntaxShape::Any;
SyntaxShape::Any
}
}
};
result
}
}
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)
} else {
working_set.error(ParseError::InvalidLiteral(
format!("invalid digits for radix {}", radix),
format!("invalid digits for radix {radix}"),
"int".into(),
span,
));
@ -3387,10 +3387,7 @@ pub fn parse_import_pattern(working_set: &mut StateWorkingSet, spans: &[Span]) -
"list"
};
working_set.error(ParseError::WrongImportPattern(
format!(
"{} member can be only at the end of an import pattern",
what
),
format!("{what} member can be only at the end of an import pattern"),
prev_span,
));
return Expression::new(
@ -6116,7 +6113,7 @@ fn check_record_key_or_value(
let colon_position = i + string_value.span.start;
ParseError::InvalidLiteral(
"colon".to_string(),
format!("bare word specifying record {}", position),
format!("bare word specifying record {position}"),
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(parse_err) = err {
let act_err = format!("{:?}", parse_err);
let act_err = format!("{parse_err:?}");
assert!(
act_err.contains(err_pat),
"{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; $"] {
let input = format!(
r#"{}foo = 1 |
r#"{prefix}foo = 1 |
# comment
dummy"#,
prefix
dummy"#
);
let block = parse(&mut working_set, None, input.as_bytes(), true);
let last_expr = &block.pipelines.last().unwrap().elements[0].expr.expr;
@ -2783,11 +2782,11 @@ mod input_types {
call.arguments[1].expr().unwrap()
}
Expr::BinaryOp(_, _, rhs) => rhs.as_ref(),
_ => panic!("Unexpected expression: {:?}", last_expr),
_ => panic!("Unexpected expression: {last_expr:?}"),
};
let block_id = match block_expr.expr {
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);
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")
.to_string_lossy()
.into_owned();
println!("{}", name);
println!("{name}");
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")
.to_string_lossy()
.into_owned();
println!("{}", name);
println!("{name}");
assert!(name.to_string().contains("test-string"));
}

View File

@ -201,7 +201,7 @@ fn reader_drop() {
impl WriteStreamMessage for Check {
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);
Ok(())
}

View File

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

View File

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

View File

@ -276,11 +276,11 @@ impl PluginTest {
)?;
(
format!("{:#?}", expectation_base),
format!("{:#?}", value_base),
format!("{expectation_base:#?}"),
format!("{value_base:#?}"),
)
}
_ => (format!("{:#?}", expectation), format!("{:#?}", value)),
_ => (format!("{expectation:#?}"), format!("{value:#?}")),
};
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()
.map(|stem| stem.to_string_lossy().into_owned())
.unwrap_or_else(|| "(unknown)".into());
println!("Plugin file path: {}", plugin_name);
println!("Plugin file path: {plugin_name}");
let mut help = String::new();
let help_style = HelpStyle::default();
@ -685,7 +685,7 @@ fn print_help(plugin: &impl Plugin, encoder: impl PluginEncoder) {
})
.and_then(|_| {
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(),
});
write!(help, "{flags}")

View File

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

View File

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

View File

@ -1511,15 +1511,15 @@ fn shell_error_serialize_roundtrip() {
from_type: "Bar".into(),
help: Some("this is a test".into()),
};
println!("orig_error = {:#?}", original_error);
println!("orig_error = {original_error:#?}");
let serialized =
serde_json::to_string_pretty(&original_error).expect("serde_json::to_string_pretty failed");
println!("serialized = {}", serialized);
println!("serialized = {serialized}");
let deserialized: ShellError =
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
// properties should be comparable

View File

@ -429,7 +429,7 @@ impl fmt::Display for FmtPattern<'_> {
}
Pattern::Variable(var_id) => {
let variable = FmtVar::new(self.engine_state, *var_id);
write!(f, "{}", variable)
write!(f, "{variable}")
}
Pattern::Or(patterns) => {
for (index, pattern) in patterns.iter().enumerate() {
@ -449,7 +449,7 @@ impl fmt::Display for FmtPattern<'_> {
}
Pattern::Rest(var_id) => {
let variable = FmtVar::new(self.engine_state, *var_id);
write!(f, "..{}", variable)
write!(f, "..{variable}")
}
Pattern::IgnoreRest => 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> {
let n = a.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 {
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
// big difference in length.
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)?;
// 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 {
Ok(value) => string.push_str(&value.into_string().expect("not a string")),
Err(err) => {
println!("string so far: {:?}", string);
println!("string so far: {string:?}");
println!("got error: {err:?}");
assert!(!string.is_empty());
assert!(matches!(err, ShellError::NonUtf8Custom { .. }));

View File

@ -773,7 +773,7 @@ where
T: AsRef<[u8]>,
{
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 {
None => 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| {
assert!(
!self.get_shorts().contains(c),
"There may be duplicate short flags for '-{}'",
c
"There may be duplicate short flags for '-{c}'"
);
});
@ -530,8 +529,7 @@ impl Signature {
let name: String = name.into();
assert!(
!self.get_names().contains(&name.as_str()),
"There may be duplicate name flags for '--{}'",
name
"There may be duplicate name flags for '--{name}'"
);
name
};

View File

@ -924,7 +924,7 @@ impl Value {
match formatter_buf.write_fmt(format_args!("{format}")) {
Ok(_) => (),
Err(_) => formatter_buf = format!("Invalid format string {}", formatter),
Err(_) => formatter_buf = format!("Invalid format string {formatter}"),
}
formatter_buf
}
@ -1035,7 +1035,7 @@ impl Value {
pub fn to_parsable_string(&self, separator: &str, config: &Config) -> String {
match self {
// 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
Value::List { vals: val, .. } => format!(
"[{}]",

View File

@ -39,7 +39,7 @@ pub fn build_kill_command(
} else {
let mut cmd = CommandSys::new("kill");
if let Some(signal_value) = signal {
cmd.arg(format!("-{}", signal_value));
cmd.arg(format!("-{signal_value}"));
} else if force {
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()
};
println!("=== stderr\n{}", err);
println!("=== stderr\n{err}");
Outcome::new(out, err.into_owned(), output.status)
}
@ -397,7 +397,7 @@ where
.spawn()
{
Ok(child) => child,
Err(why) => panic!("Can't run test {}", why),
Err(why) => panic!("Can't run test {why}"),
};
let output = process
@ -407,7 +407,7 @@ where
let out = collapse_output(&String::from_utf8_lossy(&output.stdout));
let err = String::from_utf8_lossy(&output.stderr);
println!("=== stderr\n{}", err);
println!("=== stderr\n{err}");
Outcome::new(out, err.into_owned(), output.status)
}

View File

@ -77,12 +77,11 @@ where
T: AsRef<[u8]>,
{
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()?),
Err(err) => Err(err),
};
ret
}
}
// See default_files/README.md for a description of these files

View File

@ -51,18 +51,18 @@ impl SimplePluginCommand for FromPlist {
match input {
NuValue::String { val, .. } => {
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)?;
Ok(converted)
}
NuValue::Binary { 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)?;
Ok(converted)
}
_ => Err(build_label_error(
format!("Invalid input, must be string not: {:?}", input),
format!("Invalid input, must be string not: {input:?}"),
call.head,
)),
}

View File

@ -42,14 +42,14 @@ impl SimplePluginCommand for IntoPlist {
let mut out = Vec::new();
if call.has_flag("binary")? {
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()))
} else {
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(
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(),
))
}
@ -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::Filesize { val, .. } => Ok(PlistValue::Integer(val.get().into())),
_ => Err(build_label_error(
format!("{:?} is not convertible", nu_val),
format!("{nu_val:?} is not convertible"),
span,
)),
}

View File

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

View File

@ -97,7 +97,7 @@ fn dataframe_command(
input: Value,
) -> Result<PipelineData, ShellError> {
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))
}

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> {
TimeZone::opt_try_new(Some(PlSmallStr::from_str(zone_str)))
.map_err(|e| ShellError::GenericError {
error: format!("Invalid timezone: {} : {}", zone_str, e),
error: format!("Invalid timezone: {zone_str} : {e}"),
msg: "".into(),
span,
help: None,
inner: vec![],
})?
.ok_or(ShellError::GenericError {
error: format!("Invalid timezone {}", zone_str),
error: format!("Invalid timezone {zone_str}"),
msg: "".into(),
span,
help: None,

View File

@ -14,7 +14,7 @@ fn main() {
match PolarsPlugin::new() {
Ok(ref plugin) => serve_plugin(plugin, MsgPackSerializer {}),
Err(e) => {
eprintln!("{}", e);
eprintln!("{e}");
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(" ");
if let Some(short_flag) = &named.short {
description.push_str(&format!("`-{}`", short_flag));
description.push_str(&format!("`-{short_flag}`"));
}
if !named.long.is_empty() {

View File

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

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