From 1ecbb3e09fb1dda7b3b143c23611d0f48e2ff0a2 Mon Sep 17 00:00:00 2001 From: Ian Manske Date: Fri, 26 Apr 2024 16:35:08 +0000 Subject: [PATCH] Make exit code available in `catch` block (#12648) # Description Bandaid fix for #12643, where it is not possible to get the exit code of a failed external command while also having the external command inherit nushell's stdout and stderr. This changes `try` so that the exit code of external command is available in the `catch` block via the usual `$env.LAST_EXIT_CODE`. # Tests + Formatting Added one test. # After Submitting Rework I/O redirection and possibly exit codes. --- crates/nu-cmd-lang/src/core_commands/try_.rs | 5 ++--- crates/nu-command/tests/commands/try_.rs | 6 ++++++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/nu-cmd-lang/src/core_commands/try_.rs b/crates/nu-cmd-lang/src/core_commands/try_.rs index 2bf3ee6b8d..bc96f3c28a 100644 --- a/crates/nu-cmd-lang/src/core_commands/try_.rs +++ b/crates/nu-cmd-lang/src/core_commands/try_.rs @@ -64,9 +64,8 @@ impl Command for Try { Ok(pipeline) => { let (pipeline, external_failed) = pipeline.check_external_failed(); if external_failed { - // Because external command errors aren't "real" errors, - // (unless do -c is in effect) - // they can't be passed in as Nushell values. + let exit_code = pipeline.drain_with_exit_code()?; + stack.add_env_var("LAST_EXIT_CODE".into(), Value::int(exit_code, call.head)); let err_value = Value::nothing(call.head); handle_catch(err_value, catch_block, engine_state, stack, eval_block) } else { diff --git a/crates/nu-command/tests/commands/try_.rs b/crates/nu-command/tests/commands/try_.rs index 6dc35d6840..c4fc9269d0 100644 --- a/crates/nu-command/tests/commands/try_.rs +++ b/crates/nu-command/tests/commands/try_.rs @@ -93,3 +93,9 @@ fn can_catch_infinite_recursion() { "#); assert_eq!(actual.out, "Caught infinite recursion"); } + +#[test] +fn exit_code_available_in_catch() { + let actual = nu!("try { nu -c 'exit 42' } catch { $env.LAST_EXIT_CODE }"); + assert_eq!(actual.out, "42"); +}