Refactor the CLI code a bit (#12782)

# Description
Refactors the code in `nu-cli`, `main.rs`, `run.rs`, and few others.
Namely, I added `EngineState::generate_nu_constant` function to
eliminate some duplicate code. Otherwise, I changed a bunch of areas to
return errors instead of calling `std::process::exit`.

# User-Facing Changes
Should be none.
This commit is contained in:
Ian Manske
2024-05-09 23:29:27 +00:00
committed by GitHub
parent 1b2e680059
commit 72d3860d05
19 changed files with 146 additions and 305 deletions

View File

@ -67,7 +67,6 @@ pub(crate) fn parse_commandline_args(
let output = parse(&mut working_set, None, commandline_args.as_bytes(), false);
if let Some(err) = working_set.parse_errors.first() {
report_error(&working_set, err);
std::process::exit(1);
}

View File

@ -5,7 +5,7 @@ use nu_cli::{eval_config_contents, eval_source};
use nu_path::canonicalize_with;
use nu_protocol::{
engine::{EngineState, Stack, StateWorkingSet},
report_error, Config, ParseError, PipelineData, Spanned,
report_error, report_error_new, Config, ParseError, PipelineData, Spanned,
};
use nu_utils::{get_default_config, get_default_env};
use std::{
@ -152,13 +152,11 @@ pub(crate) fn read_default_env_file(engine_state: &mut EngineState, stack: &mut
match engine_state.cwd(Some(stack)) {
Ok(cwd) => {
if let Err(e) = engine_state.merge_env(stack, cwd) {
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &e);
report_error_new(engine_state, &e);
}
}
Err(e) => {
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &e);
report_error_new(engine_state, &e);
}
}
}
@ -193,13 +191,11 @@ fn eval_default_config(
match engine_state.cwd(Some(stack)) {
Ok(cwd) => {
if let Err(e) = engine_state.merge_env(stack, cwd) {
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &e);
report_error_new(engine_state, &e);
}
}
Err(e) => {
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &e);
report_error_new(engine_state, &e);
}
}
}

View File

