From 6536fa5ff7d9ea176d2082c21b29c3e6f1a3b3da Mon Sep 17 00:00:00 2001 From: Texas Toland Date: Tue, 9 Apr 2024 09:06:41 -0500 Subject: [PATCH] Ensure `currently_parsed_cwd` is set for config files (#12338) # Description Fixes #7849, #11465 based on @kubouch's suggestion in https://github.com/nushell/nushell/issues/11465#issuecomment-1883847806. # User-Facing Changes Can source files relative to `env.nu` or `config.nu` like in #6150. # Tests + Formatting Adds test that previously failed. # After Submitting --- crates/nu-cli/src/config_files.rs | 7 +++++++ crates/nu-protocol/src/engine/engine_state.rs | 2 +- tests/parsing/mod.rs | 9 +++++++++ 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/nu-cli/src/config_files.rs b/crates/nu-cli/src/config_files.rs index e965b25f37..0d78c0ab69 100644 --- a/crates/nu-cli/src/config_files.rs +++ b/crates/nu-cli/src/config_files.rs @@ -91,6 +91,10 @@ pub fn eval_config_contents( let config_filename = config_path.to_string_lossy(); if let Ok(contents) = std::fs::read(&config_path) { + // Change currently parsed directory + let prev_currently_parsed_cwd = engine_state.currently_parsed_cwd.clone(); + engine_state.start_in_file(Some(&config_filename)); + eval_source( engine_state, stack, @@ -100,6 +104,9 @@ pub fn eval_config_contents( false, ); + // Restore the currently parsed directory back + engine_state.currently_parsed_cwd = prev_currently_parsed_cwd; + // Merge the environment in case env vars changed in the config match nu_engine::env::current_dir(engine_state, stack) { Ok(cwd) => { diff --git a/crates/nu-protocol/src/engine/engine_state.rs b/crates/nu-protocol/src/engine/engine_state.rs index 7117abf88b..82af39d093 100644 --- a/crates/nu-protocol/src/engine/engine_state.rs +++ b/crates/nu-protocol/src/engine/engine_state.rs @@ -99,7 +99,7 @@ pub struct EngineState { pub history_enabled: bool, pub history_session_id: i64, // If Nushell was started, e.g., with `nu spam.nu`, the file's parent is stored here - pub(super) currently_parsed_cwd: Option, + pub currently_parsed_cwd: Option, pub regex_cache: Arc>>, pub is_interactive: bool, pub is_login: bool, diff --git a/tests/parsing/mod.rs b/tests/parsing/mod.rs index be9f3aa4f6..e7c21d1ee6 100644 --- a/tests/parsing/mod.rs +++ b/tests/parsing/mod.rs @@ -13,6 +13,15 @@ fn source_file_relative_to_file() { assert_eq!(actual.out, "5"); } +#[test] +fn source_file_relative_to_config() { + let actual = nu!(" + nu --config tests/parsing/samples/source_file_relative.nu --commands '' + "); + + assert_eq!(actual.out, "5"); +} + #[test] fn source_const_file() { let actual = nu!(cwd: "tests/parsing/samples",