Add try/catch functionality (#7221)

# Description

This adds `try` (with an optional `catch` piece). Much like other
languages, `try` will try to run a block. If the block fails to run
successfully, the optional `catch` block will run if it is available.

# User-Facing Changes

This adds the `try` command.

# 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:
JT 2022-11-24 17:52:11 +13:00 committed by GitHub
parent 8cca447e8c
commit 04612809ab
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 129 additions and 0 deletions

View file

@ -26,6 +26,7 @@ mod metadata;
mod module;
mod mut_;
pub(crate) mod overlay;
mod try_;
mod use_;
mod version;
mod while_;
@ -58,6 +59,7 @@ pub use metadata::Metadata;
pub use module::Module;
pub use mut_::Mut;
pub use overlay::*;
pub use try_::Try;
pub use use_::Use;
pub use version::Version;
pub use while_::While;

View file

@ -0,0 +1,99 @@
use nu_engine::{eval_block, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{Block, Command, EngineState, Stack};
use nu_protocol::{Category, Example, PipelineData, Signature, SyntaxShape, Type, Value};
#[derive(Clone)]
pub struct Try;
impl Command for Try {
fn name(&self) -> &str {
"try"
}
fn usage(&self) -> &str {
"Try to run a block, if it fails optionally run a catch block"
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("try")
.input_output_types(vec![(Type::Any, Type::Any)])
.required("try_block", SyntaxShape::Block, "block to run")
.optional(
"else_expression",
SyntaxShape::Keyword(b"catch".to_vec(), Box::new(SyntaxShape::Block)),
"block to run if try block fails",
)
.category(Category::Core)
}
fn extra_usage(&self) -> &str {
r#"This command is a parser keyword. For details, check:
https://www.nushell.sh/book/thinking_in_nu.html"#
}
fn is_parser_keyword(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
let try_block: Block = call.req(engine_state, stack, 0)?;
let catch_block: Option<Block> = call.opt(engine_state, stack, 1)?;
let try_block = engine_state.get_block(try_block.block_id);
let result = eval_block(engine_state, stack, try_block, input, false, false);
match result {
Err(_) | Ok(PipelineData::Value(Value::Error { .. }, ..)) => {
if let Some(catch_block) = catch_block {
let catch_block = engine_state.get_block(catch_block.block_id);
eval_block(
engine_state,
stack,
catch_block,
PipelineData::new(call.head),
false,
false,
)
} else {
Ok(PipelineData::new(call.head))
}
}
Ok(output) => Ok(output),
}
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Try to run a missing command",
example: "try { asdfasdf }",
result: None,
},
Example {
description: "Try to run a missing command",
example: "try { asdfasdf } catch { echo 'missing' } ",
result: Some(Value::test_string("missing")),
},
]
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(Try {})
}
}

View file

@ -60,6 +60,7 @@ pub fn create_default_context() -> EngineState {
Metadata,
Module,
Mut,
Try,
Use,
Version,
While,

View file

@ -82,6 +82,7 @@ mod table;
mod take;
mod touch;
mod transpose;
mod try_;
mod uniq;
mod update;
mod upsert;

View file

@ -0,0 +1,26 @@
use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[test]
fn try_succeed() {
Playground::setup("try_succeed_test", |dirs, _sandbox| {
let output = nu!(
cwd: dirs.test(),
"try { 345 } catch { echo 'hello' }"
);
assert!(output.out.contains("345"));
})
}
#[test]
fn try_catch() {
Playground::setup("try_catch_test", |dirs, _sandbox| {
let output = nu!(
cwd: dirs.test(),
"try { foobarbaz } catch { echo 'hello' }"
);
assert!(output.out.contains("hello"));
})
}