Better generic errors for plugins (and perhaps scripts) (#12236)

# Description
This makes `LabeledError` much more capable of representing close to
everything a `miette::Diagnostic` can, including `ShellError`, and
allows plugins to generate multiple error spans, codes, help, etc.

`LabeledError` is now embeddable within `ShellError` as a transparent
variant.

This could also be used to improve `error make` and `try/catch` to
reflect `LabeledError` exactly in the future.

Also cleaned up some errors in existing plugins.

# User-Facing Changes
Breaking change for plugins. Nicer errors for users.
This commit is contained in:
Devyn Cairns
2024-03-21 04:27:21 -07:00
committed by GitHub
parent 8237d15683
commit efe25e3f58
42 changed files with 453 additions and 307 deletions

View File

@ -1,5 +1,4 @@
use nu_plugin::LabeledError;
use nu_protocol::{ast::CellPath, Span, Value};
use nu_protocol::{ast::CellPath, LabeledError, Span, Value};
use semver::{BuildMetadata, Prerelease, Version};
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
@ -102,12 +101,7 @@ impl Inc {
let cell_value = self.inc_value(head, &cell_value)?;
let mut value = value.clone();
value
.update_data_at_cell_path(&cell_path.members, cell_value)
.map_err(|x| {
let error: LabeledError = x.into();
error
})?;
value.update_data_at_cell_path(&cell_path.members, cell_value)?;
Ok(value)
} else {
self.inc_value(head, value)
@ -119,17 +113,14 @@ impl Inc {
Value::Int { val, .. } => Ok(Value::int(val + 1, head)),
Value::String { val, .. } => Ok(self.apply(val, head)),
x => {
let msg = x.coerce_string().map_err(|e| LabeledError {
label: "Unable to extract string".into(),
msg: format!("value cannot be converted to string {x:?} - {e}"),
span: Some(head),
let msg = x.coerce_string().map_err(|e| {
LabeledError::new("Unable to extract string").with_label(
format!("value cannot be converted to string {x:?} - {e}"),
head,
)
})?;
Err(LabeledError {
label: "Incorrect value".into(),
msg,
span: Some(head),
})
Err(LabeledError::new("Incorrect value").with_label(msg, head))
}
}
}

View File

@ -1,9 +1,7 @@
use crate::inc::SemVerAction;
use crate::Inc;
use nu_plugin::{
EngineInterface, EvaluatedCall, LabeledError, Plugin, PluginCommand, SimplePluginCommand,
};
use nu_protocol::{ast::CellPath, PluginSignature, SyntaxShape, Value};
use nu_plugin::{EngineInterface, EvaluatedCall, Plugin, PluginCommand, SimplePluginCommand};
use nu_protocol::{ast::CellPath, LabeledError, PluginSignature, SyntaxShape, Value};
pub struct IncPlugin;