1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
use crate::command_registry::CommandRegistry;
use crate::commands::{command::CommandArgs, Command, UnevaluatedCallInfo};
use crate::env::host::Host;
use crate::shell::shell_manager::ShellManager;
use crate::stream::{InputStream, OutputStream};
use indexmap::IndexMap;
use nu_errors::ShellError;
use nu_protocol::{hir, Scope};
use nu_source::{Tag, Text};
use parking_lot::Mutex;
use std::error::Error;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;

#[derive(Clone)]
pub struct EvaluationContext {
    pub registry: CommandRegistry,
    pub host: Arc<parking_lot::Mutex<Box<dyn Host>>>,
    pub current_errors: Arc<Mutex<Vec<ShellError>>>,
    pub ctrl_c: Arc<AtomicBool>,
    pub raw_input: String,
    pub user_recently_used_autoenv_untrust: bool,
    pub(crate) shell_manager: ShellManager,

    /// Windows-specific: keep track of previous cwd on each drive
    pub windows_drives_previous_cwd: Arc<Mutex<std::collections::HashMap<String, String>>>,
}

impl EvaluationContext {
    pub(crate) fn registry(&self) -> &CommandRegistry {
        &self.registry
    }

    pub(crate) fn from_raw(
        raw_args: &CommandArgs,
        registry: &CommandRegistry,
    ) -> EvaluationContext {
        EvaluationContext {
            registry: registry.clone(),
            host: raw_args.host.clone(),
            current_errors: raw_args.current_errors.clone(),
            ctrl_c: raw_args.ctrl_c.clone(),
            shell_manager: raw_args.shell_manager.clone(),
            user_recently_used_autoenv_untrust: false,
            windows_drives_previous_cwd: Arc::new(Mutex::new(std::collections::HashMap::new())),
            raw_input: String::default(),
        }
    }

    pub(crate) fn from_args(args: &CommandArgs, registry: &CommandRegistry) -> EvaluationContext {
        EvaluationContext {
            registry: registry.clone(),
            host: args.host.clone(),
            current_errors: args.current_errors.clone(),
            ctrl_c: args.ctrl_c.clone(),
            shell_manager: args.shell_manager.clone(),
            user_recently_used_autoenv_untrust: false,
            windows_drives_previous_cwd: Arc::new(Mutex::new(std::collections::HashMap::new())),
            raw_input: String::default(),
        }
    }

    pub fn basic() -> Result<EvaluationContext, Box<dyn Error>> {
        let registry = CommandRegistry::new();

        Ok(EvaluationContext {
            registry,
            host: Arc::new(parking_lot::Mutex::new(Box::new(
                crate::env::host::BasicHost,
            ))),
            current_errors: Arc::new(Mutex::new(vec![])),
            ctrl_c: Arc::new(AtomicBool::new(false)),
            user_recently_used_autoenv_untrust: false,
            shell_manager: ShellManager::basic()?,
            windows_drives_previous_cwd: Arc::new(Mutex::new(std::collections::HashMap::new())),
            raw_input: String::default(),
        })
    }

    pub(crate) fn error(&mut self, error: ShellError) {
        self.with_errors(|errors| errors.push(error))
    }

    pub(crate) fn clear_errors(&mut self) {
        self.current_errors.lock().clear()
    }

    pub(crate) fn get_errors(&self) -> Vec<ShellError> {
        self.current_errors.lock().clone()
    }

    pub(crate) fn add_error(&self, err: ShellError) {
        self.current_errors.lock().push(err);
    }

    pub(crate) fn maybe_print_errors(&mut self, source: Text) -> bool {
        let errors = self.current_errors.clone();
        let mut errors = errors.lock();

        if errors.len() > 0 {
            let error = errors[0].clone();
            *errors = vec![];

            crate::cli::print_err(error, &source);
            true
        } else {
            false
        }
    }

    pub(crate) fn configure<T>(
        &mut self,
        config: &dyn nu_data::config::Conf,
        block: impl FnOnce(&dyn nu_data::config::Conf, &mut Self) -> T,
    ) {
        block(config, &mut *self);
    }

    pub(crate) fn with_host<T>(&mut self, block: impl FnOnce(&mut dyn Host) -> T) -> T {
        let mut host = self.host.lock();

        block(&mut *host)
    }

    pub(crate) fn with_errors<T>(&mut self, block: impl FnOnce(&mut Vec<ShellError>) -> T) -> T {
        let mut errors = self.current_errors.lock();

        block(&mut *errors)
    }

    pub fn add_commands(&mut self, commands: Vec<Command>) {
        for command in commands {
            self.registry.insert(command.name().to_string(), command);
        }
    }

    #[allow(unused)]
    pub(crate) fn get_command(&self, name: &str) -> Option<Command> {
        self.registry.get_command(name)
    }

    pub(crate) fn is_command_registered(&self, name: &str) -> bool {
        self.registry.has(name)
    }

    pub(crate) fn expect_command(&self, name: &str) -> Result<Command, ShellError> {
        self.registry.expect_command(name)
    }

    pub(crate) async fn run_command(
        &mut self,
        command: Command,
        name_tag: Tag,
        args: hir::Call,
        scope: &Scope,
        input: InputStream,
    ) -> Result<OutputStream, ShellError> {
        let command_args = self.command_args(args, input, name_tag, scope);
        command.run(command_args, self.registry()).await
    }

    fn call_info(&self, args: hir::Call, name_tag: Tag, scope: &Scope) -> UnevaluatedCallInfo {
        UnevaluatedCallInfo {
            args,
            name_tag,
            scope: scope.clone(),
        }
    }

    fn command_args(
        &self,
        args: hir::Call,
        input: InputStream,
        name_tag: Tag,
        scope: &Scope,
    ) -> CommandArgs {
        CommandArgs {
            host: self.host.clone(),
            ctrl_c: self.ctrl_c.clone(),
            current_errors: self.current_errors.clone(),
            shell_manager: self.shell_manager.clone(),
            call_info: self.call_info(args, name_tag, scope),
            input,
            raw_input: self.raw_input.clone(),
        }
    }

    pub fn get_env(&self) -> IndexMap<String, String> {
        let mut output = IndexMap::new();
        for (var, value) in self.host.lock().vars() {
            output.insert(var, value);
        }
        output
    }
}