1use crate::{
2 BlockId, Category, Config, DeclId, FileId, GetSpan, Handlers, HistoryConfig, JobId, Module,
3 ModuleId, OverlayId, ShellError, SignalAction, Signals, Signature, Span, SpanId, Type, Value,
4 VarId, VirtualPathId,
5 ast::Block,
6 debugger::{Debugger, NoopDebugger},
7 engine::{
8 CachedFile, Command, CommandType, DEFAULT_OVERLAY_NAME, EnvVars, OverlayFrame, ScopeFrame,
9 Stack, StateDelta, Variable, Visibility,
10 description::{Doccomments, build_desc},
11 },
12 eval_const::create_nu_constant,
13 report_error::ReportLog,
14 shell_error::io::IoError,
15};
16use fancy_regex::Regex;
17use lru::LruCache;
18use nu_path::AbsolutePathBuf;
19use nu_utils::IgnoreCaseExt;
20use std::{
21 collections::HashMap,
22 num::NonZeroUsize,
23 path::PathBuf,
24 sync::{
25 Arc, Mutex, MutexGuard, PoisonError,
26 atomic::{AtomicBool, AtomicU32, Ordering},
27 mpsc::Sender,
28 mpsc::channel,
29 },
30};
31
32type PoisonDebuggerError<'a> = PoisonError<MutexGuard<'a, Box<dyn Debugger>>>;
33
34#[cfg(feature = "plugin")]
35use crate::{PluginRegistryFile, PluginRegistryItem, RegisteredPlugin};
36
37use super::{CurrentJob, Jobs, Mail, Mailbox, ThreadJob};
38
39#[derive(Clone, Debug)]
40pub enum VirtualPath {
41 File(FileId),
42 Dir(Vec<VirtualPathId>),
43}
44
45pub struct ReplState {
46 pub buffer: String,
47 pub cursor_pos: usize,
49 pub accept: bool,
51}
52
53pub struct IsDebugging(AtomicBool);
54
55impl IsDebugging {
56 pub fn new(val: bool) -> Self {
57 IsDebugging(AtomicBool::new(val))
58 }
59}
60
61impl Clone for IsDebugging {
62 fn clone(&self) -> Self {
63 IsDebugging(AtomicBool::new(self.0.load(Ordering::Relaxed)))
64 }
65}
66
67#[derive(Clone)]
85pub struct EngineState {
86 files: Vec<CachedFile>,
87 pub(super) virtual_paths: Vec<(String, VirtualPath)>,
88 vars: Vec<Variable>,
89 decls: Arc<Vec<Box<dyn Command + 'static>>>,
90 pub(super) blocks: Arc<Vec<Arc<Block>>>,
94 pub(super) modules: Arc<Vec<Arc<Module>>>,
95 pub spans: Vec<Span>,
96 doccomments: Doccomments,
97 pub scope: ScopeFrame,
98 signals: Signals,
99 pub signal_handlers: Option<Handlers>,
100 pub env_vars: Arc<EnvVars>,
101 pub previous_env_vars: Arc<HashMap<String, Value>>,
102 pub config: Arc<Config>,
103 pub pipeline_externals_state: Arc<(AtomicU32, AtomicU32)>,
104 pub repl_state: Arc<Mutex<ReplState>>,
105 pub table_decl_id: Option<DeclId>,
106 #[cfg(feature = "plugin")]
107 pub plugin_path: Option<PathBuf>,
108 #[cfg(feature = "plugin")]
109 plugins: Vec<Arc<dyn RegisteredPlugin>>,
110 config_path: HashMap<String, PathBuf>,
111 pub history_enabled: bool,
112 pub history_session_id: i64,
113 pub file: Option<PathBuf>,
115 pub regex_cache: Arc<Mutex<LruCache<String, Regex>>>,
116 pub is_interactive: bool,
117 pub is_login: bool,
118 startup_time: i64,
119 is_debugging: IsDebugging,
120 pub debugger: Arc<Mutex<Box<dyn Debugger>>>,
121 pub report_log: Arc<Mutex<ReportLog>>,
122
123 pub jobs: Arc<Mutex<Jobs>>,
124
125 pub current_job: CurrentJob,
127
128 pub root_job_sender: Sender<Mail>,
129
130 pub exit_warning_given: Arc<AtomicBool>,
137}
138
139const REGEX_CACHE_SIZE: usize = 100; pub const NU_VARIABLE_ID: VarId = VarId::new(0);
143pub const IN_VARIABLE_ID: VarId = VarId::new(1);
144pub const ENV_VARIABLE_ID: VarId = VarId::new(2);
145pub const UNKNOWN_SPAN_ID: SpanId = SpanId::new(0);
149
150impl EngineState {
151 pub fn new() -> Self {
152 let (send, recv) = channel::<Mail>();
153
154 Self {
155 files: vec![],
156 virtual_paths: vec![],
157 vars: vec![
158 Variable::new(Span::new(0, 0), Type::Any, false),
159 Variable::new(Span::new(0, 0), Type::Any, false),
160 Variable::new(Span::new(0, 0), Type::Any, false),
161 Variable::new(Span::new(0, 0), Type::Any, false),
162 Variable::new(Span::new(0, 0), Type::Any, false),
163 ],
164 decls: Arc::new(vec![]),
165 blocks: Arc::new(vec![]),
166 modules: Arc::new(vec![Arc::new(Module::new(
167 DEFAULT_OVERLAY_NAME.as_bytes().to_vec(),
168 ))]),
169 spans: vec![Span::unknown()],
170 doccomments: Doccomments::new(),
171 scope: ScopeFrame::with_empty_overlay(
173 DEFAULT_OVERLAY_NAME.as_bytes().to_vec(),
174 ModuleId::new(0),
175 false,
176 ),
177 signal_handlers: None,
178 signals: Signals::empty(),
179 env_vars: Arc::new(
180 [(DEFAULT_OVERLAY_NAME.to_string(), HashMap::new())]
181 .into_iter()
182 .collect(),
183 ),
184 previous_env_vars: Arc::new(HashMap::new()),
185 config: Arc::new(Config::default()),
186 pipeline_externals_state: Arc::new((AtomicU32::new(0), AtomicU32::new(0))),
187 repl_state: Arc::new(Mutex::new(ReplState {
188 buffer: "".to_string(),
189 cursor_pos: 0,
190 accept: false,
191 })),
192 table_decl_id: None,
193 #[cfg(feature = "plugin")]
194 plugin_path: None,
195 #[cfg(feature = "plugin")]
196 plugins: vec![],
197 config_path: HashMap::new(),
198 history_enabled: true,
199 history_session_id: 0,
200 file: None,
201 regex_cache: Arc::new(Mutex::new(LruCache::new(
202 NonZeroUsize::new(REGEX_CACHE_SIZE).expect("tried to create cache of size zero"),
203 ))),
204 is_interactive: false,
205 is_login: false,
206 startup_time: -1,
207 is_debugging: IsDebugging::new(false),
208 debugger: Arc::new(Mutex::new(Box::new(NoopDebugger))),
209 report_log: Arc::default(),
210 jobs: Arc::new(Mutex::new(Jobs::default())),
211 current_job: CurrentJob {
212 id: JobId::new(0),
213 background_thread_job: None,
214 mailbox: Arc::new(Mutex::new(Mailbox::new(recv))),
215 },
216 root_job_sender: send,
217 exit_warning_given: Arc::new(AtomicBool::new(false)),
218 }
219 }
220
221 pub fn signals(&self) -> &Signals {
222 &self.signals
223 }
224
225 pub fn reset_signals(&mut self) {
226 self.signals.reset();
227 if let Some(ref handlers) = self.signal_handlers {
228 handlers.run(SignalAction::Reset);
229 }
230 }
231
232 pub fn set_signals(&mut self, signals: Signals) {
233 self.signals = signals;
234 }
235
236 pub fn merge_delta(&mut self, mut delta: StateDelta) -> Result<(), ShellError> {
244 self.files.extend(delta.files);
246 self.virtual_paths.extend(delta.virtual_paths);
247 self.vars.extend(delta.vars);
248 self.spans.extend(delta.spans);
249 self.doccomments.merge_with(delta.doccomments);
250
251 if !delta.decls.is_empty() {
253 Arc::make_mut(&mut self.decls).extend(delta.decls);
254 }
255 if !delta.blocks.is_empty() {
256 Arc::make_mut(&mut self.blocks).extend(delta.blocks);
257 }
258 if !delta.modules.is_empty() {
259 Arc::make_mut(&mut self.modules).extend(delta.modules);
260 }
261
262 let first = delta.scope.remove(0);
263
264 for (delta_name, delta_overlay) in first.clone().overlays {
265 if let Some((_, existing_overlay)) = self
266 .scope
267 .overlays
268 .iter_mut()
269 .find(|(name, _)| name == &delta_name)
270 {
271 for item in delta_overlay.decls.into_iter() {
273 existing_overlay.decls.insert(item.0, item.1);
274 }
275 for item in delta_overlay.vars.into_iter() {
276 existing_overlay.vars.insert(item.0, item.1);
277 }
278 for item in delta_overlay.modules.into_iter() {
279 existing_overlay.modules.insert(item.0, item.1);
280 }
281
282 existing_overlay
283 .visibility
284 .merge_with(delta_overlay.visibility);
285 } else {
286 self.scope.overlays.push((delta_name, delta_overlay));
288 }
289 }
290
291 let mut activated_ids = self.translate_overlay_ids(&first);
292
293 let mut removed_ids = vec![];
294
295 for name in &first.removed_overlays {
296 if let Some(overlay_id) = self.find_overlay(name) {
297 removed_ids.push(overlay_id);
298 }
299 }
300
301 self.scope
303 .active_overlays
304 .retain(|id| !removed_ids.contains(id));
305
306 self.scope
308 .active_overlays
309 .retain(|id| !activated_ids.contains(id));
310 self.scope.active_overlays.append(&mut activated_ids);
311
312 #[cfg(feature = "plugin")]
313 if !delta.plugins.is_empty() {
314 for plugin in std::mem::take(&mut delta.plugins) {
315 if let Some(handlers) = &self.signal_handlers {
317 plugin.clone().configure_signal_handler(handlers)?;
318 }
319
320 if let Some(existing) = self
322 .plugins
323 .iter_mut()
324 .find(|p| p.identity().name() == plugin.identity().name())
325 {
326 existing.stop()?;
328 *existing = plugin;
329 } else {
330 self.plugins.push(plugin);
331 }
332 }
333 }
334
335 #[cfg(feature = "plugin")]
336 if !delta.plugin_registry_items.is_empty() {
337 if self.plugin_path.is_some() {
339 self.update_plugin_file(std::mem::take(&mut delta.plugin_registry_items))?;
340 }
341 }
342
343 Ok(())
344 }
345
346 pub fn merge_env(&mut self, stack: &mut Stack) -> Result<(), ShellError> {
348 for mut scope in stack.env_vars.drain(..) {
349 for (overlay_name, mut env) in Arc::make_mut(&mut scope).drain() {
350 if let Some(env_vars) = Arc::make_mut(&mut self.env_vars).get_mut(&overlay_name) {
351 env_vars.extend(env.drain());
353 } else {
354 Arc::make_mut(&mut self.env_vars).insert(overlay_name, env);
356 }
357 }
358 }
359
360 let cwd = self.cwd(Some(stack))?;
361 std::env::set_current_dir(cwd).map_err(|err| {
362 IoError::new_internal(err, "Could not set current dir", crate::location!())
363 })?;
364
365 if let Some(config) = stack.config.take() {
366 self.config = config;
368
369 #[cfg(feature = "plugin")]
371 self.update_plugin_gc_configs(&self.config.plugin_gc);
372 }
373
374 Ok(())
375 }
376
377 pub fn active_overlay_ids<'a, 'b>(
378 &'b self,
379 removed_overlays: &'a [Vec<u8>],
380 ) -> impl DoubleEndedIterator<Item = &'b OverlayId> + 'a
381 where
382 'b: 'a,
383 {
384 self.scope.active_overlays.iter().filter(|id| {
385 !removed_overlays
386 .iter()
387 .any(|name| name == self.get_overlay_name(**id))
388 })
389 }
390
391 pub fn active_overlays<'a, 'b>(
392 &'b self,
393 removed_overlays: &'a [Vec<u8>],
394 ) -> impl DoubleEndedIterator<Item = &'b OverlayFrame> + 'a
395 where
396 'b: 'a,
397 {
398 self.active_overlay_ids(removed_overlays)
399 .map(|id| self.get_overlay(*id))
400 }
401
402 pub fn active_overlay_names<'a, 'b>(
403 &'b self,
404 removed_overlays: &'a [Vec<u8>],
405 ) -> impl DoubleEndedIterator<Item = &'b [u8]> + 'a
406 where
407 'b: 'a,
408 {
409 self.active_overlay_ids(removed_overlays)
410 .map(|id| self.get_overlay_name(*id))
411 }
412
413 fn translate_overlay_ids(&self, other: &ScopeFrame) -> Vec<OverlayId> {
415 let other_names = other.active_overlays.iter().map(|other_id| {
416 &other
417 .overlays
418 .get(other_id.get())
419 .expect("internal error: missing overlay")
420 .0
421 });
422
423 other_names
424 .map(|other_name| {
425 self.find_overlay(other_name)
426 .expect("internal error: missing overlay")
427 })
428 .collect()
429 }
430
431 pub fn last_overlay_name(&self, removed_overlays: &[Vec<u8>]) -> &[u8] {
432 self.active_overlay_names(removed_overlays)
433 .last()
434 .expect("internal error: no active overlays")
435 }
436
437 pub fn last_overlay(&self, removed_overlays: &[Vec<u8>]) -> &OverlayFrame {
438 self.active_overlay_ids(removed_overlays)
439 .last()
440 .map(|id| self.get_overlay(*id))
441 .expect("internal error: no active overlays")
442 }
443
444 pub fn get_overlay_name(&self, overlay_id: OverlayId) -> &[u8] {
445 &self
446 .scope
447 .overlays
448 .get(overlay_id.get())
449 .expect("internal error: missing overlay")
450 .0
451 }
452
453 pub fn get_overlay(&self, overlay_id: OverlayId) -> &OverlayFrame {
454 &self
455 .scope
456 .overlays
457 .get(overlay_id.get())
458 .expect("internal error: missing overlay")
459 .1
460 }
461
462 pub fn render_env_vars(&self) -> HashMap<&str, &Value> {
463 let mut result: HashMap<&str, &Value> = HashMap::new();
464
465 for overlay_name in self.active_overlay_names(&[]) {
466 let name = String::from_utf8_lossy(overlay_name);
467 if let Some(env_vars) = self.env_vars.get(name.as_ref()) {
468 result.extend(env_vars.iter().map(|(k, v)| (k.as_str(), v)));
469 }
470 }
471
472 result
473 }
474
475 pub fn add_env_var(&mut self, name: String, val: Value) {
476 let overlay_name = String::from_utf8_lossy(self.last_overlay_name(&[])).to_string();
477
478 if let Some(env_vars) = Arc::make_mut(&mut self.env_vars).get_mut(&overlay_name) {
479 env_vars.insert(name, val);
480 } else {
481 Arc::make_mut(&mut self.env_vars)
482 .insert(overlay_name, [(name, val)].into_iter().collect());
483 }
484 }
485
486 pub fn get_env_var(&self, name: &str) -> Option<&Value> {
487 for overlay_id in self.scope.active_overlays.iter().rev() {
488 let overlay_name = String::from_utf8_lossy(self.get_overlay_name(*overlay_id));
489 if let Some(env_vars) = self.env_vars.get(overlay_name.as_ref()) {
490 if let Some(val) = env_vars.get(name) {
491 return Some(val);
492 }
493 }
494 }
495
496 None
497 }
498
499 pub fn get_env_var_insensitive(&self, name: &str) -> Option<(&String, &Value)> {
504 for overlay_id in self.scope.active_overlays.iter().rev() {
505 let overlay_name = String::from_utf8_lossy(self.get_overlay_name(*overlay_id));
506 if let Some(env_vars) = self.env_vars.get(overlay_name.as_ref()) {
507 if let Some(v) = env_vars.iter().find(|(k, _)| k.eq_ignore_case(name)) {
508 return Some((v.0, v.1));
509 }
510 }
511 }
512
513 None
514 }
515
516 #[cfg(feature = "plugin")]
517 pub fn plugins(&self) -> &[Arc<dyn RegisteredPlugin>] {
518 &self.plugins
519 }
520
521 #[cfg(feature = "plugin")]
522 fn update_plugin_file(&self, updated_items: Vec<PluginRegistryItem>) -> Result<(), ShellError> {
523 use std::fs::File;
525
526 let plugin_path = self
527 .plugin_path
528 .as_ref()
529 .ok_or_else(|| ShellError::GenericError {
530 error: "Plugin file path not set".into(),
531 msg: "".into(),
532 span: None,
533 help: Some("you may be running nu with --no-config-file".into()),
534 inner: vec![],
535 })?;
536
537 let mut contents = match File::open(plugin_path.as_path()) {
539 Ok(mut plugin_file) => PluginRegistryFile::read_from(&mut plugin_file, None),
540 Err(err) => {
541 if err.kind() == std::io::ErrorKind::NotFound {
542 Ok(PluginRegistryFile::default())
543 } else {
544 Err(ShellError::Io(IoError::new_internal_with_path(
545 err,
546 "Failed to open plugin file",
547 crate::location!(),
548 PathBuf::from(plugin_path),
549 )))
550 }
551 }
552 }?;
553
554 for item in updated_items {
556 contents.upsert_plugin(item);
557 }
558
559 let plugin_file = File::create(plugin_path.as_path()).map_err(|err| {
561 IoError::new_internal_with_path(
562 err,
563 "Failed to write plugin file",
564 crate::location!(),
565 PathBuf::from(plugin_path),
566 )
567 })?;
568
569 contents.write_to(plugin_file, None)
570 }
571
572 #[cfg(feature = "plugin")]
574 fn update_plugin_gc_configs(&self, plugin_gc: &crate::PluginGcConfigs) {
575 for plugin in &self.plugins {
576 plugin.set_gc_config(plugin_gc.get(plugin.identity().name()));
577 }
578 }
579
580 pub fn num_files(&self) -> usize {
581 self.files.len()
582 }
583
584 pub fn num_virtual_paths(&self) -> usize {
585 self.virtual_paths.len()
586 }
587
588 pub fn num_vars(&self) -> usize {
589 self.vars.len()
590 }
591
592 pub fn num_decls(&self) -> usize {
593 self.decls.len()
594 }
595
596 pub fn num_blocks(&self) -> usize {
597 self.blocks.len()
598 }
599
600 pub fn num_modules(&self) -> usize {
601 self.modules.len()
602 }
603
604 pub fn num_spans(&self) -> usize {
605 self.spans.len()
606 }
607 pub fn print_vars(&self) {
608 for var in self.vars.iter().enumerate() {
609 println!("var{}: {:?}", var.0, var.1);
610 }
611 }
612
613 pub fn print_decls(&self) {
614 for decl in self.decls.iter().enumerate() {
615 println!("decl{}: {:?}", decl.0, decl.1.signature());
616 }
617 }
618
619 pub fn print_blocks(&self) {
620 for block in self.blocks.iter().enumerate() {
621 println!("block{}: {:?}", block.0, block.1);
622 }
623 }
624
625 pub fn print_contents(&self) {
626 for cached_file in self.files.iter() {
627 let string = String::from_utf8_lossy(&cached_file.content);
628 println!("{string}");
629 }
630 }
631
632 pub fn find_decl(&self, name: &[u8], removed_overlays: &[Vec<u8>]) -> Option<DeclId> {
636 let mut visibility: Visibility = Visibility::new();
637
638 for overlay_frame in self.active_overlays(removed_overlays).rev() {
639 visibility.append(&overlay_frame.visibility);
640
641 if let Some(decl_id) = overlay_frame.get_decl(name) {
642 if visibility.is_decl_id_visible(&decl_id) {
643 return Some(decl_id);
644 }
645 }
646 }
647
648 None
649 }
650
651 pub fn find_decl_name(&self, decl_id: DeclId, removed_overlays: &[Vec<u8>]) -> Option<&[u8]> {
655 let mut visibility: Visibility = Visibility::new();
656
657 for overlay_frame in self.active_overlays(removed_overlays).rev() {
658 visibility.append(&overlay_frame.visibility);
659
660 if visibility.is_decl_id_visible(&decl_id) {
661 for (name, id) in overlay_frame.decls.iter() {
662 if id == &decl_id {
663 return Some(name);
664 }
665 }
666 }
667 }
668
669 None
670 }
671
672 pub fn find_overlay(&self, name: &[u8]) -> Option<OverlayId> {
676 self.scope.find_overlay(name)
677 }
678
679 pub fn find_active_overlay(&self, name: &[u8]) -> Option<OverlayId> {
683 self.scope.find_active_overlay(name)
684 }
685
686 pub fn find_module(&self, name: &[u8], removed_overlays: &[Vec<u8>]) -> Option<ModuleId> {
690 for overlay_frame in self.active_overlays(removed_overlays).rev() {
691 if let Some(module_id) = overlay_frame.modules.get(name) {
692 return Some(*module_id);
693 }
694 }
695
696 None
697 }
698
699 pub fn get_module_comments(&self, module_id: ModuleId) -> Option<&[Span]> {
700 self.doccomments.get_module_comments(module_id)
701 }
702
703 #[cfg(feature = "plugin")]
704 pub fn plugin_decls(&self) -> impl Iterator<Item = &Box<dyn Command + 'static>> {
705 let mut unique_plugin_decls = HashMap::new();
706
707 for decl in self.decls.iter().filter(|d| d.is_plugin()) {
709 unique_plugin_decls.insert(decl.name(), decl);
710 }
711
712 let mut plugin_decls: Vec<(&str, &Box<dyn Command>)> =
713 unique_plugin_decls.into_iter().collect();
714
715 plugin_decls.sort_by(|a, b| a.0.cmp(b.0));
717 plugin_decls.into_iter().map(|(_, decl)| decl)
718 }
719
720 pub fn which_module_has_decl(
721 &self,
722 decl_name: &[u8],
723 removed_overlays: &[Vec<u8>],
724 ) -> Option<&[u8]> {
725 for overlay_frame in self.active_overlays(removed_overlays).rev() {
726 for (module_name, module_id) in overlay_frame.modules.iter() {
727 let module = self.get_module(*module_id);
728 if module.has_decl(decl_name) {
729 return Some(module_name);
730 }
731 }
732 }
733
734 None
735 }
736
737 pub fn find_commands_by_predicate(
738 &self,
739 mut predicate: impl FnMut(&[u8]) -> bool,
740 ignore_deprecated: bool,
741 ) -> Vec<(DeclId, Vec<u8>, Option<String>, CommandType)> {
742 let mut output = vec![];
743
744 for overlay_frame in self.active_overlays(&[]).rev() {
745 for (name, decl_id) in &overlay_frame.decls {
746 if overlay_frame.visibility.is_decl_id_visible(decl_id) && predicate(name) {
747 let command = self.get_decl(*decl_id);
748 if ignore_deprecated && command.signature().category == Category::Removed {
749 continue;
750 }
751 output.push((
752 *decl_id,
753 name.clone(),
754 Some(command.description().to_string()),
755 command.command_type(),
756 ));
757 }
758 }
759 }
760
761 output
762 }
763
764 pub fn get_span_contents(&self, span: Span) -> &[u8] {
765 for file in &self.files {
766 if file.covered_span.contains_span(span) {
767 return &file.content
768 [(span.start - file.covered_span.start)..(span.end - file.covered_span.start)];
769 }
770 }
771 &[0u8; 0]
772 }
773
774 pub fn span_match_prefix(&self, span: Span, prefix: &[u8]) -> Option<(Span, Span)> {
777 let contents = self.get_span_contents(span);
778
779 if contents.starts_with(prefix) {
780 span.split_at(prefix.len())
781 } else {
782 None
783 }
784 }
785
786 pub fn span_match_postfix(&self, span: Span, prefix: &[u8]) -> Option<(Span, Span)> {
789 let contents = self.get_span_contents(span);
790
791 if contents.ends_with(prefix) {
792 span.split_at(span.len() - prefix.len())
793 } else {
794 None
795 }
796 }
797
798 pub fn get_config(&self) -> &Arc<Config> {
803 &self.config
804 }
805
806 pub fn set_config(&mut self, conf: impl Into<Arc<Config>>) {
807 let conf = conf.into();
808
809 #[cfg(feature = "plugin")]
810 if conf.plugin_gc != self.config.plugin_gc {
811 self.update_plugin_gc_configs(&conf.plugin_gc);
813 }
814
815 self.config = conf;
816 }
817
818 pub fn get_plugin_config(&self, plugin: &str) -> Option<&Value> {
823 self.config.plugins.get(plugin)
824 }
825
826 pub fn history_config(&self) -> Option<HistoryConfig> {
828 self.history_enabled.then(|| self.config.history)
829 }
830
831 pub fn get_var(&self, var_id: VarId) -> &Variable {
832 self.vars
833 .get(var_id.get())
834 .expect("internal error: missing variable")
835 }
836
837 pub fn get_constant(&self, var_id: VarId) -> Option<&Value> {
838 let var = self.get_var(var_id);
839 var.const_val.as_ref()
840 }
841
842 pub fn generate_nu_constant(&mut self) {
843 self.vars[NU_VARIABLE_ID.get()].const_val = Some(create_nu_constant(self, Span::unknown()));
844 }
845
846 pub fn get_decl(&self, decl_id: DeclId) -> &dyn Command {
847 self.decls
848 .get(decl_id.get())
849 .expect("internal error: missing declaration")
850 .as_ref()
851 }
852
853 pub fn get_decls_sorted(&self, include_hidden: bool) -> Vec<(Vec<u8>, DeclId)> {
855 let mut decls_map = HashMap::new();
856
857 for overlay_frame in self.active_overlays(&[]) {
858 let new_decls = if include_hidden {
859 overlay_frame.decls.clone()
860 } else {
861 overlay_frame
862 .decls
863 .clone()
864 .into_iter()
865 .filter(|(_, id)| overlay_frame.visibility.is_decl_id_visible(id))
866 .collect()
867 };
868
869 decls_map.extend(new_decls);
870 }
871
872 let mut decls: Vec<(Vec<u8>, DeclId)> = decls_map.into_iter().collect();
873
874 decls.sort_by(|a, b| a.0.cmp(&b.0));
875 decls
876 }
877
878 pub fn get_signature(&self, decl: &dyn Command) -> Signature {
879 if let Some(block_id) = decl.block_id() {
880 *self.blocks[block_id.get()].signature.clone()
881 } else {
882 decl.signature()
883 }
884 }
885
886 pub fn get_signatures_and_declids(&self, include_hidden: bool) -> Vec<(Signature, DeclId)> {
888 self.get_decls_sorted(include_hidden)
889 .into_iter()
890 .map(|(_, id)| {
891 let decl = self.get_decl(id);
892
893 (self.get_signature(decl).update_from_command(decl), id)
894 })
895 .collect()
896 }
897
898 pub fn get_block(&self, block_id: BlockId) -> &Arc<Block> {
899 self.blocks
900 .get(block_id.get())
901 .expect("internal error: missing block")
902 }
903
904 pub fn try_get_block(&self, block_id: BlockId) -> Option<&Arc<Block>> {
910 self.blocks.get(block_id.get())
911 }
912
913 pub fn get_module(&self, module_id: ModuleId) -> &Module {
914 self.modules
915 .get(module_id.get())
916 .expect("internal error: missing module")
917 }
918
919 pub fn get_virtual_path(&self, virtual_path_id: VirtualPathId) -> &(String, VirtualPath) {
920 self.virtual_paths
921 .get(virtual_path_id.get())
922 .expect("internal error: missing virtual path")
923 }
924
925 pub fn next_span_start(&self) -> usize {
926 if let Some(cached_file) = self.files.last() {
927 cached_file.covered_span.end
928 } else {
929 0
930 }
931 }
932
933 pub fn files(
934 &self,
935 ) -> impl DoubleEndedIterator<Item = &CachedFile> + ExactSizeIterator<Item = &CachedFile> {
936 self.files.iter()
937 }
938
939 pub fn add_file(&mut self, filename: Arc<str>, content: Arc<[u8]>) -> FileId {
940 let next_span_start = self.next_span_start();
941 let next_span_end = next_span_start + content.len();
942
943 let covered_span = Span::new(next_span_start, next_span_end);
944
945 self.files.push(CachedFile {
946 name: filename,
947 content,
948 covered_span,
949 });
950
951 FileId::new(self.num_files() - 1)
952 }
953
954 pub fn set_config_path(&mut self, key: &str, val: PathBuf) {
955 self.config_path.insert(key.to_string(), val);
956 }
957
958 pub fn get_config_path(&self, key: &str) -> Option<&PathBuf> {
959 self.config_path.get(key)
960 }
961
962 pub fn build_desc(&self, spans: &[Span]) -> (String, String) {
963 let comment_lines: Vec<&[u8]> = spans
964 .iter()
965 .map(|span| self.get_span_contents(*span))
966 .collect();
967 build_desc(&comment_lines)
968 }
969
970 pub fn build_module_desc(&self, module_id: ModuleId) -> Option<(String, String)> {
971 self.get_module_comments(module_id)
972 .map(|comment_spans| self.build_desc(comment_spans))
973 }
974
975 #[deprecated(since = "0.92.3", note = "please use `EngineState::cwd()` instead")]
979 pub fn current_work_dir(&self) -> String {
980 self.cwd(None)
981 .map(|path| path.to_string_lossy().to_string())
982 .unwrap_or_default()
983 }
984
985 pub fn cwd(&self, stack: Option<&Stack>) -> Result<AbsolutePathBuf, ShellError> {
992 fn error(msg: &str, cwd: impl AsRef<nu_path::Path>) -> ShellError {
994 ShellError::GenericError {
995 error: msg.into(),
996 msg: format!("$env.PWD = {}", cwd.as_ref().display()),
997 span: None,
998 help: Some("Use `cd` to reset $env.PWD into a good state".into()),
999 inner: vec![],
1000 }
1001 }
1002
1003 let pwd = if let Some(stack) = stack {
1005 stack.get_env_var(self, "PWD")
1006 } else {
1007 self.get_env_var("PWD")
1008 };
1009
1010 let pwd = pwd.ok_or_else(|| error("$env.PWD not found", ""))?;
1011
1012 if let Ok(pwd) = pwd.as_str() {
1013 let path = AbsolutePathBuf::try_from(pwd)
1014 .map_err(|_| error("$env.PWD is not an absolute path", pwd))?;
1015
1016 if path.parent().is_some() && nu_path::has_trailing_slash(path.as_ref()) {
1019 Err(error("$env.PWD contains trailing slashes", &path))
1020 } else if !path.exists() {
1021 Err(error("$env.PWD points to a non-existent directory", &path))
1022 } else if !path.is_dir() {
1023 Err(error("$env.PWD points to a non-directory", &path))
1024 } else {
1025 Ok(path)
1026 }
1027 } else {
1028 Err(error("$env.PWD is not a string", format!("{pwd:?}")))
1029 }
1030 }
1031
1032 pub fn cwd_as_string(&self, stack: Option<&Stack>) -> Result<String, ShellError> {
1034 let cwd = self.cwd(stack)?;
1035 cwd.into_os_string()
1036 .into_string()
1037 .map_err(|err| ShellError::NonUtf8Custom {
1038 msg: format!("The current working directory is not a valid utf-8 string: {err:?}"),
1039 span: Span::unknown(),
1040 })
1041 }
1042
1043 pub fn get_file_contents(&self) -> &[CachedFile] {
1045 &self.files
1046 }
1047
1048 pub fn get_startup_time(&self) -> i64 {
1049 self.startup_time
1050 }
1051
1052 pub fn set_startup_time(&mut self, startup_time: i64) {
1053 self.startup_time = startup_time;
1054 }
1055
1056 pub fn activate_debugger(
1057 &self,
1058 debugger: Box<dyn Debugger>,
1059 ) -> Result<(), PoisonDebuggerError> {
1060 let mut locked_debugger = self.debugger.lock()?;
1061 *locked_debugger = debugger;
1062 locked_debugger.activate();
1063 self.is_debugging.0.store(true, Ordering::Relaxed);
1064 Ok(())
1065 }
1066
1067 pub fn deactivate_debugger(&self) -> Result<Box<dyn Debugger>, PoisonDebuggerError> {
1068 let mut locked_debugger = self.debugger.lock()?;
1069 locked_debugger.deactivate();
1070 let ret = std::mem::replace(&mut *locked_debugger, Box::new(NoopDebugger));
1071 self.is_debugging.0.store(false, Ordering::Relaxed);
1072 Ok(ret)
1073 }
1074
1075 pub fn is_debugging(&self) -> bool {
1076 self.is_debugging.0.load(Ordering::Relaxed)
1077 }
1078
1079 pub fn recover_from_panic(&mut self) {
1080 if Mutex::is_poisoned(&self.repl_state) {
1081 self.repl_state = Arc::new(Mutex::new(ReplState {
1082 buffer: "".to_string(),
1083 cursor_pos: 0,
1084 accept: false,
1085 }));
1086 }
1087 if Mutex::is_poisoned(&self.jobs) {
1088 self.jobs = Arc::new(Mutex::new(Jobs::default()));
1089 }
1090 if Mutex::is_poisoned(&self.regex_cache) {
1091 self.regex_cache = Arc::new(Mutex::new(LruCache::new(
1092 NonZeroUsize::new(REGEX_CACHE_SIZE).expect("tried to create cache of size zero"),
1093 )));
1094 }
1095 }
1096
1097 pub fn add_span(&mut self, span: Span) -> SpanId {
1099 self.spans.push(span);
1100 SpanId::new(self.num_spans() - 1)
1101 }
1102
1103 pub fn find_span_id(&self, span: Span) -> Option<SpanId> {
1105 self.spans
1106 .iter()
1107 .position(|sp| sp == &span)
1108 .map(SpanId::new)
1109 }
1110
1111 pub fn is_background_job(&self) -> bool {
1113 self.current_job.background_thread_job.is_some()
1114 }
1115
1116 pub fn current_thread_job(&self) -> Option<&ThreadJob> {
1118 self.current_job.background_thread_job.as_ref()
1119 }
1120}
1121
1122impl GetSpan for &EngineState {
1123 fn get_span(&self, span_id: SpanId) -> Span {
1125 *self
1126 .spans
1127 .get(span_id.get())
1128 .expect("internal error: missing span")
1129 }
1130}
1131
1132impl Default for EngineState {
1133 fn default() -> Self {
1134 Self::new()
1135 }
1136}
1137
1138#[cfg(test)]
1139mod engine_state_tests {
1140 use crate::engine::StateWorkingSet;
1141 use std::str::{Utf8Error, from_utf8};
1142
1143 use super::*;
1144
1145 #[test]
1146 fn add_file_gives_id() {
1147 let engine_state = EngineState::new();
1148 let mut engine_state = StateWorkingSet::new(&engine_state);
1149 let id = engine_state.add_file("test.nu".into(), &[]);
1150
1151 assert_eq!(id, FileId::new(0));
1152 }
1153
1154 #[test]
1155 fn add_file_gives_id_including_parent() {
1156 let mut engine_state = EngineState::new();
1157 let parent_id = engine_state.add_file("test.nu".into(), Arc::new([]));
1158
1159 let mut working_set = StateWorkingSet::new(&engine_state);
1160 let working_set_id = working_set.add_file("child.nu".into(), &[]);
1161
1162 assert_eq!(parent_id, FileId::new(0));
1163 assert_eq!(working_set_id, FileId::new(1));
1164 }
1165
1166 #[test]
1167 fn merge_states() -> Result<(), ShellError> {
1168 let mut engine_state = EngineState::new();
1169 engine_state.add_file("test.nu".into(), Arc::new([]));
1170
1171 let delta = {
1172 let mut working_set = StateWorkingSet::new(&engine_state);
1173 let _ = working_set.add_file("child.nu".into(), &[]);
1174 working_set.render()
1175 };
1176
1177 engine_state.merge_delta(delta)?;
1178
1179 assert_eq!(engine_state.num_files(), 2);
1180 assert_eq!(&*engine_state.files[0].name, "test.nu");
1181 assert_eq!(&*engine_state.files[1].name, "child.nu");
1182
1183 Ok(())
1184 }
1185
1186 #[test]
1187 fn list_variables() -> Result<(), Utf8Error> {
1188 let varname = "something";
1189 let varname_with_sigil = "$".to_owned() + varname;
1190 let engine_state = EngineState::new();
1191 let mut working_set = StateWorkingSet::new(&engine_state);
1192 working_set.add_variable(
1193 varname.as_bytes().into(),
1194 Span { start: 0, end: 1 },
1195 Type::Int,
1196 false,
1197 );
1198 let variables = working_set
1199 .list_variables()
1200 .into_iter()
1201 .map(from_utf8)
1202 .collect::<Result<Vec<&str>, Utf8Error>>()?;
1203 assert_eq!(variables, vec![varname_with_sigil]);
1204 Ok(())
1205 }
1206
1207 #[test]
1208 fn get_plugin_config() {
1209 let mut engine_state = EngineState::new();
1210
1211 assert!(
1212 engine_state.get_plugin_config("example").is_none(),
1213 "Unexpected plugin configuration"
1214 );
1215
1216 let mut plugins = HashMap::new();
1217 plugins.insert("example".into(), Value::string("value", Span::test_data()));
1218
1219 let mut config = Config::clone(engine_state.get_config());
1220 config.plugins = plugins;
1221
1222 engine_state.set_config(config);
1223
1224 assert!(
1225 engine_state.get_plugin_config("example").is_some(),
1226 "Plugin configuration not found"
1227 );
1228 }
1229}
1230
1231#[cfg(test)]
1232mod test_cwd {
1233 use crate::{
1248 Value,
1249 engine::{EngineState, Stack},
1250 };
1251 use nu_path::{AbsolutePath, Path, assert_path_eq};
1252 use tempfile::{NamedTempFile, TempDir};
1253
1254 #[cfg(any(unix, windows))]
1256 fn symlink(
1257 original: impl AsRef<AbsolutePath>,
1258 link: impl AsRef<AbsolutePath>,
1259 ) -> std::io::Result<()> {
1260 let original = original.as_ref();
1261 let link = link.as_ref();
1262
1263 #[cfg(unix)]
1264 {
1265 std::os::unix::fs::symlink(original, link)
1266 }
1267 #[cfg(windows)]
1268 {
1269 if original.is_dir() {
1270 std::os::windows::fs::symlink_dir(original, link)
1271 } else {
1272 std::os::windows::fs::symlink_file(original, link)
1273 }
1274 }
1275 }
1276
1277 fn engine_state_with_pwd(path: impl AsRef<Path>) -> EngineState {
1279 let mut engine_state = EngineState::new();
1280 engine_state.add_env_var(
1281 "PWD".into(),
1282 Value::test_string(path.as_ref().to_str().unwrap()),
1283 );
1284 engine_state
1285 }
1286
1287 fn stack_with_pwd(path: impl AsRef<Path>) -> Stack {
1289 let mut stack = Stack::new();
1290 stack.add_env_var(
1291 "PWD".into(),
1292 Value::test_string(path.as_ref().to_str().unwrap()),
1293 );
1294 stack
1295 }
1296
1297 #[test]
1298 fn pwd_not_set() {
1299 let engine_state = EngineState::new();
1300 engine_state.cwd(None).unwrap_err();
1301 }
1302
1303 #[test]
1304 fn pwd_is_empty_string() {
1305 let engine_state = engine_state_with_pwd("");
1306 engine_state.cwd(None).unwrap_err();
1307 }
1308
1309 #[test]
1310 fn pwd_is_non_string_value() {
1311 let mut engine_state = EngineState::new();
1312 engine_state.add_env_var("PWD".into(), Value::test_glob("*"));
1313 engine_state.cwd(None).unwrap_err();
1314 }
1315
1316 #[test]
1317 fn pwd_is_relative_path() {
1318 let engine_state = engine_state_with_pwd("./foo");
1319
1320 engine_state.cwd(None).unwrap_err();
1321 }
1322
1323 #[test]
1324 fn pwd_has_trailing_slash() {
1325 let dir = TempDir::new().unwrap();
1326 let engine_state = engine_state_with_pwd(dir.path().join(""));
1327
1328 engine_state.cwd(None).unwrap_err();
1329 }
1330
1331 #[test]
1332 fn pwd_points_to_root() {
1333 #[cfg(windows)]
1334 let root = Path::new(r"C:\");
1335 #[cfg(not(windows))]
1336 let root = Path::new("/");
1337
1338 let engine_state = engine_state_with_pwd(root);
1339 let cwd = engine_state.cwd(None).unwrap();
1340 assert_path_eq!(cwd, root);
1341 }
1342
1343 #[test]
1344 fn pwd_points_to_normal_file() {
1345 let file = NamedTempFile::new().unwrap();
1346 let engine_state = engine_state_with_pwd(file.path());
1347
1348 engine_state.cwd(None).unwrap_err();
1349 }
1350
1351 #[test]
1352 fn pwd_points_to_normal_directory() {
1353 let dir = TempDir::new().unwrap();
1354 let engine_state = engine_state_with_pwd(dir.path());
1355
1356 let cwd = engine_state.cwd(None).unwrap();
1357 assert_path_eq!(cwd, dir.path());
1358 }
1359
1360 #[test]
1361 fn pwd_points_to_symlink_to_file() {
1362 let file = NamedTempFile::new().unwrap();
1363 let temp_file = AbsolutePath::try_new(file.path()).unwrap();
1364 let dir = TempDir::new().unwrap();
1365 let temp = AbsolutePath::try_new(dir.path()).unwrap();
1366
1367 let link = temp.join("link");
1368 symlink(temp_file, &link).unwrap();
1369 let engine_state = engine_state_with_pwd(&link);
1370
1371 engine_state.cwd(None).unwrap_err();
1372 }
1373
1374 #[test]
1375 fn pwd_points_to_symlink_to_directory() {
1376 let dir = TempDir::new().unwrap();
1377 let temp = AbsolutePath::try_new(dir.path()).unwrap();
1378
1379 let link = temp.join("link");
1380 symlink(temp, &link).unwrap();
1381 let engine_state = engine_state_with_pwd(&link);
1382
1383 let cwd = engine_state.cwd(None).unwrap();
1384 assert_path_eq!(cwd, link);
1385 }
1386
1387 #[test]
1388 fn pwd_points_to_broken_symlink() {
1389 let dir = TempDir::new().unwrap();
1390 let temp = AbsolutePath::try_new(dir.path()).unwrap();
1391 let other_dir = TempDir::new().unwrap();
1392 let other_temp = AbsolutePath::try_new(other_dir.path()).unwrap();
1393
1394 let link = temp.join("link");
1395 symlink(other_temp, &link).unwrap();
1396 let engine_state = engine_state_with_pwd(&link);
1397
1398 drop(other_dir);
1399 engine_state.cwd(None).unwrap_err();
1400 }
1401
1402 #[test]
1403 fn pwd_points_to_nonexistent_entity() {
1404 let engine_state = engine_state_with_pwd(TempDir::new().unwrap().path());
1405
1406 engine_state.cwd(None).unwrap_err();
1407 }
1408
1409 #[test]
1410 fn stack_pwd_not_set() {
1411 let dir = TempDir::new().unwrap();
1412 let engine_state = engine_state_with_pwd(dir.path());
1413 let stack = Stack::new();
1414
1415 let cwd = engine_state.cwd(Some(&stack)).unwrap();
1416 assert_eq!(cwd, dir.path());
1417 }
1418
1419 #[test]
1420 fn stack_pwd_is_empty_string() {
1421 let dir = TempDir::new().unwrap();
1422 let engine_state = engine_state_with_pwd(dir.path());
1423 let stack = stack_with_pwd("");
1424
1425 engine_state.cwd(Some(&stack)).unwrap_err();
1426 }
1427
1428 #[test]
1429 fn stack_pwd_points_to_normal_directory() {
1430 let dir1 = TempDir::new().unwrap();
1431 let dir2 = TempDir::new().unwrap();
1432 let engine_state = engine_state_with_pwd(dir1.path());
1433 let stack = stack_with_pwd(dir2.path());
1434
1435 let cwd = engine_state.cwd(Some(&stack)).unwrap();
1436 assert_path_eq!(cwd, dir2.path());
1437 }
1438
1439 #[test]
1440 fn stack_pwd_points_to_normal_directory_with_symlink_components() {
1441 let dir = TempDir::new().unwrap();
1442 let temp = AbsolutePath::try_new(dir.path()).unwrap();
1443
1444 let link = temp.join("link");
1446 symlink(temp, &link).unwrap();
1447 let foo = link.join("foo");
1448 std::fs::create_dir(temp.join("foo")).unwrap();
1449 let engine_state = EngineState::new();
1450 let stack = stack_with_pwd(&foo);
1451
1452 let cwd = engine_state.cwd(Some(&stack)).unwrap();
1453 assert_path_eq!(cwd, foo);
1454 }
1455}