Skip to content

Commit

Permalink
Fix file lookup in parser keywords; Refactor nu_repl (#6185)
Browse files Browse the repository at this point in the history
* Fix file lookup in parser keywords

* Make nu_repl a testbin; Fix wrong cwd test error
  • Loading branch information
kubouch committed Jul 29, 2022
1 parent 7a820b1 commit d6f4189
Show file tree
Hide file tree
Showing 10 changed files with 353 additions and 219 deletions.
32 changes: 18 additions & 14 deletions crates/nu-parser/src/parse_keywords.rs
Expand Up @@ -2834,25 +2834,29 @@ pub fn parse_register(

/// This helper function is used to find files during parsing
///
/// Checks whether the file is:
/// 1. relative to the directory of the file currently being parsed
/// 2. relative to the current working directory
/// 3. within one of the NU_LIB_DIRS entries
/// First, the actual current working directory is selected as
/// a) the directory of a file currently being parsed
/// b) current working directory (PWD)
///
/// Always returns absolute path
/// Then, if the file is not found in the actual cwd, NU_LIB_DIRS is checked.
/// If there is a relative path in NU_LIB_DIRS, it is assumed to be relative to the actual cwd
/// determined in the first step.
///
/// Always returns an absolute path
fn find_in_dirs(
filename: &str,
working_set: &StateWorkingSet,
cwd: &str,
dirs_env: &str,
) -> Option<PathBuf> {
if let Some(currently_parsed_cwd) = &working_set.currently_parsed_cwd {
if let Ok(p) = canonicalize_with(filename, currently_parsed_cwd) {
Some(p)
} else {
None
}
} else if let Ok(p) = canonicalize_with(filename, cwd) {
// Choose whether to use file-relative or PWD-relative path
let actual_cwd = if let Some(currently_parsed_cwd) = &working_set.currently_parsed_cwd {
currently_parsed_cwd.as_path()
} else {
Path::new(cwd)
};

if let Ok(p) = canonicalize_with(filename, actual_cwd) {
Some(p)
} else {
let path = Path::new(filename);
Expand All @@ -2862,8 +2866,8 @@ fn find_in_dirs(
if let Ok(dirs) = lib_dirs.as_list() {
for lib_dir in dirs {
if let Ok(dir) = lib_dir.as_path() {
if let Ok(dir_abs) = canonicalize_with(&dir, cwd) {
// make sure the dir is absolute path
// make sure the dir is absolute path
if let Ok(dir_abs) = canonicalize_with(&dir, actual_cwd) {
if let Ok(path) = canonicalize_with(filename, dir_abs) {
return Some(path);
}
Expand Down
6 changes: 3 additions & 3 deletions crates/nu-protocol/src/config.rs
Expand Up @@ -199,7 +199,7 @@ impl Value {
if let Ok(map) = create_map(value, &config) {
config.color_config = map;
} else {
eprintln!("$config.color_config is not a record")
eprintln!("$env.config.color_config is not a record")
}
}
"use_grid_icons" => {
Expand Down Expand Up @@ -403,7 +403,7 @@ impl Value {
}
}
} else {
eprintln!("$config is not a record");
eprintln!("$env.config is not a record");
}

Ok(config)
Expand All @@ -412,7 +412,7 @@ impl Value {

fn try_parse_trim_strategy(value: &Value, config: &Config) -> Result<TrimStrategy, ShellError> {
let map = create_map(value, config).map_err(|e| {
eprintln!("$config.table_trim is not a record");
eprintln!("$env.config.table_trim is not a record");
e
})?;

Expand Down
19 changes: 19 additions & 0 deletions crates/nu-test-support/src/lib.rs
Expand Up @@ -35,6 +35,25 @@ pub fn pipeline(commands: &str) -> String {
.to_string()
}

pub fn nu_repl_code(source_lines: &[&str]) -> String {
let mut out = String::from("nu --testbin=nu_repl [ ");

for line in source_lines.iter() {
// convert each "line" to really be a single line to prevent nu! macro joining the newlines
// with ';'
let line = pipeline(line);

out.push('`');
out.push_str(&line);
out.push('`');
out.push(' ');
}

out.push(']');

out
}

pub fn shell_os_paths() -> Vec<std::path::PathBuf> {
let mut original_paths = vec![];

Expand Down
1 change: 1 addition & 0 deletions src/main.rs
Expand Up @@ -177,6 +177,7 @@ fn main() -> Result<()> {
"nonu" => test_bins::nonu(),
"chop" => test_bins::chop(),
"repeater" => test_bins::repeater(),
"nu_repl" => test_bins::nu_repl(),
_ => std::process::exit(1),
}
std::process::exit(0)
Expand Down
128 changes: 128 additions & 0 deletions src/test_bins.rs
@@ -1,5 +1,13 @@
use std::io::{self, BufRead, Write};

use nu_cli::{eval_env_change_hook, eval_hook};
use nu_command::create_default_context;
use nu_engine::eval_block;
use nu_parser::parse;
use nu_protocol::engine::{EngineState, Stack, StateWorkingSet};
use nu_protocol::{CliError, PipelineData, Span, Value};
// use nu_test_support::fs::in_directory;

/// Echo's value of env keys from args
/// Example: nu --testbin env_echo FOO BAR
/// If it it's not present echo's nothing
Expand Down Expand Up @@ -112,6 +120,126 @@ pub fn chop() {
std::process::exit(0);
}

fn outcome_err(
engine_state: &EngineState,
error: &(dyn miette::Diagnostic + Send + Sync + 'static),
) -> ! {
let working_set = StateWorkingSet::new(engine_state);

eprintln!("Error: {:?}", CliError(error, &working_set));

std::process::exit(1);
}

fn outcome_ok(msg: String) -> ! {
println!("{}", msg);

std::process::exit(0);
}

pub fn nu_repl() {
//cwd: &str, source_lines: &[&str]) {
let cwd = std::env::current_dir().expect("Could not get current working directory.");
let source_lines = args();

let mut engine_state = create_default_context();
let mut stack = Stack::new();

stack.add_env_var(
"PWD".to_string(),
Value::String {
val: cwd.to_string_lossy().to_string(),
span: Span::test_data(),
},
);

let mut last_output = String::new();

for (i, line) in source_lines.iter().enumerate() {
let cwd = match nu_engine::env::current_dir(&engine_state, &stack) {
Ok(d) => d,
Err(err) => {
outcome_err(&engine_state, &err);
}
};

// Before doing anything, merge the environment from the previous REPL iteration into the
// permanent state.
if let Err(err) = engine_state.merge_env(&mut stack, &cwd) {
outcome_err(&engine_state, &err);
}

// Check for pre_prompt hook
let config = engine_state.get_config();
if let Some(hook) = config.hooks.pre_prompt.clone() {
if let Err(err) = eval_hook(&mut engine_state, &mut stack, vec![], &hook) {
outcome_err(&engine_state, &err);
}
}

// Check for env change hook
let config = engine_state.get_config();
if let Err(err) = eval_env_change_hook(
config.hooks.env_change.clone(),
&mut engine_state,
&mut stack,
) {
outcome_err(&engine_state, &err);
}

// Check for pre_execution hook
let config = engine_state.get_config();
if let Some(hook) = config.hooks.pre_execution.clone() {
if let Err(err) = eval_hook(&mut engine_state, &mut stack, vec![], &hook) {
outcome_err(&engine_state, &err);
}
}

// Eval the REPL line
let (block, delta) = {
let mut working_set = StateWorkingSet::new(&engine_state);
let (block, err) = parse(
&mut working_set,
Some(&format!("line{}", i)),
line.as_bytes(),
false,
&[],
);

if let Some(err) = err {
outcome_err(&engine_state, &err);
}
(block, working_set.render())
};

if let Err(err) = engine_state.merge_delta(delta) {
outcome_err(&engine_state, &err);
}

let input = PipelineData::new(Span::test_data());
let config = engine_state.get_config();

match eval_block(&engine_state, &mut stack, &block, input, false, false) {
Ok(pipeline_data) => match pipeline_data.collect_string("", config) {
Ok(s) => last_output = s,
Err(err) => outcome_err(&engine_state, &err),
},
Err(err) => outcome_err(&engine_state, &err),
}

if let Some(cwd) = stack.get_env_var(&engine_state, "PWD") {
let path = match cwd.as_string() {
Ok(p) => p,
Err(err) => outcome_err(&engine_state, &err),
};
let _ = std::env::set_current_dir(path);
engine_state.add_env_var("PWD".into(), cwd);
}
}

outcome_ok(last_output)
}

fn did_chop_arguments() -> bool {
let args: Vec<String> = args();

Expand Down

0 comments on commit d6f4189

Please sign in to comment.