@ -3,8 +3,7 @@ use nu_cli::NuCompleter;
use nu_parser::{flatten_block, parse, FlatShape};
use nu_protocol::{
engine::{EngineState, Stack, StateWorkingSet},
eval_const::create_nu_constant,
report_error, DeclId, ShellError, Span, Value, VarId, NU_VARIABLE_ID,
report_error_new, DeclId, ShellError, Span, Value, VarId,
};
use reedline::Completer;
use serde_json::{json, Value as JsonValue};
@ -56,9 +55,8 @@ fn read_in_file<'a>(
let file = std::fs::read(file_path)
.into_diagnostic()
.unwrap_or_else(|e| {
let working_set = StateWorkingSet::new(engine_state);
report_error(
&working_set,
report_error_new(
engine_state,
&ShellError::FileNotFoundCustom {
msg: format!("Could not read file '{}': {:?}", file_path, e.to_string()),
span: Span::unknown(),
@ -77,16 +75,7 @@ fn read_in_file<'a>(
pub fn check(engine_state: &mut EngineState, file_path: &str, max_errors: &Value) {
let cwd = std::env::current_dir().expect("Could not get current working directory.");
engine_state.add_env_var("PWD".into(), Value::test_string(cwd.to_string_lossy()));
let working_set = StateWorkingSet::new(engine_state);
let nu_const = match create_nu_constant(engine_state, Span::unknown()) {
Ok(nu_const) => nu_const,
Err(err) => {
report_error(&working_set, &err);
std::process::exit(1);
}
};
engine_state.set_variable_const_val(NU_VARIABLE_ID, nu_const);
engine_state.generate_nu_constant();
let mut working_set = StateWorkingSet::new(engine_state);
let file = std::fs::read(file_path);

View File

@ -27,8 +27,8 @@ use nu_cmd_base::util::get_init_cwd;
use nu_lsp::LanguageServer;
use nu_path::canonicalize_with;
use nu_protocol::{
engine::EngineState, eval_const::create_nu_constant, report_error_new, util::BufferedReader,
PipelineData, RawStream, ShellError, Span, Value, NU_VARIABLE_ID,
engine::EngineState, report_error_new, util::BufferedReader, PipelineData, RawStream,
ShellError, Span, Value,
};
use nu_std::load_standard_library;
use nu_utils::utils::perf;
@ -378,8 +378,7 @@ fn main() -> Result<()> {
start_time = std::time::Instant::now();
// Set up the $nu constant before evaluating config files (need to have $nu available in them)
let nu_const = create_nu_constant(&engine_state, input.span().unwrap_or_else(Span::unknown))?;
engine_state.set_variable_const_val(NU_VARIABLE_ID, nu_const);
engine_state.generate_nu_constant();
perf(
"create_nu_constant",
start_time,
@ -462,7 +461,8 @@ fn main() -> Result<()> {
&commands,
input,
entire_start_time,
)
);
Ok(())
} else if !script_name.is_empty() {
run_file(
&mut engine_state,
@ -471,7 +471,8 @@ fn main() -> Result<()> {
script_name,
args_to_script,
input,
)
);
Ok(())
} else {
run_repl(&mut engine_state, parsed_nu_cli_args, entire_start_time)
}

View File

@ -8,19 +8,22 @@ use log::trace;
#[cfg(feature = "plugin")]
use nu_cli::read_plugin_file;
use nu_cli::{evaluate_commands, evaluate_file, evaluate_repl};
use nu_protocol::{eval_const::create_nu_constant, PipelineData, Span, NU_VARIABLE_ID};
use nu_protocol::{
engine::{EngineState, Stack},
report_error_new, PipelineData, Spanned,
};
use nu_utils::utils::perf;
pub(crate) fn run_commands(
engine_state: &mut nu_protocol::engine::EngineState,
engine_state: &mut EngineState,
parsed_nu_cli_args: command::NushellCliArgs,
use_color: bool,
commands: &nu_protocol::Spanned<String>,
commands: &Spanned<String>,
input: PipelineData,
entire_start_time: std::time::Instant,
) -> Result<(), miette::ErrReport> {
) {
trace!("run_commands");
let mut stack = nu_protocol::engine::Stack::new();
let mut stack = Stack::new();
let start_time = std::time::Instant::now();
// if the --no-config-file(-n) option is NOT passed, load the plugin file,
@ -103,18 +106,20 @@ pub(crate) fn run_commands(
engine_state.set_startup_time(entire_start_time.elapsed().as_nanos() as i64);
// Regenerate the $nu constant to contain the startup time and any other potential updates
let nu_const = create_nu_constant(engine_state, commands.span)?;
engine_state.set_variable_const_val(NU_VARIABLE_ID, nu_const);
engine_state.generate_nu_constant();
let start_time = std::time::Instant::now();
let ret_val = evaluate_commands(
if let Err(err) = evaluate_commands(
commands,
engine_state,
&mut stack,
input,
parsed_nu_cli_args.table_mode,
parsed_nu_cli_args.no_newline.is_some(),
);
) {
report_error_new(engine_state, &err);
std::process::exit(1);
}
perf(
"evaluate_commands",
start_time,
@ -123,24 +128,18 @@ pub(crate) fn run_commands(
column!(),
use_color,
);
match ret_val {
Ok(Some(exit_code)) => std::process::exit(exit_code as i32),
Ok(None) => Ok(()),
Err(e) => Err(e),
}
}
pub(crate) fn run_file(
engine_state: &mut nu_protocol::engine::EngineState,
engine_state: &mut EngineState,
parsed_nu_cli_args: command::NushellCliArgs,
use_color: bool,
script_name: String,
args_to_script: Vec<String>,
input: PipelineData,
) -> Result<(), miette::ErrReport> {
) {
trace!("run_file");
let mut stack = nu_protocol::engine::Stack::new();
let mut stack = Stack::new();
// if the --no-config-file(-n) option is NOT passed, load the plugin file,
// load the default env file or custom (depending on parsed_nu_cli_args.env_file),
@ -201,17 +200,19 @@ pub(crate) fn run_file(
}
// Regenerate the $nu constant to contain the startup time and any other potential updates
let nu_const = create_nu_constant(engine_state, input.span().unwrap_or_else(Span::unknown))?;
engine_state.set_variable_const_val(NU_VARIABLE_ID, nu_const);
engine_state.generate_nu_constant();
let start_time = std::time::Instant::now();
let ret_val = evaluate_file(
if let Err(err) = evaluate_file(
script_name,
&args_to_script,
engine_state,
&mut stack,
input,
);
) {
report_error_new(engine_state, &err);
std::process::exit(1);
}
perf(
"evaluate_file",
start_time,
@ -239,17 +240,15 @@ pub(crate) fn run_file(
column!(),
use_color,
);
ret_val
}
pub(crate) fn run_repl(
engine_state: &mut nu_protocol::engine::EngineState,
engine_state: &mut EngineState,
parsed_nu_cli_args: command::NushellCliArgs,
entire_start_time: std::time::Instant,
) -> Result<(), miette::ErrReport> {
trace!("run_repl");
let mut stack = nu_protocol::engine::Stack::new();
let mut stack = Stack::new();
let start_time = std::time::Instant::now();
if parsed_nu_cli_args.no_config_file.is_none() {