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