From 04612809ab5960ca3abdbab3977efebb0dd1f1eb Mon Sep 17 00:00:00 2001 From: JT <547158+jntrnr@users.noreply.github.com> Date: Thu, 24 Nov 2022 17:52:11 +1300 Subject: [PATCH] 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. --- crates/nu-command/src/core_commands/mod.rs | 2 + crates/nu-command/src/core_commands/try_.rs | 99 +++++++++++++++++++++ crates/nu-command/src/default_context.rs | 1 + crates/nu-command/tests/commands/mod.rs | 1 + crates/nu-command/tests/commands/try_.rs | 26 ++++++ 5 files changed, 129 insertions(+) create mode 100644 crates/nu-command/src/core_commands/try_.rs create mode 100644 crates/nu-command/tests/commands/try_.rs diff --git a/crates/nu-command/src/core_commands/mod.rs b/crates/nu-command/src/core_commands/mod.rs index b11bc56c8d..e0b30c41ac 100644 --- a/crates/nu-command/src/core_commands/mod.rs +++ b/crates/nu-command/src/core_commands/mod.rs @@ -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; diff --git a/crates/nu-command/src/core_commands/try_.rs b/crates/nu-command/src/core_commands/try_.rs new file mode 100644 index 0000000000..49aade1c31 --- /dev/null +++ b/crates/nu-command/src/core_commands/try_.rs @@ -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 { + let try_block: Block = call.req(engine_state, stack, 0)?; + let catch_block: Option = 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 { + 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 {}) + } +} diff --git a/crates/nu-command/src/default_context.rs b/crates/nu-command/src/default_context.rs index 08f84fe9be..73358b5672 100644 --- a/crates/nu-command/src/default_context.rs +++ b/crates/nu-command/src/default_context.rs @@ -60,6 +60,7 @@ pub fn create_default_context() -> EngineState { Metadata, Module, Mut, + Try, Use, Version, While, diff --git a/crates/nu-command/tests/commands/mod.rs b/crates/nu-command/tests/commands/mod.rs index 21769f584e..547cd99f62 100644 --- a/crates/nu-command/tests/commands/mod.rs +++ b/crates/nu-command/tests/commands/mod.rs @@ -82,6 +82,7 @@ mod table; mod take; mod touch; mod transpose; +mod try_; mod uniq; mod update; mod upsert; diff --git a/crates/nu-command/tests/commands/try_.rs b/crates/nu-command/tests/commands/try_.rs new file mode 100644 index 0000000000..03da540082 --- /dev/null +++ b/crates/nu-command/tests/commands/try_.rs @@ -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")); + }) +}