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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
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;
use nu_protocol::{hir, ConfigPath};
use nu_source::{Span, Tag};
use nu_stream::InputStream;
use parking_lot::Mutex;
use std::sync::atomic::AtomicBool;
use std::{path::Path, sync::Arc};
#[derive(Clone, Default)]
pub struct EvaluationContext {
pub scope: Scope,
pub host: Arc<parking_lot::Mutex<Box<dyn Host>>>,
pub current_errors: Arc<Mutex<Vec<ShellError>>>,
pub ctrl_c: Arc<AtomicBool>,
pub configs: Arc<Mutex<ConfigHolder>>,
pub shell_manager: ShellManager,
pub windows_drives_previous_cwd: Arc<Mutex<std::collections::HashMap<String, String>>>,
}
impl EvaluationContext {
pub fn new(
scope: Scope,
host: Arc<parking_lot::Mutex<Box<dyn Host>>>,
current_errors: Arc<Mutex<Vec<ShellError>>>,
ctrl_c: Arc<AtomicBool>,
configs: Arc<Mutex<ConfigHolder>>,
shell_manager: ShellManager,
windows_drives_previous_cwd: Arc<Mutex<std::collections::HashMap<String, String>>>,
) -> Self {
Self {
scope,
host,
current_errors,
ctrl_c,
configs,
shell_manager,
windows_drives_previous_cwd,
}
}
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,
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))
}
pub fn clear_errors(&self) {
self.current_errors.lock().clear()
}
pub fn get_errors(&self) -> Vec<ShellError> {
self.current_errors.lock().clone()
}
pub 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 fn with_host<T>(&self, block: impl FnOnce(&mut dyn Host) -> T) -> T {
let mut host = self.host.lock();
block(&mut *host)
}
pub fn with_errors<T>(&self, block: impl FnOnce(&mut Vec<ShellError>) -> T) -> T {
let mut errors = self.current_errors.lock();
block(&mut *errors)
}
pub fn add_commands(&self, commands: Vec<Command>) {
for command in commands {
self.scope.add_command(command.name().to_string(), command);
}
}
pub fn sync_path_to_env(&self) {
let env_vars = self.scope.get_env_vars();
for (var, val) in env_vars {
if var == "PATH" || var == "Path" || var == "path" {
std::env::set_var(var, val);
break;
}
}
}
#[allow(unused)]
pub(crate) fn get_command(&self, name: &str) -> Option<Command> {
self.scope.get_command(name)
}
pub fn is_command_registered(&self, name: &str) -> bool {
self.scope.has_command(name)
}
pub(crate) fn run_command(
&self,
command: Command,
name_tag: Tag,
args: hir::Call,
input: InputStream,
) -> Result<InputStream, ShellError> {
let command_args = self.command_args(args, input, name_tag);
command.run(command_args)
}
fn call_info(&self, args: hir::Call, name_tag: Tag) -> UnevaluatedCallInfo {
UnevaluatedCallInfo { args, name_tag }
}
fn command_args(&self, args: hir::Call, input: InputStream, name_tag: Tag) -> CommandArgs {
CommandArgs {
context: self.clone(),
call_info: self.call_info(args, name_tag),
input,
}
}
pub fn load_config(&self, cfg_path: &ConfigPath) -> Result<(), ShellError> {
trace!("Loading cfg {:?}", cfg_path);
let cfg = NuConfig::load(Some(cfg_path.get_path().clone()))?;
let exit_scripts = cfg.exit_scripts()?;
let startup_scripts = cfg.startup_scripts()?;
let cfg_paths = cfg.path()?;
let joined_paths = cfg_paths
.map(|mut cfg_paths| {
let env_paths = if let Some(env_paths) = self.scope.get_env("PATH") {
Some(env_paths)
} else if let Some(env_paths) = self.scope.get_env("Path") {
Some(env_paths)
} else {
self.scope.get_env("path")
};
if let Some(env_paths) = env_paths {
let mut env_paths = std::env::split_paths(&env_paths).collect::<Vec<_>>();
env_paths.retain(|env_path| !cfg_paths.contains(env_path));
cfg_paths.extend(env_paths);
}
cfg_paths
})
.map(|paths| {
std::env::join_paths(paths)
.map(|s| s.to_string_lossy().to_string())
.map_err(|e| {
ShellError::labeled_error(
&format!("Error while joining paths from config: {:?}", e),
"Config path error",
Span::unknown(),
)
})
})
.transpose()?;
let tag = config::cfg_path_to_scope_tag(cfg_path.get_path());
self.scope.enter_scope_with_tag(tag);
self.scope.add_env(cfg.env_map());
if let Some(path) = joined_paths {
self.scope.add_env_var("PATH", path);
}
self.scope.set_exit_scripts(exit_scripts);
match cfg_path {
ConfigPath::Global(_) => self.configs.lock().set_global_cfg(cfg),
ConfigPath::Local(_) => {
self.configs.lock().add_local_cfg(cfg);
}
}
if !startup_scripts.is_empty() {
self.run_scripts(startup_scripts, cfg_path.get_path().parent());
}
Ok(())
}
pub fn reload_config(&self, cfg: &mut NuConfig) -> Result<(), ShellError> {
trace!("Reloading cfg {:?}", cfg.file_path);
cfg.reload();
let exit_scripts = cfg.exit_scripts()?;
let cfg_paths = cfg.path()?;
let joined_paths = cfg_paths
.map(|mut cfg_paths| {
let env_paths = if let Some(env_paths) = self.scope.get_env("PATH") {
Some(env_paths)
} else if let Some(env_paths) = self.scope.get_env("Path") {
Some(env_paths)
} else {
self.scope.get_env("path")
};
if let Some(env_paths) = env_paths {
let mut env_paths = std::env::split_paths(&env_paths).collect::<Vec<_>>();
env_paths.retain(|env_path| !cfg_paths.contains(env_path));
cfg_paths.extend(env_paths);
}
cfg_paths
})
.map(|paths| {
std::env::join_paths(paths)
.map(|s| s.to_string_lossy().to_string())
.map_err(|e| {
ShellError::labeled_error(
&format!("Error while joining paths from config: {:?}", e),
"Config path error",
Span::unknown(),
)
})
})
.transpose()?;
let tag = config::cfg_path_to_scope_tag(&cfg.file_path);
let mut frame = ScopeFrame::with_tag(tag.clone());
frame.env = cfg.env_map();
if let Some(path) = joined_paths {
frame.env.insert("PATH".to_string(), path);
}
frame.exitscripts = exit_scripts;
self.scope.update_frame_with_tag(frame, &tag)?;
Ok(())
}
pub fn unload_config(&self, cfg_path: &ConfigPath) {
trace!("UnLoading cfg {:?}", cfg_path);
let tag = config::cfg_path_to_scope_tag(cfg_path.get_path());
if let Some(scripts) = self.scope.get_exitscripts_of_frame_with_tag(&tag) {
self.run_scripts(scripts, cfg_path.get_path().parent());
}
self.configs.lock().remove_cfg(&cfg_path);
self.scope.exit_scope_with_tag(&tag);
}
pub fn run_scripts(&self, scripts: Vec<String>, dir: Option<&Path>) {
if let Some(dir) = dir {
for script in scripts {
match script::run_script_in_dir(script.clone(), dir, &self) {
Ok(_) => {}
Err(e) => {
let err = ShellError::untagged_runtime_error(format!(
"Err while executing exitscript. Err was\n{:?}",
e
));
let text = script.into();
self.host.lock().print_err(err, &text);
}
}
}
}
}
}