1use super::parser::Ast;
2use lazy_static::lazy_static;
3use std::cell::RefCell;
4use std::collections::{HashMap, HashSet, VecDeque};
5use std::env;
6use std::io::IsTerminal;
7use std::rc::Rc;
8use std::sync::{Arc, Mutex};
9use std::time::Instant;
10
11lazy_static! {
12 pub static ref SIGNAL_QUEUE: Arc<Mutex<VecDeque<SignalEvent>>> =
15 Arc::new(Mutex::new(VecDeque::new()));
16}
17
18const MAX_SIGNAL_QUEUE_SIZE: usize = 100;
20
21#[derive(Debug, Clone)]
23pub struct SignalEvent {
24 pub signal_name: String,
26 #[allow(dead_code)]
28 pub signal_number: i32,
29 #[allow(dead_code)]
31 pub timestamp: Instant,
32}
33
34impl SignalEvent {
35 pub fn new(signal_name: String, signal_number: i32) -> Self {
36 Self {
37 signal_name,
38 signal_number,
39 timestamp: Instant::now(),
40 }
41 }
42}
43
44#[derive(Debug, Clone)]
45pub struct ColorScheme {
46 pub prompt: String,
48 pub error: String,
50 pub success: String,
52 pub builtin: String,
54 pub directory: String,
56}
57
58impl Default for ColorScheme {
59 fn default() -> Self {
60 Self {
61 prompt: "\x1b[32m".to_string(), error: "\x1b[31m".to_string(), success: "\x1b[32m".to_string(), builtin: "\x1b[36m".to_string(), directory: "\x1b[34m".to_string(), }
67 }
68}
69
70#[derive(Debug, Clone)]
71pub struct ShellState {
72 pub variables: HashMap<String, String>,
74 pub exported: HashSet<String>,
76 pub last_exit_code: i32,
78 pub shell_pid: u32,
80 pub script_name: String,
82 pub dir_stack: Vec<String>,
84 pub aliases: HashMap<String, String>,
86 pub colors_enabled: bool,
88 pub color_scheme: ColorScheme,
90 pub positional_params: Vec<String>,
92 pub functions: HashMap<String, Ast>,
94 pub local_vars: Vec<HashMap<String, String>>,
96 pub function_depth: usize,
98 pub max_recursion_depth: usize,
100 pub returning: bool,
102 pub return_value: Option<i32>,
104 pub capture_output: Option<Rc<RefCell<Vec<u8>>>>,
106 pub condensed_cwd: bool,
108 pub trap_handlers: Arc<Mutex<HashMap<String, String>>>,
110 pub exit_trap_executed: bool,
112 pub exit_requested: bool,
114 pub exit_code: i32,
116 #[allow(dead_code)]
119 pub pending_signals: bool,
120}
121
122impl ShellState {
123 pub fn new() -> Self {
124 let shell_pid = std::process::id();
125
126 let no_color = env::var("NO_COLOR").is_ok();
128
129 let rush_colors = env::var("RUSH_COLORS")
131 .map(|v| v.to_lowercase())
132 .unwrap_or_else(|_| "auto".to_string());
133
134 let colors_enabled = match rush_colors.as_str() {
135 "1" | "true" | "on" | "enable" => !no_color && std::io::stdout().is_terminal(),
136 "0" | "false" | "off" | "disable" => false,
137 "auto" => !no_color && std::io::stdout().is_terminal(),
138 _ => !no_color && std::io::stdout().is_terminal(),
139 };
140
141 let rush_condensed = env::var("RUSH_CONDENSED")
143 .map(|v| v.to_lowercase())
144 .unwrap_or_else(|_| "true".to_string());
145
146 let condensed_cwd = match rush_condensed.as_str() {
147 "1" | "true" | "on" | "enable" => true,
148 "0" | "false" | "off" | "disable" => false,
149 _ => true, };
151
152 Self {
153 variables: HashMap::new(),
154 exported: HashSet::new(),
155 last_exit_code: 0,
156 shell_pid,
157 script_name: "rush".to_string(),
158 dir_stack: Vec::new(),
159 aliases: HashMap::new(),
160 colors_enabled,
161 color_scheme: ColorScheme::default(),
162 positional_params: Vec::new(),
163 functions: HashMap::new(),
164 local_vars: Vec::new(),
165 function_depth: 0,
166 max_recursion_depth: 500, returning: false,
168 return_value: None,
169 capture_output: None,
170 condensed_cwd,
171 trap_handlers: Arc::new(Mutex::new(HashMap::new())),
172 exit_trap_executed: false,
173 exit_requested: false,
174 exit_code: 0,
175 pending_signals: false,
176 }
177 }
178
179 pub fn get_var(&self, name: &str) -> Option<String> {
181 match name {
183 "?" => Some(self.last_exit_code.to_string()),
184 "$" => Some(self.shell_pid.to_string()),
185 "0" => Some(self.script_name.clone()),
186 "*" => {
187 if self.positional_params.is_empty() {
189 Some("".to_string())
190 } else {
191 Some(self.positional_params.join(" "))
192 }
193 }
194 "@" => {
195 if self.positional_params.is_empty() {
197 Some("".to_string())
198 } else {
199 Some(self.positional_params.join(" "))
200 }
201 }
202 "#" => Some(self.positional_params.len().to_string()),
203 _ => {
204 if let Ok(index) = name.parse::<usize>()
206 && index > 0
207 && index <= self.positional_params.len()
208 {
209 return Some(self.positional_params[index - 1].clone());
210 }
211
212 for scope in self.local_vars.iter().rev() {
215 if let Some(value) = scope.get(name) {
216 return Some(value.clone());
217 }
218 }
219
220 if let Some(value) = self.variables.get(name) {
222 Some(value.clone())
223 } else {
224 env::var(name).ok()
226 }
227 }
228 }
229 }
230
231 pub fn set_var(&mut self, name: &str, value: String) {
233 for scope in self.local_vars.iter_mut().rev() {
236 if scope.contains_key(name) {
237 scope.insert(name.to_string(), value);
238 return;
239 }
240 }
241
242 self.variables.insert(name.to_string(), value);
244 }
245
246 pub fn unset_var(&mut self, name: &str) {
248 self.variables.remove(name);
249 self.exported.remove(name);
250 }
251
252 pub fn export_var(&mut self, name: &str) {
254 if self.variables.contains_key(name) {
255 self.exported.insert(name.to_string());
256 }
257 }
258
259 pub fn set_exported_var(&mut self, name: &str, value: String) {
261 self.set_var(name, value);
262 self.export_var(name);
263 }
264
265 pub fn get_env_for_child(&self) -> HashMap<String, String> {
267 let mut child_env = HashMap::new();
268
269 for (key, value) in env::vars() {
271 child_env.insert(key, value);
272 }
273
274 for var_name in &self.exported {
276 if let Some(value) = self.variables.get(var_name) {
277 child_env.insert(var_name.clone(), value.clone());
278 }
279 }
280
281 child_env
282 }
283
284 pub fn set_last_exit_code(&mut self, code: i32) {
286 self.last_exit_code = code;
287 }
288
289 pub fn set_script_name(&mut self, name: &str) {
291 self.script_name = name.to_string();
292 }
293
294 pub fn get_condensed_cwd(&self) -> String {
296 match env::current_dir() {
297 Ok(path) => {
298 let path_str = path.to_string_lossy();
299 let components: Vec<&str> = path_str.split('/').collect();
300 if components.is_empty() || (components.len() == 1 && components[0].is_empty()) {
301 return "/".to_string();
302 }
303 let mut result = String::new();
304 for (i, comp) in components.iter().enumerate() {
305 if comp.is_empty() {
306 continue; }
308 if i == components.len() - 1 {
309 result.push('/');
310 result.push_str(comp);
311 } else {
312 result.push('/');
313 if let Some(first) = comp.chars().next() {
314 result.push(first);
315 }
316 }
317 }
318 if result.is_empty() {
319 "/".to_string()
320 } else {
321 result
322 }
323 }
324 Err(_) => "/?".to_string(), }
326 }
327
328 pub fn get_full_cwd(&self) -> String {
330 match env::current_dir() {
331 Ok(path) => path.to_string_lossy().to_string(),
332 Err(_) => "/?".to_string(), }
334 }
335
336 pub fn get_user_hostname(&self) -> String {
338 let user = env::var("USER").unwrap_or_else(|_| "user".to_string());
339
340 if let Ok(hostname) = env::var("HOSTNAME")
342 && !hostname.trim().is_empty()
343 {
344 return format!("{}@{}", user, hostname);
345 }
346
347 let hostname = match std::process::Command::new("hostname").output() {
349 Ok(output) if output.status.success() => {
350 String::from_utf8_lossy(&output.stdout).trim().to_string()
351 }
352 _ => "hostname".to_string(), };
354
355 if hostname != "hostname" {
357 unsafe {
358 env::set_var("HOSTNAME", &hostname);
359 }
360 }
361
362 format!("{}@{}", user, hostname)
363 }
364
365 pub fn get_prompt(&self) -> String {
367 let user = env::var("USER").unwrap_or_else(|_| "user".to_string());
368 let prompt_char = if user == "root" { "#" } else { "$" };
369 let cwd = if self.condensed_cwd {
370 self.get_condensed_cwd()
371 } else {
372 self.get_full_cwd()
373 };
374 format!("{}:{} {} ", self.get_user_hostname(), cwd, prompt_char)
375 }
376
377 pub fn set_alias(&mut self, name: &str, value: String) {
379 self.aliases.insert(name.to_string(), value);
380 }
381
382 pub fn get_alias(&self, name: &str) -> Option<&String> {
384 self.aliases.get(name)
385 }
386
387 pub fn remove_alias(&mut self, name: &str) {
389 self.aliases.remove(name);
390 }
391
392 pub fn get_all_aliases(&self) -> &HashMap<String, String> {
394 &self.aliases
395 }
396
397 pub fn set_positional_params(&mut self, params: Vec<String>) {
399 self.positional_params = params;
400 }
401
402 #[allow(dead_code)]
404 pub fn get_positional_params(&self) -> &[String] {
405 &self.positional_params
406 }
407
408 pub fn shift_positional_params(&mut self, count: usize) {
410 if count > 0 {
411 for _ in 0..count {
412 if !self.positional_params.is_empty() {
413 self.positional_params.remove(0);
414 }
415 }
416 }
417 }
418
419 #[allow(dead_code)]
421 pub fn push_positional_param(&mut self, param: String) {
422 self.positional_params.push(param);
423 }
424
425 pub fn define_function(&mut self, name: String, body: Ast) {
427 self.functions.insert(name, body);
428 }
429
430 pub fn get_function(&self, name: &str) -> Option<&Ast> {
432 self.functions.get(name)
433 }
434
435 #[allow(dead_code)]
437 pub fn remove_function(&mut self, name: &str) {
438 self.functions.remove(name);
439 }
440
441 #[allow(dead_code)]
443 pub fn get_function_names(&self) -> Vec<&String> {
444 self.functions.keys().collect()
445 }
446
447 pub fn push_local_scope(&mut self) {
449 self.local_vars.push(HashMap::new());
450 }
451
452 pub fn pop_local_scope(&mut self) {
454 if !self.local_vars.is_empty() {
455 self.local_vars.pop();
456 }
457 }
458
459 pub fn set_local_var(&mut self, name: &str, value: String) {
461 if let Some(current_scope) = self.local_vars.last_mut() {
462 current_scope.insert(name.to_string(), value);
463 } else {
464 self.set_var(name, value);
466 }
467 }
468
469 pub fn enter_function(&mut self) {
471 self.function_depth += 1;
472 if self.function_depth > self.local_vars.len() {
473 self.push_local_scope();
474 }
475 }
476
477 pub fn exit_function(&mut self) {
479 if self.function_depth > 0 {
480 self.function_depth -= 1;
481 if self.function_depth == self.local_vars.len() - 1 {
482 self.pop_local_scope();
483 }
484 }
485 }
486
487 pub fn set_return(&mut self, value: i32) {
489 self.returning = true;
490 self.return_value = Some(value);
491 }
492
493 pub fn clear_return(&mut self) {
495 self.returning = false;
496 self.return_value = None;
497 }
498
499 pub fn is_returning(&self) -> bool {
501 self.returning
502 }
503
504 pub fn get_return_value(&self) -> Option<i32> {
506 self.return_value
507 }
508
509 pub fn set_trap(&mut self, signal: &str, command: String) {
511 if let Ok(mut handlers) = self.trap_handlers.lock() {
512 handlers.insert(signal.to_uppercase(), command);
513 }
514 }
515
516 pub fn get_trap(&self, signal: &str) -> Option<String> {
518 if let Ok(handlers) = self.trap_handlers.lock() {
519 handlers.get(&signal.to_uppercase()).cloned()
520 } else {
521 None
522 }
523 }
524
525 pub fn remove_trap(&mut self, signal: &str) {
527 if let Ok(mut handlers) = self.trap_handlers.lock() {
528 handlers.remove(&signal.to_uppercase());
529 }
530 }
531
532 pub fn get_all_traps(&self) -> HashMap<String, String> {
534 if let Ok(handlers) = self.trap_handlers.lock() {
535 handlers.clone()
536 } else {
537 HashMap::new()
538 }
539 }
540
541 #[allow(dead_code)]
543 pub fn clear_traps(&mut self) {
544 if let Ok(mut handlers) = self.trap_handlers.lock() {
545 handlers.clear();
546 }
547 }
548}
549
550pub fn enqueue_signal(signal_name: &str, signal_number: i32) {
553 if let Ok(mut queue) = SIGNAL_QUEUE.lock() {
554 if queue.len() >= MAX_SIGNAL_QUEUE_SIZE {
556 queue.pop_front();
557 eprintln!("Warning: Signal queue overflow, dropping oldest signal");
558 }
559
560 queue.push_back(SignalEvent::new(signal_name.to_string(), signal_number));
561 }
562}
563
564pub fn process_pending_signals(shell_state: &mut ShellState) {
567 if let Ok(mut queue) = SIGNAL_QUEUE.lock() {
569 while let Some(signal_event) = queue.pop_front() {
571 if let Some(trap_cmd) = shell_state.get_trap(&signal_event.signal_name)
573 && !trap_cmd.is_empty()
574 {
575 crate::executor::execute_trap_handler(&trap_cmd, shell_state);
578 }
579 }
580 }
581}
582
583impl Default for ShellState {
584 fn default() -> Self {
585 Self::new()
586 }
587}
588
589#[cfg(test)]
590mod tests {
591 use super::*;
592
593 #[test]
594 fn test_shell_state_basic() {
595 let mut state = ShellState::new();
596 state.set_var("TEST_VAR", "test_value".to_string());
597 assert_eq!(state.get_var("TEST_VAR"), Some("test_value".to_string()));
598 }
599
600 #[test]
601 fn test_special_variables() {
602 let mut state = ShellState::new();
603 state.set_last_exit_code(42);
604 state.set_script_name("test_script");
605
606 assert_eq!(state.get_var("?"), Some("42".to_string()));
607 assert_eq!(state.get_var("$"), Some(state.shell_pid.to_string()));
608 assert_eq!(state.get_var("0"), Some("test_script".to_string()));
609 }
610
611 #[test]
612 fn test_export_variable() {
613 let mut state = ShellState::new();
614 state.set_var("EXPORT_VAR", "export_value".to_string());
615 state.export_var("EXPORT_VAR");
616
617 let child_env = state.get_env_for_child();
618 assert_eq!(
619 child_env.get("EXPORT_VAR"),
620 Some(&"export_value".to_string())
621 );
622 }
623
624 #[test]
625 fn test_unset_variable() {
626 let mut state = ShellState::new();
627 state.set_var("UNSET_VAR", "value".to_string());
628 state.export_var("UNSET_VAR");
629
630 assert!(state.variables.contains_key("UNSET_VAR"));
631 assert!(state.exported.contains("UNSET_VAR"));
632
633 state.unset_var("UNSET_VAR");
634
635 assert!(!state.variables.contains_key("UNSET_VAR"));
636 assert!(!state.exported.contains("UNSET_VAR"));
637 }
638
639 #[test]
640 fn test_get_user_hostname() {
641 let state = ShellState::new();
642 let user_hostname = state.get_user_hostname();
643 assert!(user_hostname.contains('@'));
645 }
646
647 #[test]
648 fn test_get_prompt() {
649 let state = ShellState::new();
650 let prompt = state.get_prompt();
651 assert!(prompt.ends_with(" $ "));
653 assert!(prompt.contains('@'));
654 }
655
656 #[test]
657 fn test_positional_parameters() {
658 let mut state = ShellState::new();
659 state.set_positional_params(vec![
660 "arg1".to_string(),
661 "arg2".to_string(),
662 "arg3".to_string(),
663 ]);
664
665 assert_eq!(state.get_var("1"), Some("arg1".to_string()));
666 assert_eq!(state.get_var("2"), Some("arg2".to_string()));
667 assert_eq!(state.get_var("3"), Some("arg3".to_string()));
668 assert_eq!(state.get_var("4"), None);
669 assert_eq!(state.get_var("#"), Some("3".to_string()));
670 assert_eq!(state.get_var("*"), Some("arg1 arg2 arg3".to_string()));
671 assert_eq!(state.get_var("@"), Some("arg1 arg2 arg3".to_string()));
672 }
673
674 #[test]
675 fn test_positional_parameters_empty() {
676 let mut state = ShellState::new();
677 state.set_positional_params(vec![]);
678
679 assert_eq!(state.get_var("1"), None);
680 assert_eq!(state.get_var("#"), Some("0".to_string()));
681 assert_eq!(state.get_var("*"), Some("".to_string()));
682 assert_eq!(state.get_var("@"), Some("".to_string()));
683 }
684
685 #[test]
686 fn test_shift_positional_params() {
687 let mut state = ShellState::new();
688 state.set_positional_params(vec![
689 "arg1".to_string(),
690 "arg2".to_string(),
691 "arg3".to_string(),
692 ]);
693
694 assert_eq!(state.get_var("1"), Some("arg1".to_string()));
695 assert_eq!(state.get_var("2"), Some("arg2".to_string()));
696 assert_eq!(state.get_var("3"), Some("arg3".to_string()));
697
698 state.shift_positional_params(1);
699
700 assert_eq!(state.get_var("1"), Some("arg2".to_string()));
701 assert_eq!(state.get_var("2"), Some("arg3".to_string()));
702 assert_eq!(state.get_var("3"), None);
703 assert_eq!(state.get_var("#"), Some("2".to_string()));
704
705 state.shift_positional_params(2);
706
707 assert_eq!(state.get_var("1"), None);
708 assert_eq!(state.get_var("#"), Some("0".to_string()));
709 }
710
711 #[test]
712 fn test_push_positional_param() {
713 let mut state = ShellState::new();
714 state.set_positional_params(vec!["arg1".to_string()]);
715
716 assert_eq!(state.get_var("1"), Some("arg1".to_string()));
717 assert_eq!(state.get_var("#"), Some("1".to_string()));
718
719 state.push_positional_param("arg2".to_string());
720
721 assert_eq!(state.get_var("1"), Some("arg1".to_string()));
722 assert_eq!(state.get_var("2"), Some("arg2".to_string()));
723 assert_eq!(state.get_var("#"), Some("2".to_string()));
724 }
725
726 #[test]
727 fn test_local_variable_scoping() {
728 let mut state = ShellState::new();
729
730 state.set_var("global_var", "global_value".to_string());
732 assert_eq!(
733 state.get_var("global_var"),
734 Some("global_value".to_string())
735 );
736
737 state.push_local_scope();
739
740 state.set_local_var("global_var", "local_value".to_string());
742 assert_eq!(state.get_var("global_var"), Some("local_value".to_string()));
743
744 state.set_local_var("local_var", "local_only".to_string());
746 assert_eq!(state.get_var("local_var"), Some("local_only".to_string()));
747
748 state.pop_local_scope();
750
751 assert_eq!(
753 state.get_var("global_var"),
754 Some("global_value".to_string())
755 );
756 assert_eq!(state.get_var("local_var"), None);
757 }
758
759 #[test]
760 fn test_nested_local_scopes() {
761 let mut state = ShellState::new();
762
763 state.set_var("test_var", "global".to_string());
765
766 state.push_local_scope();
768 state.set_local_var("test_var", "level1".to_string());
769 assert_eq!(state.get_var("test_var"), Some("level1".to_string()));
770
771 state.push_local_scope();
773 state.set_local_var("test_var", "level2".to_string());
774 assert_eq!(state.get_var("test_var"), Some("level2".to_string()));
775
776 state.pop_local_scope();
778 assert_eq!(state.get_var("test_var"), Some("level1".to_string()));
779
780 state.pop_local_scope();
782 assert_eq!(state.get_var("test_var"), Some("global".to_string()));
783 }
784
785 #[test]
786 fn test_variable_set_in_local_scope() {
787 let mut state = ShellState::new();
788
789 state.set_var("test_var", "global".to_string());
791 assert_eq!(state.get_var("test_var"), Some("global".to_string()));
792
793 state.push_local_scope();
795 state.set_local_var("test_var", "local".to_string());
796 assert_eq!(state.get_var("test_var"), Some("local".to_string()));
797
798 state.pop_local_scope();
800 assert_eq!(state.get_var("test_var"), Some("global".to_string()));
801 }
802
803 #[test]
804 fn test_condensed_cwd_environment_variable() {
805 let state = ShellState::new();
807 assert!(state.condensed_cwd);
808
809 unsafe {
811 env::set_var("RUSH_CONDENSED", "true");
812 }
813 let state = ShellState::new();
814 assert!(state.condensed_cwd);
815
816 unsafe {
818 env::set_var("RUSH_CONDENSED", "false");
819 }
820 let state = ShellState::new();
821 assert!(!state.condensed_cwd);
822
823 unsafe {
825 env::remove_var("RUSH_CONDENSED");
826 }
827 }
828
829 #[test]
830 fn test_get_full_cwd() {
831 let state = ShellState::new();
832 let full_cwd = state.get_full_cwd();
833 assert!(!full_cwd.is_empty());
834 assert!(full_cwd.contains('/') || full_cwd.contains('\\'));
836 }
837
838 #[test]
839 fn test_prompt_with_condensed_setting() {
840 let mut state = ShellState::new();
841
842 assert!(state.condensed_cwd);
844 let prompt_condensed = state.get_prompt();
845 assert!(prompt_condensed.contains('@'));
846
847 state.condensed_cwd = false;
849 let prompt_full = state.get_prompt();
850 assert!(prompt_full.contains('@'));
851
852 assert!(prompt_condensed.ends_with("$ ") || prompt_condensed.ends_with("# "));
854 assert!(prompt_full.ends_with("$ ") || prompt_full.ends_with("# "));
855 }
856}