Change parser cwd when running a file (#7134)

* Change parser cwd when running a file

* Add test

* Add missing file
This commit is contained in:
Jakub Žádník 2022-11-15 00:05:27 +01:00 committed by GitHub
parent 336df6c65e
commit 81b12d02ec
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 25 additions and 1 deletions

View file

@ -29,6 +29,8 @@ pub fn evaluate_file(
let file = std::fs::read(&path).into_diagnostic()?; let file = std::fs::read(&path).into_diagnostic()?;
engine_state.start_in_file(Some(&path));
let mut working_set = StateWorkingSet::new(engine_state); let mut working_set = StateWorkingSet::new(engine_state);
trace!("parsing file: {}", path); trace!("parsing file: {}", path);

View file

@ -92,6 +92,8 @@ pub struct EngineState {
sig_quit: Option<Arc<AtomicBool>>, sig_quit: Option<Arc<AtomicBool>>,
config_path: HashMap<String, PathBuf>, config_path: HashMap<String, PathBuf>,
pub history_session_id: i64, pub history_session_id: i64,
// If Nushell was started, e.g., with `nu spam.nu`, the file's parent is stored here
pub currently_parsed_cwd: Option<PathBuf>,
} }
pub const NU_VARIABLE_ID: usize = 0; pub const NU_VARIABLE_ID: usize = 0;
@ -134,6 +136,7 @@ impl EngineState {
sig_quit: None, sig_quit: None,
config_path: HashMap::new(), config_path: HashMap::new(),
history_session_id: 0, history_session_id: 0,
currently_parsed_cwd: None,
} }
} }
@ -251,6 +254,15 @@ impl EngineState {
Ok(()) Ok(())
} }
/// Mark a starting point if it is a script (e.g., nu spam.nu)
pub fn start_in_file(&mut self, file_path: Option<&str>) {
self.currently_parsed_cwd = if let Some(path) = file_path {
Path::new(path).parent().map(PathBuf::from)
} else {
None
};
}
pub fn has_overlay(&self, name: &[u8]) -> bool { pub fn has_overlay(&self, name: &[u8]) -> bool {
self.scope self.scope
.overlays .overlays
@ -987,7 +999,7 @@ impl<'a> StateWorkingSet<'a> {
permanent_state, permanent_state,
external_commands: vec![], external_commands: vec![],
type_scope: TypeScope::default(), type_scope: TypeScope::default(),
currently_parsed_cwd: None, currently_parsed_cwd: permanent_state.currently_parsed_cwd.clone(),
parsed_module_files: vec![], parsed_module_files: vec![],
} }
} }

View file

@ -2,6 +2,15 @@ use nu_test_support::fs::Stub::FileWithContentToBeTrimmed;
use nu_test_support::playground::Playground; use nu_test_support::playground::Playground;
use nu_test_support::{nu, pipeline}; use nu_test_support::{nu, pipeline};
#[test]
fn source_file_relative_to_file() {
let actual = nu!(cwd: "tests/parsing/samples", r#"
nu source_file_relative.nu
"#);
assert_eq!(actual.out, "5");
}
#[test] #[test]
fn run_nu_script_single_line() { fn run_nu_script_single_line() {
let actual = nu!(cwd: "tests/parsing/samples", r#" let actual = nu!(cwd: "tests/parsing/samples", r#"

View file

@ -0,0 +1 @@
source single_line.nu