Simplify down to one type of context (#3379)

* Simplify down to one type of context

* More simplification
This commit is contained in:
JT 2021-05-03 11:45:55 +12:00 committed by GitHub
parent 4fc05cac56
commit fc59291191
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
57 changed files with 543 additions and 678 deletions

View File

@ -513,14 +513,14 @@ fn current_branch() -> String {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use nu_engine::basic_evaluation_context; use nu_engine::EvaluationContext;
#[quickcheck] #[quickcheck]
fn quickcheck_parse(data: String) -> bool { fn quickcheck_parse(data: String) -> bool {
let (tokens, err) = nu_parser::lex(&data, 0); let (tokens, err) = nu_parser::lex(&data, 0);
let (lite_block, err2) = nu_parser::parse_block(tokens); let (lite_block, err2) = nu_parser::parse_block(tokens);
if err.is_none() && err2.is_none() { if err.is_none() && err2.is_none() {
let context = basic_evaluation_context().unwrap(); let context = EvaluationContext::basic();
let _ = nu_parser::classify_block(&lite_block, &context.scope); let _ = nu_parser::classify_block(&lite_block, &context.scope);
} }
true true

View File

@ -150,7 +150,7 @@ impl rustyline::Helper for Helper {}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use nu_engine::basic_evaluation_context; use nu_engine::EvaluationContext;
use rustyline::completion::Completer; use rustyline::completion::Completer;
use rustyline::line_buffer::LineBuffer; use rustyline::line_buffer::LineBuffer;
@ -164,7 +164,7 @@ mod tests {
buffer.insert_str(0, text); buffer.insert_str(0, text);
buffer.set_pos(text.len() - 1); buffer.set_pos(text.len() - 1);
let helper = Helper::new(basic_evaluation_context().unwrap(), None); let helper = Helper::new(EvaluationContext::basic(), None);
helper.update(&mut buffer, "cd ".len(), &replacement); helper.update(&mut buffer, "cd ".len(), &replacement);
@ -184,7 +184,7 @@ mod tests {
buffer.insert_str(0, text); buffer.insert_str(0, text);
buffer.set_pos(text.len() - 30); buffer.set_pos(text.len() - 30);
let helper = Helper::new(basic_evaluation_context().unwrap(), None); let helper = Helper::new(EvaluationContext::basic(), None);
helper.update(&mut buffer, "cd ".len(), &replacement); helper.update(&mut buffer, "cd ".len(), &replacement);

View File

@ -83,7 +83,7 @@ fn all(args: CommandArgs) -> Result<OutputStream, ShellError> {
} }
}; };
let scope = args.scope.clone(); let scope = args.scope();
let init = Ok(InputStream::one( let init = Ok(InputStream::one(
UntaggedValue::boolean(true).into_value(&tag), UntaggedValue::boolean(true).into_value(&tag),

View File

@ -83,7 +83,7 @@ fn any(args: CommandArgs) -> Result<OutputStream, ShellError> {
} }
}; };
let scope = args.scope.clone(); let scope = args.scope();
let init = Ok(InputStream::one( let init = Ok(InputStream::one(
UntaggedValue::boolean(false).into_value(&tag), UntaggedValue::boolean(false).into_value(&tag),

View File

@ -27,7 +27,7 @@ The .nu-env file has the same format as your $HOME/nu/config.toml file. By loadi
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> {
Ok(ActionStream::one(ReturnSuccess::value( Ok(ActionStream::one(ReturnSuccess::value(
UntaggedValue::string(get_full_help(&Autoenv, &args.scope)).into_value(Tag::unknown()), UntaggedValue::string(get_full_help(&Autoenv, args.scope())).into_value(Tag::unknown()),
))) )))
} }

View File

@ -43,14 +43,15 @@ impl WholeStreamCommand for Command {
} }
} }
pub fn autoview(context: CommandArgs) -> Result<OutputStream, ShellError> { pub fn autoview(args: CommandArgs) -> Result<OutputStream, ShellError> {
let configuration = context.configs.lock().global_config(); let configuration = args.configs().lock().global_config();
let tag = args.call_info.name_tag.clone();
let binary = context.scope.get_command("binaryview"); let binary = args.scope().get_command("binaryview");
let text = context.scope.get_command("textview"); let text = args.scope().get_command("textview");
let table = context.scope.get_command("table"); let table = args.scope().get_command("table");
let context = args.context;
let (mut input_stream, context) = context.split(); let mut input_stream = args.input;
if let Some(x) = input_stream.next() { if let Some(x) = input_stream.next() {
match input_stream.next() { match input_stream.next() {
@ -62,7 +63,7 @@ pub fn autoview(context: CommandArgs) -> Result<OutputStream, ShellError> {
let stream = InputStream::from_stream(xy_stream); let stream = InputStream::from_stream(xy_stream);
if let Some(table) = table { if let Some(table) = table {
let command_args = create_default_command_args(&context).with_input(stream); let command_args = create_default_command_args(&context, stream, tag);
let result = table.run(command_args)?; let result = table.run(command_args)?;
let _ = result.collect::<Vec<_>>(); let _ = result.collect::<Vec<_>>();
} }
@ -74,12 +75,13 @@ pub fn autoview(context: CommandArgs) -> Result<OutputStream, ShellError> {
tag: Tag { anchor, span }, tag: Tag { anchor, span },
} if anchor.is_some() => { } if anchor.is_some() => {
if let Some(text) = text { if let Some(text) = text {
let mut stream = VecDeque::new(); let command_args = create_default_command_args(
stream.push_back( &context,
UntaggedValue::string(s).into_value(Tag { anchor, span }), InputStream::one(
UntaggedValue::string(s).into_value(Tag { anchor, span }),
),
tag,
); );
let command_args =
create_default_command_args(&context).with_input(stream);
let result = text.run_with_actions(command_args)?; let result = text.run_with_actions(command_args)?;
let _ = result.collect::<Vec<_>>(); let _ = result.collect::<Vec<_>>();
} else { } else {
@ -158,10 +160,8 @@ pub fn autoview(context: CommandArgs) -> Result<OutputStream, ShellError> {
.. ..
} => { } => {
if let Some(binary) = binary { if let Some(binary) = binary {
let mut stream = VecDeque::new();
stream.push_back(x);
let command_args = let command_args =
create_default_command_args(&context).with_input(stream); create_default_command_args(&context, InputStream::one(x), tag);
let result = binary.run_with_actions(command_args)?; let result = binary.run_with_actions(command_args)?;
let _ = result.collect::<Vec<_>>(); let _ = result.collect::<Vec<_>>();
} else { } else {
@ -220,10 +220,8 @@ pub fn autoview(context: CommandArgs) -> Result<OutputStream, ShellError> {
println!("{}", nu_table::draw_table(&table, term_width, &color_hm)); println!("{}", nu_table::draw_table(&table, term_width, &color_hm));
} else if let Some(table) = table { } else if let Some(table) = table {
let mut stream = VecDeque::new();
stream.push_back(x);
let command_args = let command_args =
create_default_command_args(&context).with_input(stream); create_default_command_args(&context, InputStream::one(x), tag);
let result = table.run(command_args)?; let result = table.run(command_args)?;
let _ = result.collect::<Vec<_>>(); let _ = result.collect::<Vec<_>>();
} else { } else {
@ -240,10 +238,8 @@ pub fn autoview(context: CommandArgs) -> Result<OutputStream, ShellError> {
value: ref item, .. value: ref item, ..
} => { } => {
if let Some(table) = table { if let Some(table) = table {
let mut stream = VecDeque::new();
stream.push_back(x);
let command_args = let command_args =
create_default_command_args(&context).with_input(stream); create_default_command_args(&context, InputStream::one(x), tag);
let result = table.run(command_args)?; let result = table.run(command_args)?;
let _ = result.collect::<Vec<_>>(); let _ = result.collect::<Vec<_>>();
} else { } else {
@ -258,14 +254,14 @@ pub fn autoview(context: CommandArgs) -> Result<OutputStream, ShellError> {
Ok(InputStream::empty()) Ok(InputStream::empty())
} }
fn create_default_command_args(context: &RunnableContextWithoutInput) -> RawCommandArgs { fn create_default_command_args(
let span = context.name.span; context: &EvaluationContext,
RawCommandArgs { input: InputStream,
host: context.host.clone(), tag: Tag,
ctrl_c: context.ctrl_c.clone(), ) -> CommandArgs {
configs: context.configs.clone(), let span = tag.span;
current_errors: context.current_errors.clone(), CommandArgs {
shell_manager: context.shell_manager.clone(), context: context.clone(),
call_info: UnevaluatedCallInfo { call_info: UnevaluatedCallInfo {
args: hir::Call { args: hir::Call {
head: Box::new(SpannedExpression::new( head: Box::new(SpannedExpression::new(
@ -277,9 +273,9 @@ fn create_default_command_args(context: &RunnableContextWithoutInput) -> RawComm
span, span,
external_redirection: ExternalRedirection::Stdout, external_redirection: ExternalRedirection::Stdout,
}, },
name_tag: context.name.clone(), name_tag: tag,
}, },
scope: Scope::new(), input,
} }
} }

View File

@ -70,11 +70,11 @@ impl WholeStreamCommand for Benchmark {
} }
} }
fn benchmark(raw_args: CommandArgs) -> Result<ActionStream, ShellError> { fn benchmark(args: CommandArgs) -> Result<ActionStream, ShellError> {
let tag = raw_args.call_info.args.span; let tag = args.call_info.args.span;
let mut context = EvaluationContext::from_args(&raw_args); let mut context = EvaluationContext::from_args(&args);
let scope = raw_args.scope.clone(); let scope = args.scope().clone();
let (BenchmarkArgs { block, passthrough }, input) = raw_args.process()?; let (BenchmarkArgs { block, passthrough }, input) = args.process()?;
let env = scope.get_env_vars(); let env = scope.get_env_vars();
let name = generate_free_name(&env); let name = generate_free_name(&env);

View File

@ -1,7 +1,7 @@
use crate::prelude::*; use crate::prelude::*;
use chrono::{Datelike, Local, NaiveDate}; use chrono::{Datelike, Local, NaiveDate};
use indexmap::IndexMap; use indexmap::IndexMap;
use nu_engine::{EvaluatedWholeStreamCommandArgs, WholeStreamCommand}; use nu_engine::{EvaluatedCommandArgs, WholeStreamCommand};
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{Dictionary, Signature, SyntaxShape, UntaggedValue, Value}; use nu_protocol::{Dictionary, Signature, SyntaxShape, UntaggedValue, Value};
@ -165,7 +165,7 @@ fn get_current_date() -> (i32, u32, u32) {
} }
fn add_months_of_year_to_table( fn add_months_of_year_to_table(
args: &EvaluatedWholeStreamCommandArgs, args: &EvaluatedCommandArgs,
mut calendar_vec_deque: &mut VecDeque<Value>, mut calendar_vec_deque: &mut VecDeque<Value>,
tag: &Tag, tag: &Tag,
selected_year: i32, selected_year: i32,
@ -198,7 +198,7 @@ fn add_months_of_year_to_table(
} }
fn add_month_to_table( fn add_month_to_table(
args: &EvaluatedWholeStreamCommandArgs, args: &EvaluatedCommandArgs,
calendar_vec_deque: &mut VecDeque<Value>, calendar_vec_deque: &mut VecDeque<Value>,
tag: &Tag, tag: &Tag,
selected_year: i32, selected_year: i32,

View File

@ -26,7 +26,7 @@ impl WholeStreamCommand for Cd {
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> {
let name = args.call_info.name_tag.clone(); let name = args.call_info.name_tag.clone();
let shell_manager = args.shell_manager.clone(); let shell_manager = args.shell_manager();
let (args, _): (CdArgs, _) = args.process()?; let (args, _): (CdArgs, _) = args.process()?;
shell_manager.cd(args, name) shell_manager.cd(args, name)
} }

View File

@ -20,14 +20,14 @@ impl WholeStreamCommand for Chart {
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> {
if args.scope.get_command("chart bar").is_none() { if args.scope().get_command("chart bar").is_none() {
return Err(ShellError::untagged_runtime_error( return Err(ShellError::untagged_runtime_error(
"nu_plugin_chart not installed.", "nu_plugin_chart not installed.",
)); ));
} }
Ok(ActionStream::one(Ok(ReturnSuccess::Value( Ok(ActionStream::one(Ok(ReturnSuccess::Value(
UntaggedValue::string(get_full_help(&Chart, &args.scope)).into_value(Tag::unknown()), UntaggedValue::string(get_full_help(&Chart, args.scope())).into_value(Tag::unknown()),
)))) ))))
} }
} }

View File

@ -534,7 +534,7 @@ mod tests {
use super::{run_external_command, InputStream}; use super::{run_external_command, InputStream};
#[cfg(feature = "which")] #[cfg(feature = "which")]
use nu_engine::basic_evaluation_context; use nu_engine::EvaluationContext;
#[cfg(feature = "which")] #[cfg(feature = "which")]
use nu_test_support::commands::ExternalBuilder; use nu_test_support::commands::ExternalBuilder;
@ -557,8 +557,7 @@ mod tests {
let cmd = ExternalBuilder::for_name("i_dont_exist.exe").build(); let cmd = ExternalBuilder::for_name("i_dont_exist.exe").build();
let input = InputStream::empty(); let input = InputStream::empty();
let mut ctx = let mut ctx = EvaluationContext::basic();
basic_evaluation_context().expect("There was a problem creating a basic context.");
assert!(run_external_command(cmd, &mut ctx, input, ExternalRedirection::Stdout).is_err()); assert!(run_external_command(cmd, &mut ctx, input, ExternalRedirection::Stdout).is_err());
} }
@ -566,7 +565,7 @@ mod tests {
// fn failure_run() -> Result<(), ShellError> { // fn failure_run() -> Result<(), ShellError> {
// let cmd = ExternalBuilder::for_name("fail").build(); // let cmd = ExternalBuilder::for_name("fail").build();
// let mut ctx = crate::cli::basic_evaluation_context().expect("There was a problem creating a basic context."); // let mut ctx = crate::cli::EvaluationContext::basic().expect("There was a problem creating a basic context.");
// let stream = run_external_command(cmd, &mut ctx, None, false) // let stream = run_external_command(cmd, &mut ctx, None, false)
// ? // ?
// .expect("There was a problem running the external command."); // .expect("There was a problem running the external command.");

View File

@ -34,7 +34,7 @@ impl WholeStreamCommand for SubCommand {
pub fn clear(args: CommandArgs) -> Result<ActionStream, ShellError> { pub fn clear(args: CommandArgs) -> Result<ActionStream, ShellError> {
let ctx = EvaluationContext::from_args(&args); let ctx = EvaluationContext::from_args(&args);
let result = if let Some(global_cfg) = &mut args.configs.lock().global_config { let result = if let Some(global_cfg) = &mut args.configs().lock().global_config {
global_cfg.vars.clear(); global_cfg.vars.clear();
global_cfg.write()?; global_cfg.write()?;
ctx.reload_config(global_cfg)?; ctx.reload_config(global_cfg)?;

View File

@ -21,9 +21,9 @@ impl WholeStreamCommand for Command {
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> {
let name = args.call_info.name_tag; let name = args.call_info.name_tag.clone();
if let Some(global_cfg) = &args.configs.lock().global_config { if let Some(global_cfg) = &args.configs().lock().global_config {
let result = global_cfg.vars.clone(); let result = global_cfg.vars.clone();
Ok(vec![ReturnSuccess::value( Ok(vec![ReturnSuccess::value(
UntaggedValue::Row(result.into()).into_value(name), UntaggedValue::Row(result.into()).into_value(name),

View File

@ -32,7 +32,7 @@ impl WholeStreamCommand for SubCommand {
} }
pub fn path(args: CommandArgs) -> Result<ActionStream, ShellError> { pub fn path(args: CommandArgs) -> Result<ActionStream, ShellError> {
if let Some(global_cfg) = &mut args.configs.lock().global_config { if let Some(global_cfg) = &mut args.configs().lock().global_config {
Ok(ActionStream::one(ReturnSuccess::value( Ok(ActionStream::one(ReturnSuccess::value(
UntaggedValue::Primitive(Primitive::FilePath(global_cfg.file_path.clone())), UntaggedValue::Primitive(Primitive::FilePath(global_cfg.file_path.clone())),
))) )))

View File

@ -26,7 +26,7 @@ impl WholeStreamCommand for Cpy {
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> {
let shell_manager = args.shell_manager.clone(); let shell_manager = args.shell_manager();
let name = args.call_info.name_tag.clone(); let name = args.call_info.name_tag.clone();
let (args, _) = args.process()?; let (args, _) = args.process()?;
shell_manager.cp(args, name) shell_manager.cp(args, name)

View File

@ -20,7 +20,7 @@ impl WholeStreamCommand for Command {
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> {
Ok(ActionStream::one(ReturnSuccess::value( Ok(ActionStream::one(ReturnSuccess::value(
UntaggedValue::string(get_full_help(&Command, &args.scope)).into_value(Tag::unknown()), UntaggedValue::string(get_full_help(&Command, args.scope())).into_value(Tag::unknown()),
))) )))
} }
} }

View File

@ -1,10 +1,9 @@
use crate::prelude::*; use crate::prelude::*;
use nu_engine::basic_evaluation_context;
use nu_engine::whole_stream_command; use nu_engine::whole_stream_command;
use std::error::Error; use std::error::Error;
pub fn create_default_context(interactive: bool) -> Result<EvaluationContext, Box<dyn Error>> { pub fn create_default_context(interactive: bool) -> Result<EvaluationContext, Box<dyn Error>> {
let context = basic_evaluation_context()?; let context = EvaluationContext::basic();
{ {
use crate::commands::*; use crate::commands::*;

View File

@ -85,7 +85,7 @@ impl WholeStreamCommand for Du {
fn du(args: CommandArgs) -> Result<ActionStream, ShellError> { fn du(args: CommandArgs) -> Result<ActionStream, ShellError> {
let tag = args.call_info.name_tag.clone(); let tag = args.call_info.name_tag.clone();
let ctrl_c = args.ctrl_c.clone(); let ctrl_c = args.ctrl_c();
let ctrl_c_copy = ctrl_c.clone(); let ctrl_c_copy = ctrl_c.clone();
let (args, _): (DuArgs, _) = args.process()?; let (args, _): (DuArgs, _) = args.process()?;

View File

@ -75,16 +75,12 @@ documentation link at https://docs.rs/encoding_rs/0.8.28/encoding_rs/#statics"#
} }
} }
fn enter(raw_args: CommandArgs) -> Result<ActionStream, ShellError> { fn enter(args: CommandArgs) -> Result<ActionStream, ShellError> {
let scope = raw_args.scope.clone(); let head = args.call_info.args.head.clone();
let shell_manager = raw_args.shell_manager.clone(); let context = args.context.clone();
let head = raw_args.call_info.args.head.clone(); let scope = args.scope().clone();
let ctrl_c = raw_args.ctrl_c.clone(); let path = args.context.shell_manager.path();
let configs = raw_args.configs.clone(); let (EnterArgs { location, encoding }, _) = args.process()?;
let current_errors = raw_args.current_errors.clone();
let host = raw_args.host.clone();
let tag = raw_args.call_info.name_tag.clone();
let (EnterArgs { location, encoding }, _) = raw_args.process()?;
let location_string = location.display().to_string(); let location_string = location.display().to_string();
if location.is_dir() { if location.is_dir() {
@ -93,7 +89,7 @@ fn enter(raw_args: CommandArgs) -> Result<ActionStream, ShellError> {
))) )))
} else { } else {
// If it's a file, attempt to open the file as a value and enter it // If it's a file, attempt to open the file as a value and enter it
let cwd = shell_manager.path(); let cwd = path;
let full_path = std::path::PathBuf::from(cwd); let full_path = std::path::PathBuf::from(cwd);
let span = location.span(); let span = location.span();
@ -110,12 +106,9 @@ fn enter(raw_args: CommandArgs) -> Result<ActionStream, ShellError> {
if let Some(extension) = file_extension { if let Some(extension) = file_extension {
let command_name = format!("from {}", extension); let command_name = format!("from {}", extension);
if let Some(converter) = scope.get_command(&command_name) { if let Some(converter) = scope.get_command(&command_name) {
let new_args = RawCommandArgs { let tag = tagged_contents.tag.clone();
host, let new_args = CommandArgs {
ctrl_c, context,
configs,
current_errors,
shell_manager,
call_info: UnevaluatedCallInfo { call_info: UnevaluatedCallInfo {
args: nu_protocol::hir::Call { args: nu_protocol::hir::Call {
head, head,
@ -124,13 +117,11 @@ fn enter(raw_args: CommandArgs) -> Result<ActionStream, ShellError> {
span: Span::unknown(), span: Span::unknown(),
external_redirection: ExternalRedirection::Stdout, external_redirection: ExternalRedirection::Stdout,
}, },
name_tag: tag, name_tag: tag.clone(),
}, },
scope, input: InputStream::one(tagged_contents),
}; };
let tag = tagged_contents.tag.clone(); let mut result = converter.run(new_args)?;
let mut result =
converter.run(new_args.with_input(vec![tagged_contents]))?;
let result_vec: Vec<Value> = result.drain_vec(); let result_vec: Vec<Value> = result.drain_vec();
Ok(result_vec Ok(result_vec
.into_iter() .into_iter()

View File

@ -20,7 +20,7 @@ impl WholeStreamCommand for From {
fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
Ok(OutputStream::one( Ok(OutputStream::one(
UntaggedValue::string(get_full_help(&From, &args.scope)).into_value(Tag::unknown()), UntaggedValue::string(get_full_help(&From, args.scope())).into_value(Tag::unknown()),
)) ))
} }
} }

View File

@ -23,7 +23,7 @@ impl WholeStreamCommand for Command {
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> {
Ok(ActionStream::one(ReturnSuccess::value( Ok(ActionStream::one(ReturnSuccess::value(
UntaggedValue::string(get_full_help(&Command, &args.scope)).into_value(Tag::unknown()), UntaggedValue::string(get_full_help(&Command, args.scope())).into_value(Tag::unknown()),
))) )))
} }
} }

View File

@ -38,7 +38,7 @@ impl WholeStreamCommand for Help {
fn help(args: CommandArgs) -> Result<ActionStream, ShellError> { fn help(args: CommandArgs) -> Result<ActionStream, ShellError> {
let name = args.call_info.name_tag.clone(); let name = args.call_info.name_tag.clone();
let scope = args.scope.clone(); let scope = args.scope().clone();
let (HelpArgs { rest }, ..) = args.process()?; let (HelpArgs { rest }, ..) = args.process()?;
if !rest.is_empty() { if !rest.is_empty() {

View File

@ -20,7 +20,7 @@ impl WholeStreamCommand for Command {
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> {
Ok(ActionStream::one(ReturnSuccess::value( Ok(ActionStream::one(ReturnSuccess::value(
UntaggedValue::string(get_full_help(&Command, &args.scope)).into_value(Tag::unknown()), UntaggedValue::string(get_full_help(&Command, args.scope())).into_value(Tag::unknown()),
))) )))
} }
} }

View File

@ -41,8 +41,8 @@ impl WholeStreamCommand for Ls {
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> {
let name = args.call_info.name_tag.clone(); let name = args.call_info.name_tag.clone();
let ctrl_c = args.ctrl_c.clone(); let ctrl_c = args.ctrl_c();
let shell_manager = args.shell_manager.clone(); let shell_manager = args.shell_manager();
let (args, _) = args.process()?; let (args, _) = args.process()?;
shell_manager.ls(args, name, ctrl_c) shell_manager.ls(args, name, ctrl_c)
} }

View File

@ -1,352 +1,351 @@
#[doc(hidden)] // #[doc(hidden)]
#[macro_export] // #[macro_export]
macro_rules! command { // macro_rules! command {
( // (
Named { $export:tt $args:ident $body:block } // Named { $export:tt $args:ident $body:block }
Positional { $($number:tt)* } // Positional { $($number:tt)* }
Rest {} // Rest {}
Signature { // Signature {
name: $config_name:tt, // name: $config_name:tt,
mandatory_positional: vec![ $($mandatory_positional:tt)* ], // mandatory_positional: vec![ $($mandatory_positional:tt)* ],
optional_positional: vec![ $($optional_positional:tt)* ], // optional_positional: vec![ $($optional_positional:tt)* ],
rest_positional: $rest_positional:tt, // rest_positional: $rest_positional:tt,
named: { // named: {
$( // $(
($named_param:tt : $named_type:ty : $named_kind:tt) // ($named_param:tt : $named_type:ty : $named_kind:tt)
)* // )*
} // }
} // }
Function { // Function {
$( ( $param_name:tt : $param_type:tt ) )* // $( ( $param_name:tt : $param_type:tt ) )*
} // }
Extract { // Extract {
$($extract:tt)* // $($extract:tt)*
} // }
) => { // ) => {
#[allow(non_camel_case_types)] // #[allow(non_camel_case_types)]
pub struct $export; // pub struct $export;
impl Command for $export { // impl Command for $export {
fn run(&self, $args: CommandArgs) -> Result<OutputStream, ShellError> { // fn run(&self, $args: CommandArgs) -> Result<OutputStream, ShellError> {
fn command($args: EvaluatedCommandArgs, ( $($param_name),*, ): ( $($param_type),*, )) -> Result<OutputStream, ShellError> { // fn command($args: EvaluatedCommandArgs, ( $($param_name),*, ): ( $($param_type),*, )) -> Result<OutputStream, ShellError> {
let output = $body; // let output = $body;
Ok(output.to_action_stream()) // Ok(output.to_action_stream())
} // }
let $args = $args.evaluate_once(registry)?; // let $args = $args.evaluate_once(registry)?;
let tuple = ( $($extract ,)* ); // let tuple = ( $($extract ,)* );
command( $args, tuple ) // command( $args, tuple )
} // }
fn name(&self) -> &str { // fn name(&self) -> &str {
stringify!($config_name) // stringify!($config_name)
} // }
fn config(&self) -> $nu_parser::registry::Signature { // fn config(&self) -> $nu_parser::registry::Signature {
$nu_parser::registry::Signature { // $nu_parser::registry::Signature {
name: self.name().to_string(), // name: self.name().to_string(),
positional: vec![$($mandatory_positional)*], // positional: vec![$($mandatory_positional)*],
rest_positional: false, // rest_positional: false,
is_filter: false, // is_filter: false,
is_sink: false, // is_sink: false,
named: { // named: {
use $nu_parser::registry::NamedType; // use $nu_parser::registry::NamedType;
#[allow(unused_mut)] // #[allow(unused_mut)]
let mut named: indexmap::IndexMap<String, NamedType> = indexmap::IndexMap::new(); // let mut named: indexmap::IndexMap<String, NamedType> = indexmap::IndexMap::new();
$( // $(
named.insert(stringify!($named_param).to_string(), $nu_parser::registry::NamedType::$named_kind); // named.insert(stringify!($named_param).to_string(), $nu_parser::registry::NamedType::$named_kind);
)* // )*
named // named
} // }
} // }
} // }
} // }
}; // };
// switch // // switch
( // (
Named { $export:tt $args:ident $body:block } // Named { $export:tt $args:ident $body:block }
Positional { $($positional_count:tt)* } // Positional { $($positional_count:tt)* }
Rest { -- $param_name:ident : Switch , $($rest:tt)* } // Rest { -- $param_name:ident : Switch , $($rest:tt)* }
Signature { // Signature {
name: $config_name:tt, // name: $config_name:tt,
mandatory_positional: vec![ $($mandatory_positional:tt)* ], // mandatory_positional: vec![ $($mandatory_positional:tt)* ],
optional_positional: vec![ $($optional_positional:tt)* ], // optional_positional: vec![ $($optional_positional:tt)* ],
rest_positional: $rest_positional:tt, // rest_positional: $rest_positional:tt,
named: { // named: {
$($config_named:tt)* // $($config_named:tt)*
} // }
} // }
Function { // Function {
$($function:tt)* // $($function:tt)*
} // }
Extract { // Extract {
$($extract:tt)* // $($extract:tt)*
} // }
) => { // ) => {
command!( // command!(
Named { $export $args $body } // Named { $export $args $body }
Positional { $($positional_count)* + 1 } // Positional { $($positional_count)* + 1 }
Rest { $($rest)* } // Rest { $($rest)* }
Signature { // Signature {
name: $config_name, // name: $config_name,
mandatory_positional: vec![ $($mandatory_positional)* ], // mandatory_positional: vec![ $($mandatory_positional)* ],
optional_positional: vec![ $($optional_positional)* ], // optional_positional: vec![ $($optional_positional)* ],
rest_positional: $rest_positional, // rest_positional: $rest_positional,
named: { // named: {
$($config_named)* // $($config_named)*
($param_name : Switch : Switch) // ($param_name : Switch : Switch)
} // }
} // }
Function { // Function {
$($function)* ($param_name : Switch) // $($function)* ($param_name : Switch)
} // }
Extract { // Extract {
$($extract)* { // $($extract)* {
use std::convert::TryInto; // use std::convert::TryInto;
$args.get(stringify!($param_name)).try_into()? // $args.get(stringify!($param_name)).try_into()?
} // }
} // }
); // );
}; // };
// mandatory named arguments // // mandatory named arguments
( // (
Named { $export:tt $args:ident $body:block } // Named { $export:tt $args:ident $body:block }
Positional { $($positional_count:tt)* } // Positional { $($positional_count:tt)* }
Rest { -- $param_name:ident : $param_kind:ty , $($rest:tt)* } // Rest { -- $param_name:ident : $param_kind:ty , $($rest:tt)* }
Signature { // Signature {
name: $config_name:tt, // name: $config_name:tt,
mandatory_positional: vec![ $($mandatory_positional:tt)* ], // mandatory_positional: vec![ $($mandatory_positional:tt)* ],
optional_positional: vec![ $($optional_positional:tt)* ], // optional_positional: vec![ $($optional_positional:tt)* ],
rest_positional: $rest_positional:tt, // rest_positional: $rest_positional:tt,
named: { // named: {
$($config_named:tt)* // $($config_named:tt)*
} // }
} // }
Function { // Function {
$($function:tt)* // $($function:tt)*
} // }
Extract { // Extract {
$($extract:tt)* // $($extract:tt)*
} // }
) => { // ) => {
command!( // command!(
Named { $export $args $body } // Named { $export $args $body }
Positional { $($positional_count)* + 1 } // Positional { $($positional_count)* + 1 }
Rest { $($rest)* } // Rest { $($rest)* }
Signature { // Signature {
name: $config_name, // name: $config_name,
mandatory_positional: vec![ $($mandatory_positional)* ], // mandatory_positional: vec![ $($mandatory_positional)* ],
optional_positional: vec![ $($optional_positional)* ], // optional_positional: vec![ $($optional_positional)* ],
rest_positional: $rest_positional, // rest_positional: $rest_positional,
named: { // named: {
$($config_named)* // $($config_named)*
($param_name : Mandatory(NamedValue::Single)) // ($param_name : Mandatory(NamedValue::Single))
} // }
} // }
Function { // Function {
$($function)* ($param_name : $param_kind) // $($function)* ($param_name : $param_kind)
} // }
Extract { // Extract {
$($extract)* { // $($extract)* {
use std::convert::TryInto; // use std::convert::TryInto;
$args.get(stringify!($param_name)).try_into()? // $args.get(stringify!($param_name)).try_into()?
} // }
} // }
); // );
}; // };
// optional named arguments // // optional named arguments
( // (
Named { $export:tt $args:ident $body:block } // Named { $export:tt $args:ident $body:block }
Positional { $($positional_count:tt)* } // Positional { $($positional_count:tt)* }
Rest { -- $param_name:ident ? : $param_kind:ty , $($rest:tt)* } // Rest { -- $param_name:ident ? : $param_kind:ty , $($rest:tt)* }
Signature { // Signature {
name: $config_name:tt, // name: $config_name:tt,
mandatory_positional: vec![ $($mandatory_positional:tt)* ], // mandatory_positional: vec![ $($mandatory_positional:tt)* ],
optional_positional: vec![ $($optional_positional:tt)* ], // optional_positional: vec![ $($optional_positional:tt)* ],
rest_positional: $rest_positional:tt, // rest_positional: $rest_positional:tt,
named: { // named: {
$($config_named:tt)* // $($config_named:tt)*
} // }
} // }
Function { // Function {
$($function:tt)* // $($function:tt)*
} // }
Extract { // Extract {
$($extract:tt)* // $($extract:tt)*
} // }
) => { // ) => {
command!( // command!(
Named { $export $args $body } // Named { $export $args $body }
Positional { $($positional_count)* + 1 } // Positional { $($positional_count)* + 1 }
Rest { $($rest)* } // Rest { $($rest)* }
Signature { // Signature {
name: $config_name, // name: $config_name,
mandatory_positional: vec![ $($mandatory_positional)* ], // mandatory_positional: vec![ $($mandatory_positional)* ],
optional_positional: vec![ $($optional_positional)* ], // optional_positional: vec![ $($optional_positional)* ],
rest_positional: $rest_positional, // rest_positional: $rest_positional,
named: { // named: {
$($config_named)* // $($config_named)*
($param_name : Optional(NamedValue::Single)) // ($param_name : Optional(NamedValue::Single))
} // }
} // }
Function { // Function {
$($function)* ($param_name : $param_kind) // $($function)* ($param_name : $param_kind)
} // }
Extract { // Extract {
$($extract)* { // $($extract)* {
use std::convert::TryInto; // use std::convert::TryInto;
$args.get(stringify!($param_name)).try_into()? // $args.get(stringify!($param_name)).try_into()?
} // }
} // }
); // );
}; // };
// mandatory positional block // // mandatory positional block
( // (
Named { $export:ident $args:ident $body:block } // Named { $export:ident $args:ident $body:block }
Positional { $($positional_count:tt)* } // Positional { $($positional_count:tt)* }
Rest { $param_name:ident : Block , $($rest:tt)* } // Rest { $param_name:ident : Block , $($rest:tt)* }
Signature { // Signature {
name: $config_name:tt, // name: $config_name:tt,
mandatory_positional: vec![ $($mandatory_positional:tt)* ], // mandatory_positional: vec![ $($mandatory_positional:tt)* ],
optional_positional: vec![ $($optional_positional:tt)* ], // optional_positional: vec![ $($optional_positional:tt)* ],
rest_positional: $rest_positional:tt, // rest_positional: $rest_positional:tt,
named: { // named: {
$($config_named:tt)* // $($config_named:tt)*
} // }
} // }
Function { // Function {
$($function:tt)* // $($function:tt)*
} // }
Extract { // Extract {
$($extract:tt)* // $($extract:tt)*
} // }
) => { // ) => {
command!( // command!(
Named { $export $args $body } // Named { $export $args $body }
Positional { $($positional_count)* + 1 } // Positional { $($positional_count)* + 1 }
Rest { $($rest)* } // Rest { $($rest)* }
Signature { // Signature {
name: $config_name, // name: $config_name,
mandatory_positional: vec![ $($mandatory_positional)* $nu_parser::registry::PositionalType::mandatory_block( // mandatory_positional: vec![ $($mandatory_positional)* $nu_parser::registry::PositionalType::mandatory_block(
stringify!($param_name) // stringify!($param_name)
), ], // ), ],
optional_positional: vec![ $($optional_positional)* ], // optional_positional: vec![ $($optional_positional)* ],
rest_positional: $rest_positional, // rest_positional: $rest_positional,
named: { // named: {
$($config_named)* // $($config_named)*
} // }
} // }
Function { // Function {
$($function)* ($param_name : Block) // $($function)* ($param_name : Block)
} // }
Extract { // Extract {
$($extract:tt)* { // $($extract:tt)* {
use $nu_data::types::ExtractType; // use $nu_data::types::ExtractType;
let value = $args.expect_nth($($positional_count)*)?; // let value = $args.expect_nth($($positional_count)*)?;
Block::extract(value)? // Block::extract(value)?
} // }
} // }
); // );
}; // };
// // mandatory positional argument
// (
// Named { $export:ident $args:ident $body:block }
// Positional { $($positional_count:tt)* }
// Rest { $param_name:ident : $param_kind:ty , $($rest:tt)* }
// Signature {
// name: $config_name:tt,
// mandatory_positional: vec![ $($mandatory_positional:tt)* ],
// optional_positional: vec![ $($optional_positional:tt)* ],
// rest_positional: $rest_positional:tt,
// named: {
// $($config_named:tt)*
// }
// }
// mandatory positional argument // Function {
( // $($function:tt)*
Named { $export:ident $args:ident $body:block } // }
Positional { $($positional_count:tt)* }
Rest { $param_name:ident : $param_kind:ty , $($rest:tt)* }
Signature {
name: $config_name:tt,
mandatory_positional: vec![ $($mandatory_positional:tt)* ],
optional_positional: vec![ $($optional_positional:tt)* ],
rest_positional: $rest_positional:tt,
named: {
$($config_named:tt)*
}
}
Function { // Extract {
$($function:tt)* // $($extract:tt)*
} // }
Extract { // ) => {
$($extract:tt)* // command!(
} // Named { $export $args $body }
// Positional { $($positional_count)* + 1 }
// Rest { $($rest)* }
// Signature {
// name: $config_name,
// mandatory_positional: vec![ $($mandatory_positional)* $nu_parser::registry::PositionalType::mandatory(
// stringify!($param_name), <$param_kind>::syntax_type()
// ), ],
// optional_positional: vec![ $($optional_positional)* ],
// rest_positional: $rest_positional,
// named: {
// $($config_named)*
// }
// }
) => { // Function {
command!( // $($function)* ($param_name : $param_kind)
Named { $export $args $body } // }
Positional { $($positional_count)* + 1 }
Rest { $($rest)* }
Signature {
name: $config_name,
mandatory_positional: vec![ $($mandatory_positional)* $nu_parser::registry::PositionalType::mandatory(
stringify!($param_name), <$param_kind>::syntax_type()
), ],
optional_positional: vec![ $($optional_positional)* ],
rest_positional: $rest_positional,
named: {
$($config_named)*
}
}
Function { // Extract {
$($function)* ($param_name : $param_kind) // $($extract:tt)* {
} // use $nu_data::types::ExtractType;
// let value = $args.expect_nth($($positional_count)*)?;
// <$param_kind>::extract(&value)?
// }
// }
// );
// };
Extract { // ($export:ident as $config_name:tt ( $args:ident , $($command_rest:tt)* ) $body:block) => {
$($extract:tt)* { // command!(
use $nu_data::types::ExtractType; // Named { $export $args $body }
let value = $args.expect_nth($($positional_count)*)?; // Positional { 0 }
<$param_kind>::extract(&value)? // Rest { $($command_rest)* }
} // Signature {
} // name: $config_name,
); // mandatory_positional: vec![],
}; // optional_positional: vec![],
// rest_positional: false,
// named: {}
// }
($export:ident as $config_name:tt ( $args:ident , $($command_rest:tt)* ) $body:block) => { // Function {
command!( // }
Named { $export $args $body }
Positional { 0 }
Rest { $($command_rest)* }
Signature {
name: $config_name,
mandatory_positional: vec![],
optional_positional: vec![],
rest_positional: false,
named: {}
}
Function { // Extract {
} // }
// );
Extract { // };
} // }
);
};
}

View File

@ -20,7 +20,7 @@ impl WholeStreamCommand for Command {
fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
Ok(OutputStream::one( Ok(OutputStream::one(
UntaggedValue::string(get_full_help(&Command, &args.scope)).into_value(Tag::unknown()), UntaggedValue::string(get_full_help(&Command, args.scope())).into_value(Tag::unknown()),
)) ))
} }
} }

View File

@ -37,7 +37,7 @@ impl WholeStreamCommand for Mkdir {
fn mkdir(args: CommandArgs) -> Result<ActionStream, ShellError> { fn mkdir(args: CommandArgs) -> Result<ActionStream, ShellError> {
let name = args.call_info.name_tag.clone(); let name = args.call_info.name_tag.clone();
let shell_manager = args.shell_manager.clone(); let shell_manager = args.shell_manager();
let (args, _) = args.process()?; let (args, _) = args.process()?;
shell_manager.mkdir(args, name) shell_manager.mkdir(args, name)

View File

@ -55,7 +55,7 @@ impl WholeStreamCommand for Mv {
fn mv(args: CommandArgs) -> Result<ActionStream, ShellError> { fn mv(args: CommandArgs) -> Result<ActionStream, ShellError> {
let name = args.call_info.name_tag.clone(); let name = args.call_info.name_tag.clone();
let shell_manager = args.shell_manager.clone(); let shell_manager = args.shell_manager();
let (args, _) = args.process()?; let (args, _) = args.process()?;
shell_manager.mv(args, name) shell_manager.mv(args, name)

View File

@ -46,8 +46,8 @@ impl WholeStreamCommand for SubCommand {
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> {
let scope = args.scope.clone(); let scope = args.scope().clone();
let shell_manager = args.shell_manager.clone(); let shell_manager = args.shell_manager();
let (Arguments { load_path }, _) = args.process()?; let (Arguments { load_path }, _) = args.process()?;
if let Some(Tagged { if let Some(Tagged {

View File

@ -100,11 +100,11 @@ pub fn get_encoding(opt: Option<Tagged<String>>) -> Result<&'static Encoding, Sh
} }
fn open(args: CommandArgs) -> Result<ActionStream, ShellError> { fn open(args: CommandArgs) -> Result<ActionStream, ShellError> {
let scope = args.scope.clone(); let scope = args.scope().clone();
let cwd = PathBuf::from(args.shell_manager.path()); let shell_manager = args.shell_manager();
let shell_manager = args.shell_manager.clone(); let cwd = PathBuf::from(shell_manager.path());
let name = args.call_info.name_tag.clone(); let name = args.call_info.name_tag.clone();
let ctrl_c = args.ctrl_c.clone(); let ctrl_c = args.ctrl_c();
let ( let (
OpenArgs { OpenArgs {

View File

@ -35,7 +35,7 @@ the path literal."#
fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
Ok(OutputStream::one( Ok(OutputStream::one(
UntaggedValue::string(get_full_help(&Path, &args.scope)).into_value(Tag::unknown()), UntaggedValue::string(get_full_help(&Path, args.scope())).into_value(Tag::unknown()),
)) ))
} }
} }

View File

@ -32,7 +32,7 @@ impl WholeStreamCommand for Pwd {
} }
pub fn pwd(args: CommandArgs) -> Result<ActionStream, ShellError> { pub fn pwd(args: CommandArgs) -> Result<ActionStream, ShellError> {
let shell_manager = args.shell_manager.clone(); let shell_manager = args.shell_manager();
let args = args.evaluate_once()?; let args = args.evaluate_once()?;
shell_manager.pwd(args) shell_manager.pwd(args)

View File

@ -20,7 +20,7 @@ impl WholeStreamCommand for Command {
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> {
Ok(ActionStream::one(Ok(ReturnSuccess::Value( Ok(ActionStream::one(Ok(ReturnSuccess::Value(
UntaggedValue::string(get_full_help(&Command, &args.scope)).into_value(Tag::unknown()), UntaggedValue::string(get_full_help(&Command, args.scope())).into_value(Tag::unknown()),
)))) ))))
} }
} }

View File

@ -64,7 +64,7 @@ impl WholeStreamCommand for Remove {
fn rm(args: CommandArgs) -> Result<ActionStream, ShellError> { fn rm(args: CommandArgs) -> Result<ActionStream, ShellError> {
let name = args.call_info.name_tag.clone(); let name = args.call_info.name_tag.clone();
let shell_manager = args.shell_manager.clone(); let shell_manager = args.shell_manager();
let (args, _): (RemoveArgs, _) = args.process()?; let (args, _): (RemoveArgs, _) = args.process()?;
if args.trash.item && args.permanent.item { if args.trash.item && args.permanent.item {

View File

@ -2,7 +2,6 @@ use crate::commands::classified::external;
use crate::prelude::*; use crate::prelude::*;
use derive_new::new; use derive_new::new;
use parking_lot::Mutex;
use std::path::PathBuf; use std::path::PathBuf;
use nu_engine::shell::CdArgs; use nu_engine::shell::CdArgs;
@ -75,17 +74,7 @@ impl WholeStreamCommand for RunExternalCommand {
}) })
.and_then(spanned_expression_to_string)?; .and_then(spanned_expression_to_string)?;
let mut external_context = { let mut external_context = args.context.clone();
EvaluationContext {
scope: args.scope.clone(),
host: args.host.clone(),
shell_manager: args.shell_manager.clone(),
ctrl_c: args.ctrl_c.clone(),
configs: args.configs.clone(),
current_errors: Arc::new(Mutex::new(vec![])),
windows_drives_previous_cwd: Arc::new(Mutex::new(std::collections::HashMap::new())),
}
};
let is_interactive = self.interactive; let is_interactive = self.interactive;
@ -111,7 +100,7 @@ impl WholeStreamCommand for RunExternalCommand {
let result = external_context let result = external_context
.shell_manager .shell_manager
.cd(cd_args, args.call_info.name_tag.clone()); .cd(cd_args, args.call_info.name_tag);
return Ok(result?.to_action_stream()); return Ok(result?.to_action_stream());
} }

View File

@ -153,19 +153,16 @@ impl WholeStreamCommand for Save {
} }
} }
fn save(raw_args: CommandArgs) -> Result<OutputStream, ShellError> { fn save(args: CommandArgs) -> Result<OutputStream, ShellError> {
let mut full_path = PathBuf::from(raw_args.shell_manager.path()); let shell_manager = args.shell_manager();
let name_tag = raw_args.call_info.name_tag.clone(); let mut full_path = PathBuf::from(shell_manager.path());
let name = raw_args.call_info.name_tag.clone(); let name_tag = args.call_info.name_tag.clone();
let scope = raw_args.scope.clone(); let name = args.call_info.name_tag.clone();
let host = raw_args.host.clone(); let context = args.context.clone();
let ctrl_c = raw_args.ctrl_c.clone(); let scope = args.scope().clone();
let configs = raw_args.configs.clone();
let current_errors = raw_args.current_errors.clone();
let shell_manager = raw_args.shell_manager.clone();
let head = raw_args.call_info.args.head.clone(); let head = args.call_info.args.head.clone();
let args = raw_args.evaluate_once()?; let args = args.evaluate_once()?;
let path: Option<Tagged<PathBuf>> = args.opt(0)?; let path: Option<Tagged<PathBuf>> = args.opt(0)?;
let save_raw = args.has_flag("raw"); let save_raw = args.has_flag("raw");
@ -203,12 +200,8 @@ fn save(raw_args: CommandArgs) -> Result<OutputStream, ShellError> {
if let Some(extension) = full_path.extension() { if let Some(extension) = full_path.extension() {
let command_name = format!("to {}", extension.to_string_lossy()); let command_name = format!("to {}", extension.to_string_lossy());
if let Some(converter) = scope.get_command(&command_name) { if let Some(converter) = scope.get_command(&command_name) {
let new_args = RawCommandArgs { let new_args = CommandArgs {
host, context,
ctrl_c,
configs,
current_errors,
shell_manager: shell_manager.clone(),
call_info: UnevaluatedCallInfo { call_info: UnevaluatedCallInfo {
args: nu_protocol::hir::Call { args: nu_protocol::hir::Call {
head, head,
@ -219,9 +212,9 @@ fn save(raw_args: CommandArgs) -> Result<OutputStream, ShellError> {
}, },
name_tag: name_tag.clone(), name_tag: name_tag.clone(),
}, },
scope, input: InputStream::from_stream(input.into_iter()),
}; };
let mut result = converter.run(new_args.with_input(input))?; let mut result = converter.run(new_args)?;
let result_vec: Vec<Value> = result.drain_vec(); let result_vec: Vec<Value> = result.drain_vec();
if converter.is_binary() { if converter.is_binary() {
process_binary_return_success!('scope, result_vec, name_tag) process_binary_return_success!('scope, result_vec, name_tag)

View File

@ -26,12 +26,14 @@ impl WholeStreamCommand for Shells {
fn shells(args: CommandArgs) -> ActionStream { fn shells(args: CommandArgs) -> ActionStream {
let mut shells_out = VecDeque::new(); let mut shells_out = VecDeque::new();
let shell_manager = args.shell_manager();
let tag = args.call_info.name_tag; let tag = args.call_info.name_tag;
let active_index = shell_manager.current_shell.load(Ordering::SeqCst);
for (index, shell) in args.shell_manager.shells.lock().iter().enumerate() { for (index, shell) in shell_manager.shells.lock().iter().enumerate() {
let mut dict = TaggedDictBuilder::new(&tag); let mut dict = TaggedDictBuilder::new(&tag);
if index == (*args.shell_manager.current_shell).load(Ordering::SeqCst) { if index == active_index {
dict.insert_untagged("active", true); dict.insert_untagged("active", true);
} else { } else {
dict.insert_untagged("active", false); dict.insert_untagged("active", false);

View File

@ -35,7 +35,7 @@ impl WholeStreamCommand for Sleep {
} }
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> {
let ctrl_c = args.ctrl_c().clone(); let ctrl_c = args.ctrl_c();
let (SleepArgs { duration, rest }, _) = args.process()?; let (SleepArgs { duration, rest }, _) = args.process()?;

View File

@ -21,7 +21,7 @@ impl WholeStreamCommand for Command {
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> {
Ok(ActionStream::one(Ok(ReturnSuccess::Value( Ok(ActionStream::one(Ok(ReturnSuccess::Value(
UntaggedValue::string(get_full_help(&Command, &args.scope)).into_value(Tag::unknown()), UntaggedValue::string(get_full_help(&Command, args.scope())).into_value(Tag::unknown()),
)))) ))))
} }
} }

View File

@ -23,7 +23,7 @@ impl WholeStreamCommand for Command {
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> {
Ok(ActionStream::one(ReturnSuccess::value( Ok(ActionStream::one(ReturnSuccess::value(
UntaggedValue::string(get_full_help(&Command, &args.scope)).into_value(Tag::unknown()), UntaggedValue::string(get_full_help(&Command, args.scope())).into_value(Tag::unknown()),
))) )))
} }
} }

View File

@ -173,7 +173,7 @@ fn values_to_entries(
fn table(args: CommandArgs) -> Result<OutputStream, ShellError> { fn table(args: CommandArgs) -> Result<OutputStream, ShellError> {
let mut args = args.evaluate_once()?; let mut args = args.evaluate_once()?;
let configuration = args.configs.lock().global_config(); let configuration = args.configs().lock().global_config();
// Ideally, get_color_config would get all the colors configured in the config.toml // Ideally, get_color_config would get all the colors configured in the config.toml
// and create a style based on those settings. However, there are few places where // and create a style based on those settings. However, there are few places where
@ -191,7 +191,7 @@ fn table(args: CommandArgs) -> Result<OutputStream, ShellError> {
let mut delay_slot = None; let mut delay_slot = None;
let term_width = args.host.lock().width(); let term_width = args.host().lock().width();
#[cfg(feature = "table-pager")] #[cfg(feature = "table-pager")]
let pager = Pager::new() let pager = Pager::new()

View File

@ -21,7 +21,7 @@ impl WholeStreamCommand for To {
fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> { fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
Ok(OutputStream::one( Ok(OutputStream::one(
UntaggedValue::string(get_full_help(&To, &args.scope)).into_value(Tag::unknown()), UntaggedValue::string(get_full_help(&To, args.scope())).into_value(Tag::unknown()),
)) ))
} }
} }

View File

@ -20,7 +20,7 @@ impl WholeStreamCommand for Url {
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> {
Ok(ActionStream::one(ReturnSuccess::value( Ok(ActionStream::one(ReturnSuccess::value(
UntaggedValue::string(get_full_help(&Url, &args.scope)).into_value(Tag::unknown()), UntaggedValue::string(get_full_help(&Url, args.scope())).into_value(Tag::unknown()),
))) )))
} }
} }

View File

@ -220,7 +220,7 @@ fn which(args: CommandArgs) -> Result<OutputStream, ShellError> {
let mut output = vec![]; let mut output = vec![];
for app in which_args.applications { for app in which_args.applications {
let values = which_single(app, which_args.all, &args.scope); let values = which_single(app, which_args.all, &args.scope());
output.extend(values); output.extend(values);
} }

View File

@ -8,7 +8,6 @@ use double_echo::Command as DoubleEcho;
use double_ls::Command as DoubleLs; use double_ls::Command as DoubleLs;
use stub_generate::{mock_path, Command as StubOpen}; use stub_generate::{mock_path, Command as StubOpen};
use nu_engine::basic_evaluation_context;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_parser::ParserScope; use nu_parser::ParserScope;
use nu_protocol::hir::{ClassifiedBlock, ExternalRedirection}; use nu_protocol::hir::{ClassifiedBlock, ExternalRedirection};
@ -25,7 +24,7 @@ use nu_stream::InputStream;
pub fn test_examples(cmd: Command) -> Result<(), ShellError> { pub fn test_examples(cmd: Command) -> Result<(), ShellError> {
let examples = cmd.examples(); let examples = cmd.examples();
let base_context = basic_evaluation_context()?; let base_context = EvaluationContext::basic();
base_context.add_commands(vec![ base_context.add_commands(vec![
// Command Doubles // Command Doubles
@ -91,7 +90,7 @@ pub fn test_examples(cmd: Command) -> Result<(), ShellError> {
pub fn test(cmd: impl WholeStreamCommand + 'static) -> Result<(), ShellError> { pub fn test(cmd: impl WholeStreamCommand + 'static) -> Result<(), ShellError> {
let examples = cmd.examples(); let examples = cmd.examples();
let base_context = basic_evaluation_context()?; let base_context = EvaluationContext::basic();
base_context.add_commands(vec![ base_context.add_commands(vec![
whole_stream_command(Math), whole_stream_command(Math),
@ -150,7 +149,7 @@ pub fn test(cmd: impl WholeStreamCommand + 'static) -> Result<(), ShellError> {
pub fn test_anchors(cmd: Command) -> Result<(), ShellError> { pub fn test_anchors(cmd: Command) -> Result<(), ShellError> {
let examples = cmd.examples(); let examples = cmd.examples();
let base_context = basic_evaluation_context()?; let base_context = EvaluationContext::basic();
base_context.add_commands(vec![ base_context.add_commands(vec![
// Minimal restricted commands to aid in testing // Minimal restricted commands to aid in testing

View File

@ -16,9 +16,8 @@ pub(crate) use nu_data::value;
pub(crate) use nu_engine::EvaluationContext; pub(crate) use nu_engine::EvaluationContext;
pub(crate) use nu_engine::Example; pub(crate) use nu_engine::Example;
pub(crate) use nu_engine::Host; pub(crate) use nu_engine::Host;
pub(crate) use nu_engine::RawCommandArgs; pub(crate) use nu_engine::RunnableContext;
pub(crate) use nu_engine::{get_full_help, CommandArgs, Scope, WholeStreamCommand}; pub(crate) use nu_engine::{get_full_help, CommandArgs, Scope, WholeStreamCommand};
pub(crate) use nu_engine::{RunnableContext, RunnableContextWithoutInput};
pub(crate) use nu_parser::ParserScope; pub(crate) use nu_parser::ParserScope;
pub(crate) use nu_protocol::{out, row}; pub(crate) use nu_protocol::{out, row};
pub(crate) use nu_source::{AnchorLocation, PrettyDebug, Span, SpannedItem, Tag, TaggedItem}; pub(crate) use nu_source::{AnchorLocation, PrettyDebug, Span, SpannedItem, Tag, TaggedItem};

View File

@ -1,26 +0,0 @@
use crate::EvaluationContext;
use crate::Scope;
use crate::{basic_shell_manager, config_holder::ConfigHolder};
use crate::{env::basic_host::BasicHost, Host};
use indexmap::IndexMap;
use parking_lot::Mutex;
use std::error::Error;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
pub fn basic_evaluation_context() -> Result<EvaluationContext, Box<dyn Error>> {
let scope = Scope::new();
let mut host = BasicHost {};
let env_vars = host.vars().iter().cloned().collect::<IndexMap<_, _>>();
scope.add_env(env_vars);
Ok(EvaluationContext {
scope,
host: Arc::new(parking_lot::Mutex::new(Box::new(host))),
current_errors: Arc::new(Mutex::new(vec![])),
ctrl_c: Arc::new(AtomicBool::new(false)),
configs: Arc::new(Mutex::new(ConfigHolder::new())),
shell_manager: basic_shell_manager::basic_shell_manager()?,
windows_drives_previous_cwd: Arc::new(Mutex::new(std::collections::HashMap::new())),
})
}

View File

@ -1,16 +0,0 @@
use crate::filesystem::filesystem_shell::{FilesystemShell, FilesystemShellMode};
use crate::shell::shell_manager::ShellManager;
use parking_lot::Mutex;
use std::error::Error;
use std::sync::atomic::AtomicUsize;
use std::sync::Arc;
pub fn basic_shell_manager() -> Result<ShellManager, Box<dyn Error>> {
Ok(ShellManager {
current_shell: Arc::new(AtomicUsize::new(0)),
shells: Arc::new(Mutex::new(vec![Box::new(FilesystemShell::basic(
FilesystemShellMode::Cli,
)?)])),
})
}

View File

@ -21,72 +21,39 @@ use std::sync::Arc;
#[derive(Getters)] #[derive(Getters)]
#[get = "pub"] #[get = "pub"]
pub struct CommandArgs { pub struct CommandArgs {
pub host: Arc<parking_lot::Mutex<Box<dyn Host>>>, pub context: EvaluationContext,
pub ctrl_c: Arc<AtomicBool>,
pub configs: Arc<Mutex<ConfigHolder>>,
pub current_errors: Arc<Mutex<Vec<ShellError>>>,
pub shell_manager: ShellManager,
pub call_info: UnevaluatedCallInfo, pub call_info: UnevaluatedCallInfo,
pub scope: Scope,
pub input: InputStream, pub input: InputStream,
} }
impl CommandArgs {
pub fn scope(&self) -> &Scope {
&self.context.scope
}
pub fn host(&self) -> Arc<parking_lot::Mutex<Box<dyn Host>>> {
self.context.host.clone()
}
pub fn current_errors(&self) -> Arc<Mutex<Vec<ShellError>>> {
self.context.current_errors.clone()
}
pub fn ctrl_c(&self) -> Arc<AtomicBool> {
self.context.ctrl_c.clone()
}
pub fn configs(&self) -> Arc<Mutex<ConfigHolder>> {
self.context.configs.clone()
}
pub fn shell_manager(&self) -> ShellManager {
self.context.shell_manager.clone()
}
}
pub type RunnableContext = CommandArgs; pub type RunnableContext = CommandArgs;
#[derive(Clone)]
pub struct RunnableContextWithoutInput {
pub shell_manager: ShellManager,
pub host: Arc<parking_lot::Mutex<Box<dyn Host>>>,
pub current_errors: Arc<Mutex<Vec<ShellError>>>,
pub ctrl_c: Arc<AtomicBool>,
pub call_info: UnevaluatedCallInfo,
pub configs: Arc<Mutex<ConfigHolder>>,
pub scope: Scope,
pub name: Tag,
}
impl RunnableContextWithoutInput {
pub fn with_input(self, input: InputStream) -> CommandArgs {
CommandArgs {
shell_manager: self.shell_manager,
host: self.host,
current_errors: self.current_errors,
ctrl_c: self.ctrl_c,
call_info: self.call_info,
configs: self.configs,
scope: self.scope,
input,
}
}
}
#[derive(Getters, Clone)]
#[get = "pub"]
pub struct RawCommandArgs {
pub host: Arc<parking_lot::Mutex<Box<dyn Host>>>,
pub ctrl_c: Arc<AtomicBool>,
pub current_errors: Arc<Mutex<Vec<ShellError>>>,
pub configs: Arc<Mutex<ConfigHolder>>,
pub shell_manager: ShellManager,
pub scope: Scope,
pub call_info: UnevaluatedCallInfo,
}
impl RawCommandArgs {
pub fn with_input(self, input: impl Into<InputStream>) -> CommandArgs {
CommandArgs {
host: self.host,
ctrl_c: self.ctrl_c,
configs: self.configs,
current_errors: self.current_errors,
shell_manager: self.shell_manager,
call_info: self.call_info,
scope: self.scope,
input: input.into(),
}
}
}
impl std::fmt::Debug for CommandArgs { impl std::fmt::Debug for CommandArgs {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.call_info.fmt(f) self.call_info.fmt(f)
@ -94,49 +61,18 @@ impl std::fmt::Debug for CommandArgs {
} }
impl CommandArgs { impl CommandArgs {
pub fn evaluate_once(self) -> Result<EvaluatedWholeStreamCommandArgs, ShellError> { pub fn evaluate_once(self) -> Result<EvaluatedCommandArgs, ShellError> {
let ctx = EvaluationContext::new( let ctx = self.context.clone();
self.scope,
self.host,
self.current_errors,
self.ctrl_c,
self.configs,
self.shell_manager,
Arc::new(Mutex::new(std::collections::HashMap::new())),
);
let input = self.input; let input = self.input;
let call_info = self.call_info.evaluate(&ctx)?; let call_info = self.call_info.evaluate(&ctx)?;
Ok(EvaluatedWholeStreamCommandArgs::new( Ok(EvaluatedCommandArgs::new(ctx, call_info, input))
ctx.host,
ctx.ctrl_c,
ctx.configs,
ctx.shell_manager,
call_info,
input,
ctx.scope,
))
}
pub fn split(self) -> (InputStream, RunnableContextWithoutInput) {
let new_context = RunnableContextWithoutInput {
shell_manager: self.shell_manager,
host: self.host,
ctrl_c: self.ctrl_c,
configs: self.configs,
name: self.call_info.name_tag.clone(),
call_info: self.call_info,
current_errors: self.current_errors,
scope: self.scope,
};
(self.input, new_context)
} }
pub fn extract<T>( pub fn extract<T>(
self, self,
f: impl FnOnce(&EvaluatedCommandArgs) -> Result<T, ShellError>, f: impl FnOnce(&EvaluatedCommandArgsWithoutInput) -> Result<T, ShellError>,
) -> Result<(T, InputStream), ShellError> { ) -> Result<(T, InputStream), ShellError> {
let evaluated_args = self.evaluate_once()?; let evaluated_args = self.evaluate_once()?;
@ -153,37 +89,26 @@ impl CommandArgs {
} }
} }
pub struct EvaluatedWholeStreamCommandArgs { pub struct EvaluatedCommandArgs {
pub args: EvaluatedCommandArgs, pub args: EvaluatedCommandArgsWithoutInput,
pub input: InputStream, pub input: InputStream,
} }
impl Deref for EvaluatedWholeStreamCommandArgs { impl Deref for EvaluatedCommandArgs {
type Target = EvaluatedCommandArgs; type Target = EvaluatedCommandArgsWithoutInput;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
&self.args &self.args
} }
} }
impl EvaluatedWholeStreamCommandArgs { impl EvaluatedCommandArgs {
pub fn new( pub fn new(
host: Arc<parking_lot::Mutex<dyn Host>>, context: EvaluationContext,
ctrl_c: Arc<AtomicBool>,
configs: Arc<Mutex<ConfigHolder>>,
shell_manager: ShellManager,
call_info: CallInfo, call_info: CallInfo,
input: impl Into<InputStream>, input: impl Into<InputStream>,
scope: Scope, ) -> EvaluatedCommandArgs {
) -> EvaluatedWholeStreamCommandArgs { EvaluatedCommandArgs {
EvaluatedWholeStreamCommandArgs { args: EvaluatedCommandArgsWithoutInput { context, call_info },
args: EvaluatedCommandArgs {
host,
ctrl_c,
configs,
shell_manager,
call_info,
scope,
},
input: input.into(), input: input.into(),
} }
} }
@ -193,13 +118,13 @@ impl EvaluatedWholeStreamCommandArgs {
} }
pub fn parts(self) -> (InputStream, EvaluatedArgs) { pub fn parts(self) -> (InputStream, EvaluatedArgs) {
let EvaluatedWholeStreamCommandArgs { args, input } = self; let EvaluatedCommandArgs { args, input } = self;
(input, args.call_info.args) (input, args.call_info.args)
} }
pub fn split(self) -> (InputStream, EvaluatedCommandArgs) { pub fn split(self) -> (InputStream, EvaluatedCommandArgsWithoutInput) {
let EvaluatedWholeStreamCommandArgs { args, input } = self; let EvaluatedCommandArgs { args, input } = self;
(input, args) (input, args)
} }
@ -207,20 +132,28 @@ impl EvaluatedWholeStreamCommandArgs {
#[derive(Getters, new)] #[derive(Getters, new)]
#[get = "pub(crate)"] #[get = "pub(crate)"]
pub struct EvaluatedCommandArgs { pub struct EvaluatedCommandArgsWithoutInput {
pub host: Arc<parking_lot::Mutex<dyn Host>>, pub context: EvaluationContext,
pub ctrl_c: Arc<AtomicBool>,
pub configs: Arc<Mutex<ConfigHolder>>,
pub shell_manager: ShellManager,
pub call_info: CallInfo, pub call_info: CallInfo,
pub scope: Scope,
} }
impl EvaluatedCommandArgs { impl EvaluatedCommandArgsWithoutInput {
pub fn nth(&self, pos: usize) -> Option<&Value> { pub fn nth(&self, pos: usize) -> Option<&Value> {
self.call_info.args.nth(pos) self.call_info.args.nth(pos)
} }
pub fn scope(&self) -> Scope {
self.context.scope.clone()
}
pub fn configs(&self) -> Arc<Mutex<ConfigHolder>> {
self.context.configs.clone()
}
pub fn host(&self) -> Arc<parking_lot::Mutex<Box<dyn Host>>> {
self.context.host.clone()
}
/// Get the nth positional argument, error if not possible /// Get the nth positional argument, error if not possible
pub fn expect_nth(&self, pos: usize) -> Result<&Value, ShellError> { pub fn expect_nth(&self, pos: usize) -> Result<&Value, ShellError> {
self.call_info self.call_info

View File

@ -1,8 +1,8 @@
use crate::call_info::UnevaluatedCallInfo; use crate::call_info::UnevaluatedCallInfo;
use crate::command_args::RawCommandArgs;
use crate::evaluation_context::EvaluationContext; use crate::evaluation_context::EvaluationContext;
use crate::filesystem::filesystem_shell::{FilesystemShell, FilesystemShellMode}; use crate::filesystem::filesystem_shell::{FilesystemShell, FilesystemShellMode};
use crate::shell::value_shell::ValueShell; use crate::shell::value_shell::ValueShell;
use crate::CommandArgs;
use log::{log_enabled, trace}; use log::{log_enabled, trace};
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::hir::{ use nu_protocol::hir::{
@ -90,12 +90,8 @@ impl Iterator for InternalIterator {
let contents_tag = tagged_contents.tag.clone(); let contents_tag = tagged_contents.tag.clone();
let command_name = format!("from {}", extension); let command_name = format!("from {}", extension);
if let Some(converter) = self.context.scope.get_command(&command_name) { if let Some(converter) = self.context.scope.get_command(&command_name) {
let new_args = RawCommandArgs { let new_args = CommandArgs {
host: self.context.host.clone(), context: self.context.clone(),
ctrl_c: self.context.ctrl_c.clone(),
configs: self.context.configs.clone(),
current_errors: self.context.current_errors.clone(),
shell_manager: self.context.shell_manager.clone(),
call_info: UnevaluatedCallInfo { call_info: UnevaluatedCallInfo {
args: nu_protocol::hir::Call { args: nu_protocol::hir::Call {
head: Box::new(SpannedExpression { head: Box::new(SpannedExpression {
@ -111,9 +107,9 @@ impl Iterator for InternalIterator {
}, },
name_tag: tagged_contents.tag(), name_tag: tagged_contents.tag(),
}, },
scope: self.context.scope.clone(), input: InputStream::one(tagged_contents),
}; };
let result = converter.run(new_args.with_input(vec![tagged_contents])); let result = converter.run(new_args);
match result { match result {
Ok(mut result) => { Ok(mut result) => {

View File

@ -1,9 +1,10 @@
use crate::env::host::Host;
use crate::evaluate::scope::{Scope, ScopeFrame}; use crate::evaluate::scope::{Scope, ScopeFrame};
use crate::shell::shell_manager::ShellManager; use crate::shell::shell_manager::ShellManager;
use crate::whole_stream_command::Command; use crate::whole_stream_command::Command;
use crate::{call_info::UnevaluatedCallInfo, config_holder::ConfigHolder}; use crate::{call_info::UnevaluatedCallInfo, config_holder::ConfigHolder};
use crate::{command_args::CommandArgs, script}; use crate::{command_args::CommandArgs, script};
use crate::{env::basic_host::BasicHost, Host};
use indexmap::IndexMap;
use log::trace; use log::trace;
use nu_data::config::{self, Conf, NuConfig}; use nu_data::config::{self, Conf, NuConfig};
use nu_errors::ShellError; use nu_errors::ShellError;
@ -48,18 +49,27 @@ impl EvaluationContext {
} }
} }
pub fn from_args(args: &CommandArgs) -> EvaluationContext { pub fn basic() -> EvaluationContext {
let scope = Scope::new();
let mut host = BasicHost {};
let env_vars = host.vars().iter().cloned().collect::<IndexMap<_, _>>();
scope.add_env(env_vars);
EvaluationContext { EvaluationContext {
scope: args.scope.clone(), scope,
host: args.host.clone(), host: Arc::new(parking_lot::Mutex::new(Box::new(host))),
current_errors: args.current_errors.clone(), current_errors: Arc::new(Mutex::new(vec![])),
ctrl_c: args.ctrl_c.clone(), ctrl_c: Arc::new(AtomicBool::new(false)),
configs: args.configs.clone(), configs: Arc::new(Mutex::new(ConfigHolder::new())),
shell_manager: args.shell_manager.clone(), shell_manager: ShellManager::basic(),
windows_drives_previous_cwd: Arc::new(Mutex::new(std::collections::HashMap::new())), windows_drives_previous_cwd: Arc::new(Mutex::new(std::collections::HashMap::new())),
} }
} }
pub fn from_args(args: &CommandArgs) -> EvaluationContext {
args.context.clone()
}
pub fn error(&self, error: ShellError) { pub fn error(&self, error: ShellError) {
self.with_errors(|errors| errors.push(error)) self.with_errors(|errors| errors.push(error))
} }
@ -135,13 +145,8 @@ impl EvaluationContext {
fn command_args(&self, args: hir::Call, input: InputStream, name_tag: Tag) -> CommandArgs { fn command_args(&self, args: hir::Call, input: InputStream, name_tag: Tag) -> CommandArgs {
CommandArgs { CommandArgs {
host: self.host.clone(), context: self.clone(),
ctrl_c: self.ctrl_c.clone(),
configs: self.configs.clone(),
current_errors: self.current_errors.clone(),
shell_manager: self.shell_manager.clone(),
call_info: self.call_info(args, name_tag), call_info: self.call_info(args, name_tag),
scope: self.scope.clone(),
input, input,
} }
} }

View File

@ -4,14 +4,14 @@ use crate::filesystem::utils::FileStructure;
use crate::maybe_text_codec::{MaybeTextCodec, StringOrBinary}; use crate::maybe_text_codec::{MaybeTextCodec, StringOrBinary};
use crate::shell::shell_args::{CdArgs, CopyArgs, LsArgs, MkdirArgs, MvArgs, RemoveArgs}; use crate::shell::shell_args::{CdArgs, CopyArgs, LsArgs, MkdirArgs, MvArgs, RemoveArgs};
use crate::shell::Shell; use crate::shell::Shell;
use crate::{command_args::EvaluatedWholeStreamCommandArgs, BufCodecReader}; use crate::{command_args::EvaluatedCommandArgs, BufCodecReader};
use encoding_rs::Encoding; use encoding_rs::Encoding;
use nu_data::config::LocalConfigDiff; use nu_data::config::LocalConfigDiff;
use nu_protocol::{CommandAction, ConfigPath, TaggedDictBuilder, Value}; use nu_protocol::{CommandAction, ConfigPath, TaggedDictBuilder, Value};
use nu_source::{Span, Tag}; use nu_source::{Span, Tag};
use nu_stream::{ActionStream, Interruptible, OutputStream, ToActionStream}; use nu_stream::{ActionStream, Interruptible, OutputStream, ToActionStream};
use std::collections::VecDeque; use std::collections::VecDeque;
use std::io::{Error, ErrorKind}; use std::io::ErrorKind;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicBool;
use std::sync::Arc; use std::sync::Arc;
@ -57,17 +57,17 @@ impl FilesystemShell {
matches!(&self.mode, FilesystemShellMode::Cli) matches!(&self.mode, FilesystemShellMode::Cli)
} }
pub fn basic(mode: FilesystemShellMode) -> Result<FilesystemShell, Error> { pub fn basic(mode: FilesystemShellMode) -> FilesystemShell {
let path = match std::env::current_dir() { let path = match std::env::current_dir() {
Ok(path) => path, Ok(path) => path,
Err(_) => PathBuf::from("/"), Err(_) => PathBuf::from("/"),
}; };
Ok(FilesystemShell { FilesystemShell {
path: path.to_string_lossy().to_string(), path: path.to_string_lossy().to_string(),
last_path: path.to_string_lossy().to_string(), last_path: path.to_string_lossy().to_string(),
mode, mode,
}) }
} }
pub fn with_location( pub fn with_location(
@ -713,6 +713,7 @@ impl Shell for FilesystemShell {
let result; let result;
#[cfg(feature = "trash-support")] #[cfg(feature = "trash-support")]
{ {
use std::io::Error;
result = if _trash.item || (rm_always_trash && !_permanent.item) { result = if _trash.item || (rm_always_trash && !_permanent.item) {
trash::delete(&f).map_err(|e: trash::Error| { trash::delete(&f).map_err(|e: trash::Error| {
Error::new(ErrorKind::Other, format!("{:?}", e)) Error::new(ErrorKind::Other, format!("{:?}", e))
@ -765,7 +766,7 @@ impl Shell for FilesystemShell {
self.path.clone() self.path.clone()
} }
fn pwd(&self, args: EvaluatedWholeStreamCommandArgs) -> Result<ActionStream, ShellError> { fn pwd(&self, args: EvaluatedCommandArgs) -> Result<ActionStream, ShellError> {
let path = PathBuf::from(self.path()); let path = PathBuf::from(self.path());
let p = match dunce::canonicalize(path.as_path()) { let p = match dunce::canonicalize(path.as_path()) {
Ok(p) => p, Ok(p) => p,

View File

@ -1,5 +1,3 @@
pub mod basic_evaluation_context;
pub mod basic_shell_manager;
mod call_info; mod call_info;
mod command_args; mod command_args;
mod config_holder; mod config_holder;
@ -18,12 +16,9 @@ pub mod script;
pub mod shell; pub mod shell;
mod whole_stream_command; mod whole_stream_command;
pub use crate::basic_evaluation_context::basic_evaluation_context;
pub use crate::basic_shell_manager::basic_shell_manager;
pub use crate::call_info::UnevaluatedCallInfo; pub use crate::call_info::UnevaluatedCallInfo;
pub use crate::command_args::{ pub use crate::command_args::{
CommandArgs, EvaluatedCommandArgs, EvaluatedWholeStreamCommandArgs, RawCommandArgs, CommandArgs, EvaluatedCommandArgs, EvaluatedCommandArgsWithoutInput, RunnableContext,
RunnableContext, RunnableContextWithoutInput,
}; };
pub use crate::config_holder::ConfigHolder; pub use crate::config_holder::ConfigHolder;
pub use crate::documentation::{generate_docs, get_brief_help, get_documentation, get_full_help}; pub use crate::documentation::{generate_docs, get_brief_help, get_documentation, get_full_help};

View File

@ -1,6 +1,6 @@
use nu_stream::{ActionStream, OutputStream}; use nu_stream::{ActionStream, OutputStream};
use crate::command_args::EvaluatedWholeStreamCommandArgs; use crate::command_args::EvaluatedCommandArgs;
use crate::maybe_text_codec::StringOrBinary; use crate::maybe_text_codec::StringOrBinary;
pub use crate::shell::shell_args::{CdArgs, CopyArgs, LsArgs, MkdirArgs, MvArgs, RemoveArgs}; pub use crate::shell::shell_args::{CdArgs, CopyArgs, LsArgs, MkdirArgs, MvArgs, RemoveArgs};
use encoding_rs::Encoding; use encoding_rs::Encoding;
@ -33,7 +33,7 @@ pub trait Shell: std::fmt::Debug {
fn mv(&self, args: MvArgs, name: Tag, path: &str) -> Result<ActionStream, ShellError>; fn mv(&self, args: MvArgs, name: Tag, path: &str) -> Result<ActionStream, ShellError>;
fn rm(&self, args: RemoveArgs, name: Tag, path: &str) -> Result<ActionStream, ShellError>; fn rm(&self, args: RemoveArgs, name: Tag, path: &str) -> Result<ActionStream, ShellError>;
fn path(&self) -> String; fn path(&self) -> String;
fn pwd(&self, args: EvaluatedWholeStreamCommandArgs) -> Result<ActionStream, ShellError>; fn pwd(&self, args: EvaluatedCommandArgs) -> Result<ActionStream, ShellError>;
fn set_path(&mut self, path: String); fn set_path(&mut self, path: String);
fn open( fn open(
&self, &self,

View File

@ -1,5 +1,5 @@
use crate::shell::Shell; use crate::shell::Shell;
use crate::{command_args::EvaluatedWholeStreamCommandArgs, FilesystemShell}; use crate::{command_args::EvaluatedCommandArgs, FilesystemShell};
use crate::{filesystem::filesystem_shell::FilesystemShellMode, maybe_text_codec::StringOrBinary}; use crate::{filesystem::filesystem_shell::FilesystemShellMode, maybe_text_codec::StringOrBinary};
use nu_stream::{ActionStream, OutputStream}; use nu_stream::{ActionStream, OutputStream};
@ -19,6 +19,15 @@ pub struct ShellManager {
} }
impl ShellManager { impl ShellManager {
pub fn basic() -> ShellManager {
ShellManager {
current_shell: Arc::new(AtomicUsize::new(0)),
shells: Arc::new(Mutex::new(vec![Box::new(FilesystemShell::basic(
FilesystemShellMode::Cli,
))])),
}
}
pub fn enter_script_mode(&self) -> Result<(), std::io::Error> { pub fn enter_script_mode(&self) -> Result<(), std::io::Error> {
//New fs_shell starting from current path //New fs_shell starting from current path
let fs_shell = FilesystemShell::with_location(self.path(), FilesystemShellMode::Script)?; let fs_shell = FilesystemShell::with_location(self.path(), FilesystemShellMode::Script)?;
@ -69,7 +78,7 @@ impl ShellManager {
self.shells.lock()[self.current_shell()].path() self.shells.lock()[self.current_shell()].path()
} }
pub fn pwd(&self, args: EvaluatedWholeStreamCommandArgs) -> Result<ActionStream, ShellError> { pub fn pwd(&self, args: EvaluatedCommandArgs) -> Result<ActionStream, ShellError> {
let env = self.shells.lock(); let env = self.shells.lock();
env[self.current_shell()].pwd(args) env[self.current_shell()].pwd(args)

View File

@ -1,4 +1,4 @@
use crate::command_args::EvaluatedWholeStreamCommandArgs; use crate::command_args::EvaluatedCommandArgs;
use crate::maybe_text_codec::StringOrBinary; use crate::maybe_text_codec::StringOrBinary;
use crate::shell::shell_args::{CdArgs, CopyArgs, LsArgs, MkdirArgs, MvArgs, RemoveArgs}; use crate::shell::shell_args::{CdArgs, CopyArgs, LsArgs, MkdirArgs, MvArgs, RemoveArgs};
use crate::shell::Shell; use crate::shell::Shell;
@ -217,7 +217,7 @@ impl Shell for ValueShell {
self.path.clone() self.path.clone()
} }
fn pwd(&self, args: EvaluatedWholeStreamCommandArgs) -> Result<ActionStream, ShellError> { fn pwd(&self, args: EvaluatedCommandArgs) -> Result<ActionStream, ShellError> {
Ok(ActionStream::one( Ok(ActionStream::one(
UntaggedValue::string(self.path()).into_value(&args.call_info.name_tag), UntaggedValue::string(self.path()).into_value(&args.call_info.name_tag),
)) ))

View File

@ -237,7 +237,8 @@ impl Command {
if args.call_info.switch_present("help") { if args.call_info.switch_present("help") {
let cl = self.0.clone(); let cl = self.0.clone();
Ok(ActionStream::one(Ok(ReturnSuccess::Value( Ok(ActionStream::one(Ok(ReturnSuccess::Value(
UntaggedValue::string(get_full_help(&*cl, &args.scope)).into_value(Tag::unknown()), UntaggedValue::string(get_full_help(&*cl, &args.context.scope))
.into_value(Tag::unknown()),
)))) ))))
} else { } else {
self.0.run_with_actions(args) self.0.run_with_actions(args)
@ -248,7 +249,8 @@ impl Command {
if args.call_info.switch_present("help") { if args.call_info.switch_present("help") {
let cl = self.0.clone(); let cl = self.0.clone();
Ok(InputStream::one( Ok(InputStream::one(
UntaggedValue::string(get_full_help(&*cl, &args.scope)).into_value(Tag::unknown()), UntaggedValue::string(get_full_help(&*cl, &args.context.scope))
.into_value(Tag::unknown()),
)) ))
} else { } else {
self.0.run(args) self.0.run(args)