add unspanned flag to error make, add tests (#6017)

* add `unspanned` flag to error make, add tests

* fmt
This commit is contained in:
pwygab 2022-07-12 19:03:50 +08:00 committed by GitHub
parent a5470b2362
commit a54f9719e5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 57 additions and 12 deletions

View file

@ -16,6 +16,11 @@ impl Command for ErrorMake {
fn signature(&self) -> Signature {
Signature::build("error make")
.required("error_struct", SyntaxShape::Record, "the error to create")
.switch(
"unspanned",
"remove the origin label from the error",
Some('u'),
)
.category(Category::Core)
}
@ -36,16 +41,29 @@ impl Command for ErrorMake {
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
let span = call.head;
let arg: Value = call.req(engine_state, stack, 0)?;
let unspanned = call.has_flag("unspanned");
Err(make_error(&arg, span).unwrap_or_else(|| {
ShellError::GenericError(
"Creating error value not supported.".into(),
"unsupported error format".into(),
Some(span),
None,
Vec::new(),
)
}))
if unspanned {
Err(make_error(&arg, None).unwrap_or_else(|| {
ShellError::GenericError(
"Creating error value not supported.".into(),
"unsupported error format".into(),
Some(span),
None,
Vec::new(),
)
}))
} else {
Err(make_error(&arg, Some(span)).unwrap_or_else(|| {
ShellError::GenericError(
"Creating error value not supported.".into(),
"unsupported error format".into(),
Some(span),
None,
Vec::new(),
)
}))
}
}
fn examples(&self) -> Vec<Example> {
@ -69,7 +87,7 @@ impl Command for ErrorMake {
}
}
fn make_error(value: &Value, throw_span: Span) -> Option<ShellError> {
fn make_error(value: &Value, throw_span: Option<Span>) -> Option<ShellError> {
if let Value::Record { .. } = &value {
let msg = value.get_data_by_key("msg");
let label = value.get_data_by_key("label");
@ -106,7 +124,7 @@ fn make_error(value: &Value, throw_span: Span) -> Option<ShellError> {
) => Some(ShellError::GenericError(
message,
label_text,
Some(throw_span),
throw_span,
None,
Vec::new(),
)),
@ -116,7 +134,7 @@ fn make_error(value: &Value, throw_span: Span) -> Option<ShellError> {
(Some(Value::String { val: message, .. }), None) => Some(ShellError::GenericError(
message,
"originates from here".to_string(),
Some(throw_span),
throw_span,
None,
Vec::new(),
)),

View file

@ -0,0 +1,26 @@
use nu_test_support::{nu, pipeline};
#[test]
fn error_label_works() {
let actual = nu!(
cwd: ".", pipeline(
r#"
error make {msg:foo label:{text:unseen}}
"#
));
assert!(actual.err.contains("unseen"));
assert!(actual.err.contains("╰──"));
}
#[test]
fn no_span_if_unspanned() {
let actual = nu!(
cwd: ".", pipeline(
r#"
error make -u {msg:foo label:{text:unseen}}
"#
));
assert!(!actual.err.contains("unseen"));
}

View file

@ -15,6 +15,7 @@ mod each;
mod echo;
mod empty;
mod enter;
mod error_make;
mod every;
mod find;
mod first;