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
57 changed files with 543 additions and 678 deletions

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

View File

@ -1,8 +1,8 @@
use crate::call_info::UnevaluatedCallInfo;
use crate::command_args::RawCommandArgs;
use crate::evaluation_context::EvaluationContext;
use crate::filesystem::filesystem_shell::{FilesystemShell, FilesystemShellMode};
use crate::shell::value_shell::ValueShell;
use crate::CommandArgs;
use log::{log_enabled, trace};
use nu_errors::ShellError;
use nu_protocol::hir::{
@ -90,12 +90,8 @@ impl Iterator for InternalIterator {
let contents_tag = tagged_contents.tag.clone();
let command_name = format!("from {}", extension);
if let Some(converter) = self.context.scope.get_command(&command_name) {
let new_args = RawCommandArgs {
host: self.context.host.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(),
let new_args = CommandArgs {
context: self.context.clone(),
call_info: UnevaluatedCallInfo {
args: nu_protocol::hir::Call {
head: Box::new(SpannedExpression {
@ -111,9 +107,9 @@ impl Iterator for InternalIterator {
},
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 {
Ok(mut result) => {

View File

@ -1,9 +1,10 @@
use crate::env::host::Host;
use crate::evaluate::scope::{Scope, ScopeFrame};
use crate::shell::shell_manager::ShellManager;
use crate::whole_stream_command::Command;
use crate::{call_info::UnevaluatedCallInfo, config_holder::ConfigHolder};
use crate::{command_args::CommandArgs, script};
use crate::{env::basic_host::BasicHost, Host};
use indexmap::IndexMap;
use log::trace;
use nu_data::config::{self, Conf, NuConfig};
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 {
scope: args.scope.clone(),
host: args.host.clone(),
current_errors: args.current_errors.clone(),
ctrl_c: args.ctrl_c.clone(),
configs: args.configs.clone(),
shell_manager: args.shell_manager.clone(),
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: ShellManager::basic(),
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) {
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 {
CommandArgs {
host: self.host.clone(),
ctrl_c: self.ctrl_c.clone(),
configs: self.configs.clone(),
current_errors: self.current_errors.clone(),
shell_manager: self.shell_manager.clone(),
context: self.clone(),
call_info: self.call_info(args, name_tag),
scope: self.scope.clone(),
input,
}
}

View File

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

View File

@ -1,5 +1,3 @@
pub mod basic_evaluation_context;
pub mod basic_shell_manager;
mod call_info;
mod command_args;
mod config_holder;
@ -18,12 +16,9 @@ pub mod script;
pub mod shell;
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::command_args::{
CommandArgs, EvaluatedCommandArgs, EvaluatedWholeStreamCommandArgs, RawCommandArgs,
RunnableContext, RunnableContextWithoutInput,
CommandArgs, EvaluatedCommandArgs, EvaluatedCommandArgsWithoutInput, RunnableContext,
};
pub use crate::config_holder::ConfigHolder;
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 crate::command_args::EvaluatedWholeStreamCommandArgs;
use crate::command_args::EvaluatedCommandArgs;
use crate::maybe_text_codec::StringOrBinary;
pub use crate::shell::shell_args::{CdArgs, CopyArgs, LsArgs, MkdirArgs, MvArgs, RemoveArgs};
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 rm(&self, args: RemoveArgs, name: Tag, path: &str) -> Result<ActionStream, ShellError>;
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 open(
&self,

View File

@ -1,5 +1,5 @@
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 nu_stream::{ActionStream, OutputStream};
@ -19,6 +19,15 @@ pub struct 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> {
//New fs_shell starting from current path
let fs_shell = FilesystemShell::with_location(self.path(), FilesystemShellMode::Script)?;
@ -69,7 +78,7 @@ impl ShellManager {
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();
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::shell::shell_args::{CdArgs, CopyArgs, LsArgs, MkdirArgs, MvArgs, RemoveArgs};
use crate::shell::Shell;
@ -217,7 +217,7 @@ impl Shell for ValueShell {
self.path.clone()
}
fn pwd(&self, args: EvaluatedWholeStreamCommandArgs) -> Result<ActionStream, ShellError> {
fn pwd(&self, args: EvaluatedCommandArgs) -> Result<ActionStream, ShellError> {
Ok(ActionStream::one(
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") {
let cl = self.0.clone();
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 {
self.0.run_with_actions(args)
@ -248,7 +249,8 @@ impl Command {
if args.call_info.switch_present("help") {
let cl = self.0.clone();
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 {
self.0.run(args)