-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecutable.rs
More file actions
1675 lines (1505 loc) · 65.1 KB
/
Copy pathexecutable.rs
File metadata and controls
1675 lines (1505 loc) · 65.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) Jonathan D.A. Jewell <j.d.a.jewell@open.ac.uk>
//! Executable Command Trait
//!
//! Decouples command parsing from execution, creating a clean seam
//! between Layer 1 (Implementation) and Layer 2 (Parser).
use anyhow::Result;
use crate::parser::Command;
use crate::proof_refs::ProofReference;
use crate::redirection;
use crate::state::ShellState;
use crate::{commands, external};
/// Trait for executable commands with proof references.
///
/// Separates concerns between parsing and execution:
/// - Parser creates [`Command`] enum from user input
/// - This trait handles command execution logic
/// - REPL just calls [`execute`](ExecutableCommand::execute)
///
/// # Examples
/// ```no_run
/// use vsh::executable::ExecutableCommand;
/// use vsh::parser::Command;
/// use vsh::state::ShellState;
///
/// let mut state = ShellState::new("/tmp/test")?;
/// let cmd = Command::Mkdir { path: "test".to_string(), redirects: vec![] };
/// cmd.execute(&mut state)?;
/// # Ok::<(), anyhow::Error>(())
/// ```
pub trait ExecutableCommand {
/// Execute the command, potentially modifying shell state
fn execute(&self, state: &mut ShellState) -> Result<ExecutionResult>;
/// Check if this command is reversible (creates undo entry)
#[allow(dead_code)]
fn is_reversible(&self) -> bool;
/// Get the proof reference for this command (if any)
#[allow(dead_code)]
fn proof_reference(&self) -> Option<ProofReference>;
/// Get command description for display
#[allow(dead_code)]
fn description(&self) -> String;
}
/// Result of command execution indicating next REPL action.
///
/// Determines whether the REPL should continue, exit, or handle
/// external command exit codes.
#[derive(Debug)]
pub enum ExecutionResult {
/// Command completed successfully
Success,
/// Command requests shell exit
Exit,
/// External command executed with exit code
ExternalCommand { exit_code: i32 },
/// `return` was invoked inside a function. This variant propagates
/// up through nested control structures (if/while/for/case/&&/||)
/// until it is caught by `execute_function_call`, which converts it
/// back to a regular exit code result.
Return { exit_code: i32 },
}
impl ExecutableCommand for Command {
fn execute(&self, state: &mut ShellState) -> Result<ExecutionResult> {
match self {
// Filesystem operations (reversible)
Command::Mkdir { path, redirects } => {
let expanded_path = crate::parser::expand_variables(path, state);
if redirects.is_empty() {
commands::mkdir(state, &expanded_path, false)?;
} else {
redirection::capture_and_redirect(redirects, state, |s| {
commands::mkdir(s, &expanded_path, false)
})?;
}
Ok(ExecutionResult::Success)
}
Command::Rmdir { path, redirects } => {
let expanded_path = crate::parser::expand_variables(path, state);
if redirects.is_empty() {
commands::rmdir(state, &expanded_path, false)?;
} else {
redirection::capture_and_redirect(redirects, state, |s| {
commands::rmdir(s, &expanded_path, false)
})?;
}
Ok(ExecutionResult::Success)
}
Command::Touch { path, redirects } => {
let expanded_path = crate::parser::expand_variables(path, state);
if redirects.is_empty() {
commands::touch(state, &expanded_path, false)?;
} else {
redirection::capture_and_redirect(redirects, state, |s| {
commands::touch(s, &expanded_path, false)
})?;
}
Ok(ExecutionResult::Success)
}
Command::Rm { path, redirects } => {
let expanded_path = crate::parser::expand_variables(path, state);
if redirects.is_empty() {
commands::rm(state, &expanded_path, false)?;
} else {
redirection::capture_and_redirect(redirects, state, |s| {
commands::rm(s, &expanded_path, false)
})?;
}
Ok(ExecutionResult::Success)
}
Command::Cp {
src,
dst,
redirects,
} => {
let expanded_src = crate::parser::expand_variables(src, state);
let expanded_dst = crate::parser::expand_variables(dst, state);
if redirects.is_empty() {
commands::cp(state, &expanded_src, &expanded_dst, false)?;
} else {
redirection::capture_and_redirect(redirects, state, |s| {
commands::cp(s, &expanded_src, &expanded_dst, false)
})?;
}
Ok(ExecutionResult::Success)
}
Command::Mv {
src,
dst,
redirects,
} => {
let expanded_src = crate::parser::expand_variables(src, state);
let expanded_dst = crate::parser::expand_variables(dst, state);
if redirects.is_empty() {
commands::mv(state, &expanded_src, &expanded_dst, false)?;
} else {
redirection::capture_and_redirect(redirects, state, |s| {
commands::mv(s, &expanded_src, &expanded_dst, false)
})?;
}
Ok(ExecutionResult::Success)
}
Command::Ln {
target,
link,
redirects,
} => {
let expanded_target = crate::parser::expand_variables(target, state);
let expanded_link = crate::parser::expand_variables(link, state);
if redirects.is_empty() {
commands::symlink(state, &expanded_target, &expanded_link, false)?;
} else {
redirection::capture_and_redirect(redirects, state, |s| {
commands::symlink(s, &expanded_target, &expanded_link, false)
})?;
}
Ok(ExecutionResult::Success)
}
Command::Chmod {
mode,
path,
redirects,
} => {
let expanded_mode = crate::parser::expand_variables(mode, state);
let expanded_path = crate::parser::expand_variables(path, state);
if redirects.is_empty() {
commands::chmod(state, &expanded_mode, &expanded_path, false)?;
} else {
redirection::capture_and_redirect(redirects, state, |s| {
commands::chmod(s, &expanded_mode, &expanded_path, false)
})?;
}
Ok(ExecutionResult::Success)
}
#[cfg(unix)]
Command::Chown {
owner,
path,
redirects,
} => {
let expanded_owner = crate::parser::expand_variables(owner, state);
let expanded_path = crate::parser::expand_variables(path, state);
if redirects.is_empty() {
commands::chown(state, &expanded_owner, &expanded_path, false)?;
} else {
redirection::capture_and_redirect(redirects, state, |s| {
commands::chown(s, &expanded_owner, &expanded_path, false)
})?;
}
Ok(ExecutionResult::Success)
}
#[cfg(not(unix))]
Command::Chown { .. } => {
anyhow::bail!("chown not supported on this platform");
}
// Undo/redo operations
Command::Undo { count } => {
commands::undo(state, *count, false)?;
Ok(ExecutionResult::Success)
}
Command::Redo { count } => {
commands::redo(state, *count, false)?;
Ok(ExecutionResult::Success)
}
Command::History { count, show_proofs } => {
commands::history(state, *count, *show_proofs)?;
Ok(ExecutionResult::Success)
}
// Transactions
Command::Begin { name } => {
let expanded_name = crate::parser::expand_variables(name, state);
commands::begin_transaction(state, &expanded_name)?;
Ok(ExecutionResult::Success)
}
Command::Commit => {
commands::commit_transaction(state)?;
Ok(ExecutionResult::Success)
}
Command::Rollback => {
commands::rollback_transaction(state)?;
Ok(ExecutionResult::Success)
}
// Display commands
Command::Graph => {
commands::show_graph(state)?;
Ok(ExecutionResult::Success)
}
Command::Proofs => {
commands::show_proofs()?;
Ok(ExecutionResult::Success)
}
// Exit commands
Command::Exit | Command::Quit => Ok(ExecutionResult::Exit),
// Navigation (built-ins but not reversible)
Command::Ls { path, redirects } => {
// Expand variables in path
let expanded_path = path
.as_ref()
.map(|p| crate::parser::expand_variables(p, state));
if redirects.is_empty() {
// Direct output to terminal
use std::fs;
let target = if let Some(ref p) = expanded_path {
state.resolve_path(p)
} else {
state.root.clone()
};
if !target.is_dir() {
anyhow::bail!("Not a directory");
}
for entry in fs::read_dir(&target)? {
let entry = entry?;
let name = entry.file_name();
let file_type = entry.file_type()?;
if file_type.is_dir() {
use colored::Colorize;
println!("{}/", name.to_string_lossy().bright_blue());
} else {
println!("{}", name.to_string_lossy());
}
}
} else {
// Capture and redirect output
redirection::capture_and_redirect(redirects, state, |s| {
use std::fs;
let target = if let Some(ref p) = expanded_path {
s.resolve_path(p)
} else {
s.root.clone()
};
if !target.is_dir() {
anyhow::bail!("Not a directory");
}
for entry in fs::read_dir(&target)? {
let entry = entry?;
let name = entry.file_name();
let file_type = entry.file_type()?;
if file_type.is_dir() {
// No colors when redirecting
println!("{}/", name.to_string_lossy());
} else {
println!("{}", name.to_string_lossy());
}
}
Ok(())
})?;
}
Ok(ExecutionResult::Success)
}
Command::Pwd { redirects } => {
if redirects.is_empty() {
println!("{}", state.root.display());
} else {
redirection::capture_and_redirect(redirects, state, |s| {
println!("{}", s.root.display());
Ok(())
})?;
}
Ok(ExecutionResult::Success)
}
Command::Cd { path } => {
use std::path::PathBuf;
// Expand variables in path first
let expanded_path = path
.as_ref()
.map(|p| crate::parser::expand_variables(p, state));
let target = if let Some(ref p) = expanded_path {
if p == "-" {
// cd - : swap to previous directory
match &state.previous_dir {
Some(prev) => {
// Print the directory we're switching to (bash behavior)
println!("{}", prev.display());
prev.clone()
}
None => {
anyhow::bail!("cd: OLDPWD not set");
}
}
} else if p.starts_with('/') {
// Absolute path (also handles expanded ~/... since
// tilde expansion in expand_variables already turned
// ~/path into /home/user/path)
PathBuf::from(p)
} else {
// Relative to current directory
state.root.join(p)
}
} else {
// cd with no args goes to home
dirs::home_dir()
.ok_or_else(|| anyhow::anyhow!("Could not find home directory"))?
};
if !target.exists() {
anyhow::bail!("cd: {}: No such file or directory", target.display());
}
if !target.is_dir() {
anyhow::bail!("cd: {}: Not a directory", target.display());
}
// Store current directory as previous before changing
state.previous_dir = Some(state.root.clone());
// Change the shell's working directory
std::env::set_current_dir(&target)?;
// Update state root to track current directory
state.root = std::fs::canonicalize(target)?;
Ok(ExecutionResult::Success)
}
// Conditionals
Command::Test { args, redirects } => {
// Expand arguments
let expanded_args: Vec<String> = args
.iter()
.map(|arg| crate::parser::expand_variables(arg, state))
.collect();
let exit_code = if redirects.is_empty() {
crate::test_command::execute_test(&expanded_args, false)?
} else {
let mut code = 0;
redirection::capture_and_redirect(redirects, state, |_s| {
code = crate::test_command::execute_test(&expanded_args, false)?;
Ok(())
})?;
code
};
Ok(ExecutionResult::ExternalCommand { exit_code })
}
Command::Bracket { args, redirects } => {
// Expand arguments
let expanded_args: Vec<String> = args
.iter()
.map(|arg| crate::parser::expand_variables(arg, state))
.collect();
let exit_code = if redirects.is_empty() {
crate::test_command::execute_test(&expanded_args, true)?
} else {
let mut code = 0;
redirection::capture_and_redirect(redirects, state, |_s| {
code = crate::test_command::execute_test(&expanded_args, true)?;
Ok(())
})?;
code
};
Ok(ExecutionResult::ExternalCommand { exit_code })
}
Command::ExtendedTest { args, redirects } => {
// Extended test [[ ... ]] - NO word splitting, pattern matching enabled
// Expand variables but without word splitting (key difference from regular test)
let expanded_args: Vec<String> = args
.iter()
.map(|arg| crate::parser::expand_variables(arg, state))
.collect();
let exit_code = if redirects.is_empty() {
crate::test_command::execute_extended_test(&expanded_args)?
} else {
let mut code = 0;
redirection::capture_and_redirect(redirects, state, |_s| {
code = crate::test_command::execute_extended_test(&expanded_args)?;
Ok(())
})?;
code
};
Ok(ExecutionResult::ExternalCommand { exit_code })
}
// External commands (not reversible by default, but redirections are)
Command::External {
program,
args,
redirects,
background,
} => {
// Expand program name (no process substitutions in program name)
let expanded_program = crate::parser::expand_with_command_sub(program, state)?;
// Check if the command is a shell function before external execution.
// `if let Some(...)` performs a single map lookup; the previous
// `is_defined()` + `.get(...).expect("TODO")` shape both panicked
// through a fake-debt marker and duplicated the lookup.
if let Some(func_def) = state.functions.get(&expanded_program).cloned() {
let expanded_args: Vec<String> = args
.iter()
.map(|a| crate::parser::expand_variables(a, state))
.collect();
return execute_function_call(&func_def, &expanded_args, state);
}
// Expand arguments with process substitutions
let mut all_process_subs = Vec::new();
let mut expanded_args = Vec::new();
for arg in args {
let (expanded_arg, proc_subs) =
crate::parser::expand_with_process_sub(arg, state)?;
expanded_args.push(expanded_arg);
all_process_subs.extend(proc_subs);
}
// Execute main command
if *background {
// Background execution
let _job_id = external::execute_external_background(
&expanded_program,
&expanded_args,
redirects,
state,
)
.unwrap_or_else(|e| {
eprintln!("{}: {}", expanded_program, e);
0 // No job created
});
// Cleanup all process substitutions
for proc_sub in all_process_subs {
if let Err(e) = proc_sub.cleanup() {
eprintln!("Warning: Failed to cleanup process substitution: {}", e);
}
}
Ok(ExecutionResult::Success)
} else {
// Foreground execution
let exit_code = if redirects.is_empty() {
// No redirections - use simple path
external::execute_external(&expanded_program, &expanded_args)
} else {
// Has redirections - use redirection-aware execution
external::execute_external_with_redirects(
&expanded_program,
&expanded_args,
redirects,
state,
)
}
.unwrap_or_else(|e| {
eprintln!("{}: {}", expanded_program, e);
127
});
// Cleanup all process substitutions
for proc_sub in all_process_subs {
if let Err(e) = proc_sub.cleanup() {
eprintln!("Warning: Failed to cleanup process substitution: {}", e);
}
}
Ok(ExecutionResult::ExternalCommand { exit_code })
}
}
// Pipeline commands (not reversible by default, but redirections are)
Command::Pipeline {
stages,
redirects,
background,
} => {
// Expand variables and command substitutions in all pipeline stages
let expanded_stages: Result<Vec<(String, Vec<String>)>> = stages
.iter()
.map(|(program, args)| {
let expanded_program =
crate::parser::expand_with_command_sub(program, state)?;
let expanded_args: Result<Vec<String>> = args
.iter()
.map(|arg| crate::parser::expand_with_command_sub(arg, state))
.collect();
Ok((expanded_program, expanded_args?))
})
.collect();
let expanded_stages = expanded_stages?;
if *background && !expanded_stages.is_empty() {
// Background pipeline: launch first stage in background, pipe rest
// For now, warn and run in foreground — full background pipeline
// requires SIGCHLD handler and process group management for all stages
eprintln!(
"vsh: background pipelines not yet fully supported, running in foreground"
);
}
let exit_code = external::execute_pipeline(&expanded_stages, redirects, state)
.unwrap_or_else(|e| {
eprintln!("Pipeline error: {}", e);
127
});
Ok(ExecutionResult::ExternalCommand { exit_code })
}
// Variable assignment (tracked for undo/redo)
Command::Assignment { name, value } => {
// Expand variables and command substitutions in the value
let expanded_value = crate::parser::expand_with_command_sub(value, state)?;
state.set_variable_tracked(name, expanded_value);
Ok(ExecutionResult::Success)
}
// Array assignment
Command::ArrayAssignment { name, elements } => {
// Expand variables in each element
let expanded_elements: Vec<String> = elements
.iter()
.map(|elem| crate::parser::expand_variables(elem, state))
.collect();
state.set_array(name, expanded_elements);
Ok(ExecutionResult::Success)
}
// Array element assignment
Command::ArrayElementAssignment { name, index, value } => {
// Expand variables in the value
let expanded_value = crate::parser::expand_variables(value, state);
state.set_array_element(name, *index, expanded_value);
Ok(ExecutionResult::Success)
}
// Array append
Command::ArrayAppend { name, elements } => {
// Expand variables in each element
let expanded_elements: Vec<String> = elements
.iter()
.map(|elem| crate::parser::expand_variables(elem, state))
.collect();
state.append_to_array(name, expanded_elements);
Ok(ExecutionResult::Success)
}
// Export command
Command::Export { name, value } => {
if let Some(val) = value {
// export VAR=value
// Expand variables and command substitutions in the value
let expanded_value = crate::parser::expand_with_command_sub(val, state)?;
state.set_variable(name, expanded_value);
state.export_variable(name);
} else {
// export VAR (export existing variable)
if state.get_variable(name).is_some() {
state.export_variable(name);
} else {
anyhow::bail!("export: {}: variable not set", name);
}
}
Ok(ExecutionResult::Success)
}
// Job control
Command::Jobs { long } => {
commands::jobs(state, *long)?;
Ok(ExecutionResult::Success)
}
Command::Fg { job_spec } => {
commands::fg(state, job_spec.as_deref())?;
Ok(ExecutionResult::Success)
}
Command::Bg { job_spec } => {
commands::bg(state, job_spec.as_deref())?;
Ok(ExecutionResult::Success)
}
Command::Kill { signal, job_spec } => {
commands::kill_job(state, signal.as_deref(), job_spec)?;
Ok(ExecutionResult::Success)
}
// Shell builtins
Command::Echo {
args,
no_newline,
interpret_escapes,
redirects,
} => {
let expanded_args: Vec<String> = args
.iter()
.map(|a| crate::parser::expand_variables(a, state))
.collect();
let output = if *interpret_escapes {
expanded_args
.join(" ")
.replace("\\n", "\n")
.replace("\\t", "\t")
.replace("\\\\", "\\")
.replace("\\a", "\x07")
.replace("\\b", "\x08")
} else {
expanded_args.join(" ")
};
if redirects.is_empty() {
if *no_newline {
print!("{}", output);
std::io::Write::flush(&mut std::io::stdout()).ok();
} else {
println!("{}", output);
}
} else {
let full_output = if *no_newline {
output
} else {
format!("{}\n", output)
};
redirection::capture_and_redirect(redirects, state, |_s| {
print!("{}", full_output);
Ok(())
})?;
}
Ok(ExecutionResult::Success)
}
Command::True => Ok(ExecutionResult::ExternalCommand { exit_code: 0 }),
Command::False => Ok(ExecutionResult::ExternalCommand { exit_code: 1 }),
Command::Read {
var_names,
prompt,
redirects: _,
} => {
if let Some(p) = prompt {
let expanded_prompt = crate::parser::expand_variables(p, state);
eprint!("{}", expanded_prompt);
std::io::Write::flush(&mut std::io::stderr()).ok();
}
let mut input = String::new();
match std::io::stdin().read_line(&mut input) {
Ok(0) => {
// EOF
Ok(ExecutionResult::ExternalCommand { exit_code: 1 })
}
Ok(_) => {
let value = input.trim_end_matches('\n').trim_end_matches('\r');
// POSIX §2.21: split by IFS, assign fields to vars.
// The last variable gets the remainder (including
// any fields beyond the variable count).
let ifs = state
.get_variable("IFS")
.map(|s| s.to_string())
.unwrap_or_else(|| crate::posix_builtins::DEFAULT_IFS.to_string());
let fields = crate::posix_builtins::ifs_split(value, &ifs);
for (i, var_name) in var_names.iter().enumerate() {
let expanded_var = crate::parser::expand_variables(var_name, state);
if i == var_names.len() - 1 {
// Last variable gets the remainder.
// Rejoin un-consumed fields with a single
// space (POSIX behaviour).
let remainder = if i < fields.len() {
fields[i..].join(" ")
} else {
String::new()
};
state.set_variable(expanded_var, remainder);
} else {
let field = fields.get(i).cloned().unwrap_or_default();
state.set_variable(expanded_var, field);
}
}
Ok(ExecutionResult::Success)
}
Err(e) => Err(anyhow::anyhow!("read: {}", e)),
}
}
Command::Source { file } => {
let expanded_file = crate::parser::expand_variables(file, state);
// For absolute paths, use directly; for relative, resolve against root
let path = if expanded_file.starts_with('/') {
std::path::PathBuf::from(&expanded_file)
} else {
state.resolve_path(&expanded_file)
};
let content = crate::fs_pure::read_to_string(&path)
.map_err(|e| anyhow::anyhow!("source: {}: {}", path.display(), e))?;
// Strip whole-line comments first, then feed the entire
// content to the statement splitter so multi-line `if/fi`,
// `for/done`, etc. stay together.
let stripped: String = content
.lines()
.map(|line| {
let trimmed = line.trim_start();
if trimmed.starts_with('#') {
""
} else {
line
}
})
.collect::<Vec<_>>()
.join("\n");
let mut last_result = ExecutionResult::Success;
for segment in crate::parser::split_on_statement_separators(&stripped) {
let segment = segment.trim();
if segment.is_empty() || segment.starts_with('#') {
continue;
}
let cmd = crate::parser::parse_command(segment)?;
last_result = cmd.execute(state)?;
// Propagate Exit (shell-wide) and Return (function-scope).
// A `return` inside a sourced file that was itself sourced
// from a function must break out all the way to
// `execute_function_call`.
if matches!(
last_result,
ExecutionResult::Exit | ExecutionResult::Return { .. }
) {
return Ok(last_result);
}
}
Ok(last_result)
}
Command::Set { args } => {
if args.is_empty() {
// Display all variables
for (name, value) in state.get_all_variables() {
println!("{}={}", name, value);
}
} else if args[0] == "--" {
// Set positional parameters: set -- arg1 arg2 ...
let params: Vec<String> = args[1..].to_vec();
state.set_positional_params(params);
} else if args[0].starts_with('-') || args[0].starts_with('+') {
// Shell options (stub: just acknowledge)
// -e: exit on error, -x: trace, -u: error on unset, etc.
for arg in args {
let enable = arg.starts_with('-');
for ch in arg[1..].chars() {
match ch {
'e' => state.set_variable(
"SHOPT_E".to_string(),
if enable { "1" } else { "0" }.to_string(),
),
'x' => state.set_variable(
"SHOPT_X".to_string(),
if enable { "1" } else { "0" }.to_string(),
),
'u' => state.set_variable(
"SHOPT_U".to_string(),
if enable { "1" } else { "0" }.to_string(),
),
_ => {}
}
}
}
} else {
// Set positional params
state.set_positional_params(args.clone());
}
Ok(ExecutionResult::Success)
}
Command::Unset { name } => {
let expanded_name = crate::parser::expand_variables(name, state);
if let Some(func_name) = expanded_name.strip_prefix("-f ") {
// unset -f: remove a function
if !state.functions.unset(func_name) {
eprintln!("unset: {}: not a function", func_name);
}
} else {
state.unset_variable_tracked(&expanded_name);
}
Ok(ExecutionResult::Success)
}
Command::Eval { args } => {
if args.is_empty() {
return Ok(ExecutionResult::Success);
}
let expanded_args: Vec<String> = args
.iter()
.map(|a| crate::parser::expand_variables(a, state))
.collect();
let combined = expanded_args.join(" ");
let cmd = crate::parser::parse_command(&combined)?;
cmd.execute(state)
}
// Control structures
Command::If {
condition,
then_body,
elif_parts,
else_body,
} => {
// Execute condition and get exit code
let cond_result = condition.execute(state)?;
let cond_exit = match cond_result {
ExecutionResult::Success => 0,
ExecutionResult::Exit => return Ok(ExecutionResult::Exit),
ExecutionResult::Return { .. } => return Ok(cond_result),
ExecutionResult::ExternalCommand { exit_code } => exit_code,
};
if cond_exit == 0 {
// Condition succeeded — execute then body
return execute_block(then_body, state);
}
// Try elif parts
for (elif_cond, elif_body) in elif_parts {
let elif_result = elif_cond.execute(state)?;
let elif_exit = match elif_result {
ExecutionResult::Success => 0,
ExecutionResult::Exit => return Ok(ExecutionResult::Exit),
ExecutionResult::Return { .. } => return Ok(elif_result),
ExecutionResult::ExternalCommand { exit_code } => exit_code,
};
if elif_exit == 0 {
return execute_block(elif_body, state);
}
}
// Execute else body if present
if let Some(ref else_cmds) = else_body {
return execute_block(else_cmds, state);
}
// No branch matched — return last condition's exit code
Ok(ExecutionResult::ExternalCommand { exit_code: 1 })
}
Command::WhileLoop { condition, body } => {
let mut last_result = ExecutionResult::Success;
// Safety: limit iterations to prevent infinite loops
let max_iterations = 100_000;
let mut iterations = 0;
loop {
if iterations >= max_iterations {
return Err(anyhow::anyhow!(
"while: exceeded {} iterations (safety limit)",
max_iterations
));
}
iterations += 1;
// Check condition
let cond_result = condition.execute(state)?;
let cond_exit = match cond_result {
ExecutionResult::Success => 0,
ExecutionResult::Exit => return Ok(ExecutionResult::Exit),
ExecutionResult::Return { .. } => return Ok(cond_result),
ExecutionResult::ExternalCommand { exit_code } => exit_code,
};
if cond_exit != 0 {
break; // Condition failed — exit loop
}
// Execute body
last_result = execute_block(body, state)?;
if matches!(
last_result,
ExecutionResult::Exit | ExecutionResult::Return { .. }
) {
return Ok(last_result);
}
// Check for SIGINT
if crate::signals::is_interrupt_requested() {
crate::signals::clear_interrupt();
break;
}
}
Ok(last_result)
}
Command::ForLoop { var, words, body } => {
let mut last_result = ExecutionResult::Success;
// POSIX §2.6.5: expand each word, then apply IFS splitting
// to produce the actual iteration list.
let ifs = state
.get_variable("IFS")
.map(|s| s.to_string())
.unwrap_or_else(|| crate::posix_builtins::DEFAULT_IFS.to_string());
let expanded_words: Vec<String> = words
.iter()
.flat_map(|word| {
let expanded = crate::parser::expand_variables(word, state);
crate::posix_builtins::ifs_split(&expanded, &ifs)
})
.collect();
for word in &expanded_words {
// Set loop variable
state.set_variable(var.clone(), word.clone());
// Execute body
last_result = execute_block(body, state)?;
if matches!(
last_result,
ExecutionResult::Exit | ExecutionResult::Return { .. }
) {