forked from extern/nushell
Standardise the use of ShellError::UnsupportedInput and ShellError::TypeMismatch and add spans to every instance of the former (#7217)
# Description * I was dismayed to discover recently that UnsupportedInput and TypeMismatch are used *extremely* inconsistently across the codebase. UnsupportedInput is sometimes used for input type-checks (as per the name!!), but *also* used for argument type-checks. TypeMismatch is also used for both. I thus devised the following standard: input type-checking *only* uses UnsupportedInput, and argument type-checking *only* uses TypeMismatch. Moreover, to differentiate them, UnsupportedInput now has *two* error arrows (spans), one pointing at the command and the other at the input origin, while TypeMismatch only has the one (because the command should always be nearby) * In order to apply that standard, a very large number of UnsupportedInput uses were changed so that the input's span could be retrieved and delivered to it. * Additionally, I noticed many places where **errors are not propagated correctly**: there are lots of `match` sites which take a Value::Error, then throw it away and replace it with a new Value::Error with less/misleading information (such as reporting the error as an "incorrect type"). I believe that the earliest errors are the most important, and should always be propagated where possible. * Also, to standardise one broad subset of UnsupportedInput error messages, who all used slightly different wordings of "expected `<type>`, got `<type>`", I created OnlySupportsThisInputType as a variant of it. * Finally, a bunch of error sites that had "repeated spans" - i.e. where an error expected two spans, but `call.head` was given for both - were fixed to use different spans. # Example BEFORE ``` 〉20b | str starts-with 'a' Error: nu:🐚:unsupported_input (link) × Unsupported input ╭─[entry #31:1:1] 1 │ 20b | str starts-with 'a' · ┬ · ╰── Input's type is filesize. This command only works with strings. ╰──── 〉'a' | math cos Error: nu:🐚:unsupported_input (link) × Unsupported input ╭─[entry #33:1:1] 1 │ 'a' | math cos · ─┬─ · ╰── Only numerical values are supported, input type: String ╰──── 〉0x[12] | encode utf8 Error: nu:🐚:unsupported_input (link) × Unsupported input ╭─[entry #38:1:1] 1 │ 0x[12] | encode utf8 · ───┬── · ╰── non-string input ╰──── ``` AFTER ``` 〉20b | str starts-with 'a' Error: nu:🐚:pipeline_mismatch (link) × Pipeline mismatch. ╭─[entry #1:1:1] 1 │ 20b | str starts-with 'a' · ┬ ───────┬─────── · │ ╰── only string input data is supported · ╰── input type: filesize ╰──── 〉'a' | math cos Error: nu:🐚:pipeline_mismatch (link) × Pipeline mismatch. ╭─[entry #2:1:1] 1 │ 'a' | math cos · ─┬─ ────┬─── · │ ╰── only numeric input data is supported · ╰── input type: string ╰──── 〉0x[12] | encode utf8 Error: nu:🐚:pipeline_mismatch (link) × Pipeline mismatch. ╭─[entry #3:1:1] 1 │ 0x[12] | encode utf8 · ───┬── ───┬── · │ ╰── only string input data is supported · ╰── input type: binary ╰──── ``` # User-Facing Changes Various error messages suddenly make more sense (i.e. have two arrows instead of one). # Tests + Formatting Don't forget to add tests that cover your changes. Make sure you've run and fixed any issues with these commands: - `cargo fmt --all -- --check` to check standard code formatting (`cargo fmt --all` applies these changes) - `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect` to check that you're using the standard code style - `cargo test --workspace` to check that all tests pass # After Submitting If your PR had any user-facing changes, update [the documentation](https://github.com/nushell/nushell.github.io) after the PR is merged, if necessary. This will help us keep the docs up to date.
This commit is contained in:
@ -80,7 +80,7 @@ fn to_csv(
|
||||
} else {
|
||||
let vec_s: Vec<char> = s.chars().collect();
|
||||
if vec_s.len() != 1 {
|
||||
return Err(ShellError::UnsupportedInput(
|
||||
return Err(ShellError::TypeMismatch(
|
||||
"Expected a single separator char from --separator".to_string(),
|
||||
span,
|
||||
));
|
||||
|
@ -20,17 +20,17 @@ fn from_value_to_delimited_string(
|
||||
for (k, v) in cols.iter().zip(vals.iter()) {
|
||||
fields.push_back(k.clone());
|
||||
|
||||
values.push_back(to_string_tagged_value(v, config, *span)?);
|
||||
values.push_back(to_string_tagged_value(v, config, head, *span)?);
|
||||
}
|
||||
|
||||
wtr.write_record(fields).expect("can not write.");
|
||||
wtr.write_record(values).expect("can not write.");
|
||||
|
||||
let v = String::from_utf8(wtr.into_inner().map_err(|_| {
|
||||
ShellError::UnsupportedInput("Could not convert record".to_string(), *span)
|
||||
ShellError::CantConvert("record".to_string(), "string".to_string(), *span, None)
|
||||
})?)
|
||||
.map_err(|_| {
|
||||
ShellError::UnsupportedInput("Could not convert record".to_string(), *span)
|
||||
ShellError::CantConvert("record".to_string(), "string".to_string(), *span, None)
|
||||
})?;
|
||||
Ok(v)
|
||||
}
|
||||
@ -45,7 +45,7 @@ fn from_value_to_delimited_string(
|
||||
wtr.write_record(
|
||||
vals.iter()
|
||||
.map(|ele| {
|
||||
to_string_tagged_value(ele, config, *span)
|
||||
to_string_tagged_value(ele, config, head, *span)
|
||||
.unwrap_or_else(|_| String::new())
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
@ -59,7 +59,7 @@ fn from_value_to_delimited_string(
|
||||
let mut row = vec![];
|
||||
for desc in &merged_descriptors {
|
||||
row.push(match l.to_owned().get_data_by_key(desc) {
|
||||
Some(s) => to_string_tagged_value(&s, config, *span)?,
|
||||
Some(s) => to_string_tagged_value(&s, config, head, *span)?,
|
||||
None => String::new(),
|
||||
});
|
||||
}
|
||||
@ -67,18 +67,25 @@ fn from_value_to_delimited_string(
|
||||
}
|
||||
}
|
||||
let v = String::from_utf8(wtr.into_inner().map_err(|_| {
|
||||
ShellError::UnsupportedInput("Could not convert record".to_string(), *span)
|
||||
ShellError::CantConvert("record".to_string(), "string".to_string(), *span, None)
|
||||
})?)
|
||||
.map_err(|_| {
|
||||
ShellError::UnsupportedInput("Could not convert record".to_string(), *span)
|
||||
ShellError::CantConvert("record".to_string(), "string".to_string(), *span, None)
|
||||
})?;
|
||||
Ok(v)
|
||||
}
|
||||
_ => to_string_tagged_value(value, config, head),
|
||||
// Propagate errors by explicitly matching them before the final case.
|
||||
Value::Error { error } => Err(error.clone()),
|
||||
other => to_string_tagged_value(value, config, other.expect_span(), head),
|
||||
}
|
||||
}
|
||||
|
||||
fn to_string_tagged_value(v: &Value, config: &Config, span: Span) -> Result<String, ShellError> {
|
||||
fn to_string_tagged_value(
|
||||
v: &Value,
|
||||
config: &Config,
|
||||
span: Span,
|
||||
head: Span,
|
||||
) -> Result<String, ShellError> {
|
||||
match &v {
|
||||
Value::String { .. }
|
||||
| Value::Bool { .. }
|
||||
@ -86,7 +93,6 @@ fn to_string_tagged_value(v: &Value, config: &Config, span: Span) -> Result<Stri
|
||||
| Value::Duration { .. }
|
||||
| Value::Binary { .. }
|
||||
| Value::CustomValue { .. }
|
||||
| Value::Error { .. }
|
||||
| Value::Filesize { .. }
|
||||
| Value::CellPath { .. }
|
||||
| Value::List { .. }
|
||||
@ -94,9 +100,13 @@ fn to_string_tagged_value(v: &Value, config: &Config, span: Span) -> Result<Stri
|
||||
| Value::Float { .. } => Ok(v.clone().into_abbreviated_string(config)),
|
||||
Value::Date { val, .. } => Ok(val.to_string()),
|
||||
Value::Nothing { .. } => Ok(String::new()),
|
||||
// Propagate existing errors
|
||||
Value::Error { error } => Err(error.clone()),
|
||||
_ => Err(ShellError::UnsupportedInput(
|
||||
"Unexpected value".to_string(),
|
||||
v.span().unwrap_or(span),
|
||||
"Unexpected type".to_string(),
|
||||
format!("input type: {:?}", v.get_type()),
|
||||
head,
|
||||
span,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
@ -58,7 +58,9 @@ fn value_to_string(v: &Value, span: Span) -> Result<String, ShellError> {
|
||||
if write!(s, "{:02X}", byte).is_err() {
|
||||
return Err(ShellError::UnsupportedInput(
|
||||
"could not convert binary to string".into(),
|
||||
"value originates from here".into(),
|
||||
span,
|
||||
v.expect_span(),
|
||||
));
|
||||
}
|
||||
}
|
||||
@ -66,11 +68,15 @@ fn value_to_string(v: &Value, span: Span) -> Result<String, ShellError> {
|
||||
}
|
||||
Value::Block { .. } => Err(ShellError::UnsupportedInput(
|
||||
"blocks are currently not nuon-compatible".into(),
|
||||
"value originates from here".into(),
|
||||
span,
|
||||
v.expect_span(),
|
||||
)),
|
||||
Value::Closure { .. } => Err(ShellError::UnsupportedInput(
|
||||
"closure not supported".into(),
|
||||
"closures are currently not nuon-compatible".into(),
|
||||
"value originates from here".into(),
|
||||
span,
|
||||
v.expect_span(),
|
||||
)),
|
||||
Value::Bool { val, .. } => {
|
||||
if *val {
|
||||
@ -81,19 +87,21 @@ fn value_to_string(v: &Value, span: Span) -> Result<String, ShellError> {
|
||||
}
|
||||
Value::CellPath { .. } => Err(ShellError::UnsupportedInput(
|
||||
"cellpaths are currently not nuon-compatible".to_string(),
|
||||
"value originates from here".into(),
|
||||
span,
|
||||
v.expect_span(),
|
||||
)),
|
||||
Value::CustomValue { .. } => Err(ShellError::UnsupportedInput(
|
||||
"customs are currently not nuon-compatible".to_string(),
|
||||
"custom values are currently not nuon-compatible".to_string(),
|
||||
"value originates from here".into(),
|
||||
span,
|
||||
v.expect_span(),
|
||||
)),
|
||||
Value::Date { val, .. } => Ok(val.to_rfc3339()),
|
||||
// FIXME: make duratiobs use the shortest lossless representation.
|
||||
// FIXME: make durations use the shortest lossless representation.
|
||||
Value::Duration { val, .. } => Ok(format!("{}ns", *val)),
|
||||
Value::Error { .. } => Err(ShellError::UnsupportedInput(
|
||||
"errors are currently not nuon-compatible".to_string(),
|
||||
span,
|
||||
)),
|
||||
// Propagate existing errors
|
||||
Value::Error { error } => Err(error.clone()),
|
||||
// FIXME: make filesizes use the shortest lossless representation.
|
||||
Value::Filesize { val, .. } => Ok(format!("{}b", *val)),
|
||||
Value::Float { val, .. } => {
|
||||
|
@ -130,7 +130,9 @@ fn value_to_toml_value(
|
||||
Value::List { ref vals, span } => match &vals[..] {
|
||||
[Value::Record { .. }, _end @ ..] => helper(engine_state, v),
|
||||
_ => Err(ShellError::UnsupportedInput(
|
||||
"Expected a table with TOML-compatible structure from pipeline".to_string(),
|
||||
"Expected a table with TOML-compatible structure".to_string(),
|
||||
"value originates from here".into(),
|
||||
head,
|
||||
*span,
|
||||
)),
|
||||
},
|
||||
@ -138,14 +140,20 @@ fn value_to_toml_value(
|
||||
// Attempt to de-serialize the String
|
||||
toml::de::from_str(val).map_err(|_| {
|
||||
ShellError::UnsupportedInput(
|
||||
format!("{:?} unable to de-serialize string to TOML", val),
|
||||
"unable to de-serialize string to TOML".into(),
|
||||
format!("input: '{:?}'", val),
|
||||
head,
|
||||
*span,
|
||||
)
|
||||
})
|
||||
}
|
||||
// Propagate existing errors
|
||||
Value::Error { error } => Err(error.clone()),
|
||||
_ => Err(ShellError::UnsupportedInput(
|
||||
format!("{:?} is not a valid top-level TOML", v.get_type()),
|
||||
v.span().unwrap_or(head),
|
||||
format!("{:?} is not valid top-level TOML", v.get_type()),
|
||||
"value originates from here".into(),
|
||||
head,
|
||||
v.expect_span(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
@ -47,7 +47,9 @@ fn to_url(input: PipelineData, head: Span) -> Result<PipelineData, ShellError> {
|
||||
.into_iter()
|
||||
.map(move |value| match value {
|
||||
Value::Record {
|
||||
ref cols, ref vals, ..
|
||||
ref cols,
|
||||
ref vals,
|
||||
span,
|
||||
} => {
|
||||
let mut row_vec = vec![];
|
||||
for (k, v) in cols.iter().zip(vals.iter()) {
|
||||
@ -57,8 +59,10 @@ fn to_url(input: PipelineData, head: Span) -> Result<PipelineData, ShellError> {
|
||||
}
|
||||
_ => {
|
||||
return Err(ShellError::UnsupportedInput(
|
||||
"Expected table with string values".to_string(),
|
||||
"Expected a record with string values".to_string(),
|
||||
"value originates from here".into(),
|
||||
head,
|
||||
span,
|
||||
));
|
||||
}
|
||||
}
|
||||
@ -74,9 +78,13 @@ fn to_url(input: PipelineData, head: Span) -> Result<PipelineData, ShellError> {
|
||||
)),
|
||||
}
|
||||
}
|
||||
// Propagate existing errors
|
||||
Value::Error { error } => Err(error),
|
||||
other => Err(ShellError::UnsupportedInput(
|
||||
"Expected a table from pipeline".to_string(),
|
||||
other.span().unwrap_or(head),
|
||||
"value originates from here".into(),
|
||||
head,
|
||||
other.expect_span(),
|
||||
)),
|
||||
})
|
||||
.collect();
|
||||
|
Reference in New Issue
Block a user