-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexternal.rs
More file actions
829 lines (727 loc) · 29.2 KB
/
Copy pathexternal.rs
File metadata and controls
829 lines (727 loc) · 29.2 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
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) Jonathan D.A. Jewell <j.d.a.jewell@open.ac.uk>
//! External Command Execution
//!
//! Executes external programs via execve(), handles PATH lookup,
//! and manages stdio.
use anyhow::{Context, Result};
use std::fs::{File, OpenOptions};
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::time::Duration;
use crate::glob;
use crate::redirection::{RedirectSetup, Redirection};
use crate::signals;
use crate::state::ShellState;
/// Execute an external command with I/O redirections
///
/// Handles:
/// - Output redirection (>, >>, 2>, 2>>, &>)
/// - Input redirection (<)
/// - Error to output (2>&1)
/// - Signal termination (SIGINT, SIGTERM)
/// - File modification tracking for undo
pub fn execute_external_with_redirects(
program: &str,
args: &[String],
redirects: &[Redirection],
state: &mut ShellState,
) -> Result<i32> {
// Setup redirections (validates, opens files, saves state)
let redirect_setup = RedirectSetup::setup(redirects, state)?;
// Configure stdio from redirections
let (stdin_cfg, stdout_cfg, stderr_cfg) =
stdio_config_from_redirects(redirects, &redirect_setup, state)?;
// Expand glob patterns in arguments (Phase 6 M12)
let expanded_args = expand_glob_args(args, state)?;
// PATH lookup
let executable = find_in_path(program)?;
// Build command with redirected stdio
let mut command = Command::new(&executable);
command
.args(&expanded_args)
.stdin(stdin_cfg)
.stdout(stdout_cfg)
.stderr(stderr_cfg);
// Set process group on Unix for proper job control
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
command.process_group(0);
}
// Spawn child process (non-blocking)
let mut child = command
.spawn()
.context(format!("Failed to spawn: {}", program))?;
// Poll for exit while checking for interrupt
loop {
match child.try_wait().context("Failed to wait for child")? {
Some(status) => {
// Child exited - record modifications and return
redirect_setup.record_for_undo(state)?;
return handle_exit_status(status);
}
None => {
// Child still running - check for interrupt
if signals::is_interrupt_requested() {
// User pressed Ctrl+C - kill child and reset flag
child.kill().context("Failed to kill child process")?;
signals::clear_interrupt();
// Wait for child to actually terminate
child.wait().context("Failed to wait for killed child")?;
// Don't record modifications - operation interrupted
return Ok(130); // 128 + SIGINT(2)
}
// Sleep briefly before next check
std::thread::sleep(Duration::from_millis(50));
}
}
}
}
/// Execute a pipeline of external commands with stdio chaining.
///
/// Spawns each command in sequence, piping stdout of stage N to stdin of stage N+1.
/// Final stage's output goes to redirections or inherits from shell.
///
/// # Arguments
/// * `stages` - Vector of (program, args) pairs for each pipeline stage
/// * `redirects` - Final redirections (>, >>, etc.) applied to last stage
/// * `state` - Shell state for undo tracking
///
/// # Returns
/// Exit code of the rightmost (last) command in the pipeline (POSIX behavior)
///
/// # Errors
/// Returns error if:
/// - Pipeline is empty or has only one stage
/// - Program not found in PATH
/// - Failed to spawn child process
/// - Failed to setup redirections
///
/// # Examples
/// ```no_run
/// use vsh::external;
/// use vsh::state::ShellState;
///
/// let stages = vec![
/// ("ls".to_string(), vec!["-la".to_string()]),
/// ("grep".to_string(), vec!["test".to_string()]),
/// ];
/// let mut state = ShellState::new("/tmp")?;
/// let exit_code = external::execute_pipeline(&stages, &[], &mut state)?;
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn execute_pipeline(
stages: &[(String, Vec<String>)],
redirects: &[Redirection],
state: &mut ShellState,
) -> Result<i32> {
if stages.is_empty() {
anyhow::bail!("Pipeline must have at least one stage");
}
if stages.len() == 1 {
// Single stage - just run normally with redirects
return execute_external_with_redirects(&stages[0].0, &stages[0].1, redirects, state);
}
// Setup final redirection output files
let redirect_setup = if !redirects.is_empty() {
Some(RedirectSetup::setup(redirects, state)?)
} else {
None
};
// Configure stdio for stages and spawn children
let mut children: Vec<std::process::Child> = Vec::new();
let mut prev_stdout: Option<std::process::ChildStdout> = None;
for (idx, (program, args)) in stages.iter().enumerate() {
let executable = find_in_path(program)?;
let is_first = idx == 0;
let is_last = idx == stages.len() - 1;
// Configure stdin
let stdin_cfg =
if is_first {
// First stage: inherit from shell
Stdio::inherit()
} else {
// Middle/last stages: read from previous stdout.
// Invariant: when idx > 0, the previous iteration spawned a
// non-last child with Stdio::piped() stdout (line below) and
// stored child.stdout into prev_stdout after spawning. So the
// expect documents an unreachable branch rather than a TODO.
Stdio::from(prev_stdout.take().expect(
"prev_stdout invariant: previous non-last stage stored its piped stdout",
))
};
// Configure stdout. Pivot on redirect_setup directly: it is Some
// iff redirects is non-empty (constructed above), so matching the
// Option both removes a duplicated emptiness check and eliminates
// a previous panic site.
let stdout_cfg = if is_last {
match &redirect_setup {
Some(setup) => stdio_config_from_redirects(redirects, setup, state)?.1,
None => Stdio::inherit(),
}
} else {
// First/middle stages: pipe to next
Stdio::piped()
};
// Configure stderr (inherit unless redirected in last stage).
let stderr_cfg = match (is_last, &redirect_setup) {
(true, Some(setup)) => stdio_config_from_redirects(redirects, setup, state)?.2,
_ => Stdio::inherit(),
};
// Spawn child
let mut command = Command::new(&executable);
command
.args(args)
.stdin(stdin_cfg)
.stdout(stdout_cfg)
.stderr(stderr_cfg);
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
command.process_group(0);
}
let mut child = command
.spawn()
.context(format!("Failed to spawn: {}", program))?;
// Save stdout for next stage
if !is_last {
prev_stdout = child.stdout.take();
}
children.push(child);
}
// Wait for all children in order, checking for SIGINT
let mut final_exit_code = 0;
for (idx, mut child) in children.into_iter().enumerate() {
loop {
match child.try_wait().context("Failed to wait for child")? {
Some(status) => {
let exit_code = handle_exit_status(status)?;
if idx == stages.len() - 1 {
// Last stage's exit code is pipeline's exit code
final_exit_code = exit_code;
}
break;
}
None => {
// Child still running - check for interrupt
if signals::is_interrupt_requested() {
// Kill all remaining children
child.kill().context("Failed to kill child process")?;
signals::clear_interrupt();
child.wait().context("Failed to wait for killed child")?;
// Don't record modifications - operation interrupted
return Ok(130); // 128 + SIGINT
}
std::thread::sleep(Duration::from_millis(50));
}
}
}
}
// Record undo for final redirection (if any)
if let Some(setup) = redirect_setup {
setup.record_for_undo(state)?;
}
Ok(final_exit_code)
}
/// Execute an external command without redirections (legacy interface).
///
/// Spawns a child process via execve(), polls for completion, and handles
/// Ctrl+C interruption gracefully. The child process runs in its own process
/// group for proper job control on Unix.
///
/// # Arguments
/// * `program` - Program name (resolved via PATH lookup)
/// * `args` - Command arguments
///
/// # Returns
/// Exit code from the child process:
/// - 0: Success
/// - 1-127: Program-specific exit codes
/// - 128+N: Terminated by signal N (130 = SIGINT, 143 = SIGTERM)
///
/// # Errors
/// Returns error if:
/// - Program not found in PATH
/// - Failed to spawn child process
/// - Failed to wait for child termination
///
/// # Examples
/// ```no_run
/// use vsh::external;
///
/// let exit_code = external::execute_external("ls", &["-la".to_string()])?;
/// assert_eq!(exit_code, 0);
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn execute_external(program: &str, args: &[String]) -> Result<i32> {
// PATH lookup
let executable = find_in_path(program)?;
// Spawn child process (non-blocking)
let mut child = Command::new(&executable)
.args(args)
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.spawn()
.context(format!("Failed to spawn: {}", program))?;
// Poll for exit while checking for interrupt
loop {
match child.try_wait().context("Failed to wait for child")? {
Some(status) => {
// Child exited normally
return handle_exit_status(status);
}
None => {
// Child still running - check for interrupt
if signals::is_interrupt_requested() {
// User pressed Ctrl+C - kill child and reset flag
child.kill().context("Failed to kill child process")?;
signals::clear_interrupt();
// Wait for child to actually terminate
child.wait().context("Failed to wait for killed child")?;
return Ok(130); // 128 + SIGINT(2)
}
// Sleep briefly before next check
std::thread::sleep(Duration::from_millis(50));
}
}
}
}
/// Convert redirections to stdio configuration
fn stdio_config_from_redirects(
redirects: &[Redirection],
_setup: &RedirectSetup,
state: &mut ShellState,
) -> Result<(Stdio, Stdio, Stdio)> {
let mut stdin_cfg = Stdio::inherit();
let mut stdout_cfg = Stdio::inherit();
let mut stderr_cfg = Stdio::inherit();
// Track stdout's file handle for 2>&1 fd duplication
let mut stdout_file_dup: Option<File> = None;
for redirect in redirects {
match redirect {
Redirection::Output { file } => {
let target = state.resolve_path(file);
let file_handle = File::create(&target)
.with_context(|| format!("Failed to open output file: {}", target.display()))?;
// Keep a clone for potential 2>&1 duplication
stdout_file_dup = Some(
file_handle
.try_clone()
.context("Failed to duplicate stdout file handle for 2>&1 tracking")?,
);
stdout_cfg = Stdio::from(file_handle);
}
Redirection::Append { file } => {
let target = state.resolve_path(file);
let file_handle = OpenOptions::new()
.create(true)
.append(true)
.open(&target)
.with_context(|| {
format!(
"Failed to open output file for append: {}",
target.display()
)
})?;
stdout_file_dup = Some(
file_handle
.try_clone()
.context("Failed to duplicate stdout file handle for 2>&1 tracking")?,
);
stdout_cfg = Stdio::from(file_handle);
}
Redirection::Input { file } => {
let target = state.resolve_path(file);
let file_handle = File::open(&target)
.with_context(|| format!("Failed to open input file: {}", target.display()))?;
stdin_cfg = Stdio::from(file_handle);
}
Redirection::ErrorOutput { file } | Redirection::ErrorAppend { file } => {
let target = state.resolve_path(file);
let file_handle = if matches!(redirect, Redirection::ErrorAppend { .. }) {
OpenOptions::new().create(true).append(true).open(&target)
} else {
File::create(&target)
}
.with_context(|| format!("Failed to open error file: {}", target.display()))?;
stderr_cfg = Stdio::from(file_handle);
}
Redirection::BothOutput { file } => {
let target = state.resolve_path(file);
let file_handle = File::create(&target)
.with_context(|| format!("Failed to open output file: {}", target.display()))?;
// Clone the file handle for both stdout and stderr
let file_handle2 = file_handle
.try_clone()
.context("Failed to duplicate file handle")?;
stdout_file_dup = Some(
file_handle
.try_clone()
.context("Failed to duplicate stdout file handle for 2>&1 tracking")?,
);
stdout_cfg = Stdio::from(file_handle);
stderr_cfg = Stdio::from(file_handle2);
}
Redirection::ErrorToOutput => {
// 2>&1: Redirect stderr to wherever stdout currently goes
// POSIX processes redirections left-to-right, so at this point
// stdout_file_dup reflects the current stdout target (if redirected)
if let Some(ref f) = stdout_file_dup {
stderr_cfg =
Stdio::from(f.try_clone().context("Failed to duplicate fd for 2>&1")?);
} else {
// stdout is still inherited (terminal), so stderr inherits too
stderr_cfg = Stdio::inherit();
}
}
Redirection::HereDoc {
content,
expand,
strip_tabs,
..
} => {
// Process here document content
let processed =
crate::parser::process_heredoc_content(content, *strip_tabs, *expand, state)?;
// Write heredoc content to a pipe instead of a temp file (avoids
// predictable temp path + symlink attacks entirely).
use std::os::unix::io::FromRawFd;
let mut pipe_fds = [0i32; 2];
// SAFETY: pipe() is a POSIX syscall; pipe_fds is a valid 2-element array.
if unsafe { libc::pipe(pipe_fds.as_mut_ptr()) } != 0 {
anyhow::bail!(
"Failed to create pipe for here document: {}",
std::io::Error::last_os_error()
);
}
// SAFETY: pipe_fds[1] is a valid file descriptor from pipe().
let mut write_end = unsafe { File::from_raw_fd(pipe_fds[1]) };
std::io::Write::write_all(&mut write_end, processed.as_bytes())?;
drop(write_end); // Close write end so reader gets EOF
// SAFETY: pipe_fds[0] is a valid file descriptor from pipe().
let read_end = unsafe { File::from_raw_fd(pipe_fds[0]) };
stdin_cfg = Stdio::from(read_end);
}
Redirection::HereString { content, expand } => {
// Process here string content (always add trailing newline)
let processed = if *expand {
let expanded = crate::parser::expand_with_command_sub(content, state)?;
format!("{}\n", expanded)
} else {
format!("{}\n", content)
};
// Write here string content to a pipe (avoids predictable temp paths).
use std::os::unix::io::FromRawFd;
let mut pipe_fds = [0i32; 2];
// SAFETY: pipe() is a POSIX syscall; pipe_fds is a valid 2-element array.
if unsafe { libc::pipe(pipe_fds.as_mut_ptr()) } != 0 {
anyhow::bail!(
"Failed to create pipe for here string: {}",
std::io::Error::last_os_error()
);
}
// SAFETY: pipe_fds[1] is a valid file descriptor from pipe().
let mut write_end = unsafe { File::from_raw_fd(pipe_fds[1]) };
std::io::Write::write_all(&mut write_end, processed.as_bytes())?;
drop(write_end); // Close write end so reader gets EOF
// SAFETY: pipe_fds[0] is a valid file descriptor from pipe().
let read_end = unsafe { File::from_raw_fd(pipe_fds[0]) };
stdin_cfg = Stdio::from(read_end);
}
}
}
Ok((stdin_cfg, stdout_cfg, stderr_cfg))
}
/// Expand glob patterns in command arguments (Phase 6 M12)
///
/// For each argument:
/// - If it contains glob metacharacters (*, ?, [, {), expand it
/// - If expansion succeeds, use matching paths
/// - If expansion fails or returns empty, use literal pattern (POSIX behavior)
/// - If no metacharacters, use argument as-is
///
/// # POSIX Behavior
/// - Brace expansion happens first: {a,b} -> [a, b]
/// - Then glob expansion: *.txt -> [file1.txt, file2.txt]
/// - Empty matches return literal: "*.xyz" if no .xyz files
///
/// # Examples
/// ```ignore
/// expand_glob_args(&["echo", "*.txt"], state) // -> ["echo", "file1.txt", "file2.txt"]
/// expand_glob_args(&["ls", "file?.rs"], state) // -> ["ls", "file1.rs", "file2.rs"]
/// expand_glob_args(&["rm", "*.xyz"], state) // -> ["rm", "*.xyz"] (no .xyz files)
/// ```
fn expand_glob_args(args: &[String], _state: &ShellState) -> Result<Vec<String>> {
let mut expanded: Vec<String> = Vec::new();
// Get current working directory for glob expansion
let cwd = std::env::current_dir().context("Failed to get current working directory")?;
for arg in args {
// Check if argument contains glob metacharacters
if glob::contains_glob_pattern(arg) {
// First, expand braces: file{1,2}.txt -> [file1.txt, file2.txt]
let brace_expanded = glob::expand_braces(arg);
// Then expand each brace result for glob patterns
let mut glob_matches: Vec<String> = Vec::new();
for pattern in &brace_expanded {
// Expand glob pattern relative to current directory
match glob::expand_glob(pattern, &cwd) {
Ok(matches) if !matches.is_empty() => {
// Found matches - add them as strings
for path in matches {
glob_matches.push(path.to_string_lossy().to_string());
}
}
_ => {
// No matches or error - use literal pattern (POSIX behavior)
glob_matches.push(pattern.clone());
}
}
}
// Add all matches (or literal if no matches)
expanded.extend(glob_matches);
} else {
// No glob pattern - use argument as-is
expanded.push(arg.clone());
}
}
Ok(expanded)
}
/// Handle command exit status, converting signals to exit codes
fn handle_exit_status(status: std::process::ExitStatus) -> Result<i32> {
#[cfg(unix)]
{
use std::os::unix::process::ExitStatusExt;
// Check if terminated by signal
if let Some(signal) = status.signal() {
// Convert Unix signal to shell exit code
// Convention: 128 + signal number
let exit_code = 128 + signal;
return Ok(exit_code);
}
}
// Normal exit code
Ok(status.code().unwrap_or(1))
}
/// Find executable in PATH
fn find_in_path(program: &str) -> Result<PathBuf> {
// If path contains '/', treat as literal path
if program.contains('/') {
let path = PathBuf::from(program);
if path.exists() && is_executable(&path) {
return Ok(path);
}
anyhow::bail!("Command not found: {}", program);
}
// Search PATH
let path_env =
std::env::var("PATH").unwrap_or_else(|_| "/usr/local/bin:/usr/bin:/bin".to_string());
for dir in path_env.split(':') {
let candidate = PathBuf::from(dir).join(program);
if candidate.exists() && is_executable(&candidate) {
return Ok(candidate);
}
}
anyhow::bail!("Command not found: {}", program);
}
/// Check if file is executable
fn is_executable(path: &PathBuf) -> bool {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if let Ok(metadata) = std::fs::metadata(path) {
let perms = metadata.permissions();
return perms.mode() & 0o111 != 0; // Check any execute bit
}
}
#[cfg(not(unix))]
{
// On non-Unix, just check if file exists
let _ = path;
true
}
false
}
/// Execute an external command in the background
///
/// Creates a new process group for the job and adds it to the job table.
/// Does not wait for the command to complete.
///
/// # Arguments
/// * `program` - Program name or path
/// * `args` - Command arguments
/// * `redirects` - I/O redirections
/// * `state` - Shell state for job tracking
///
/// # Returns
/// Job ID for the background job
pub fn execute_external_background(
program: &str,
args: &[String],
redirects: &[Redirection],
state: &mut ShellState,
) -> Result<usize> {
// Setup redirections if any
let redirect_setup = RedirectSetup::setup(redirects, state)?;
// Configure stdio from redirections
let (stdin_cfg, stdout_cfg, stderr_cfg) =
stdio_config_from_redirects(redirects, &redirect_setup, state)?;
// PATH lookup
let executable = find_in_path(program)?;
// Build command string for display
let command_str = if args.is_empty() {
format!("{} &", program)
} else {
format!("{} {} &", program, args.join(" "))
};
// Build command with redirected stdio
let mut command = Command::new(&executable);
command
.args(args)
.stdin(stdin_cfg)
.stdout(stdout_cfg)
.stderr(stderr_cfg);
// Create new process group for job (Unix only)
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
command.process_group(0);
}
// Spawn child process (non-blocking)
let child = command
.spawn()
.context(format!("Failed to spawn: {}", program))?;
let pid = child.id() as i32;
let pgid = pid; // Process becomes its own group leader
// Add job to job table
let job_id = state.jobs.add_job(pgid, command_str, vec![pid]);
// Print job info (bash-style)
println!("[{}] {}", job_id, pid);
// Don't wait for background job - it will run independently
// Job state will be updated by SIGCHLD handler (TODO)
Ok(job_id)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_find_ls() {
let ls = find_in_path("ls");
assert!(ls.is_ok(), "Should find 'ls' in PATH");
if let Ok(ls_path) = ls {
assert!(ls_path.to_string_lossy().contains("ls"));
}
}
#[test]
fn test_not_found() {
assert!(find_in_path("nonexistent-command-xyz").is_err());
}
#[test]
fn test_absolute_path() {
let result = find_in_path("/bin/ls");
// Platform-dependent - may or may not exist
assert!(result.is_ok() || result.is_err());
}
#[test]
fn test_executable_check() {
// Test with a known executable
if let Ok(ls_path) = find_in_path("ls") {
assert!(is_executable(&ls_path), "ls should be executable");
}
}
#[test]
fn test_external_command_success() {
// Test successful command execution
let exit_code = execute_external("true", &[]).unwrap();
assert_eq!(exit_code, 0, "true command should return 0");
}
#[test]
fn test_external_command_failure() {
// Test failed command execution
let exit_code = execute_external("false", &[]).unwrap();
assert_eq!(exit_code, 1, "false command should return 1");
}
#[test]
fn test_external_command_with_args() {
// Test command with arguments
let exit_code = execute_external("echo", &["hello".to_string()]).unwrap();
assert_eq!(exit_code, 0, "echo should return 0");
}
#[test]
fn test_pipeline_simple() {
// Test simple 2-stage pipeline: true | true
use tempfile::TempDir;
let temp = TempDir::new().unwrap();
let mut state = crate::state::ShellState::new(temp.path().to_str().unwrap()).unwrap();
let stages = vec![("true".to_string(), vec![]), ("true".to_string(), vec![])];
let exit_code = execute_pipeline(&stages, &[], &mut state).unwrap();
assert_eq!(exit_code, 0, "true | true should return 0");
}
#[test]
fn test_pipeline_exit_code() {
// Test that pipeline returns exit code from last stage
use tempfile::TempDir;
let temp = TempDir::new().unwrap();
let mut state = crate::state::ShellState::new(temp.path().to_str().unwrap()).unwrap();
let stages = vec![("true".to_string(), vec![]), ("false".to_string(), vec![])];
let exit_code = execute_pipeline(&stages, &[], &mut state).unwrap();
assert_eq!(exit_code, 1, "true | false should return 1 (from false)");
}
#[test]
fn test_pipeline_three_stages() {
// Test 3-stage pipeline
use tempfile::TempDir;
let temp = TempDir::new().unwrap();
let mut state = crate::state::ShellState::new(temp.path().to_str().unwrap()).unwrap();
let stages = vec![
("echo".to_string(), vec!["hello".to_string()]),
("cat".to_string(), vec![]),
("cat".to_string(), vec![]),
];
let exit_code = execute_pipeline(&stages, &[], &mut state).unwrap();
assert_eq!(exit_code, 0, "echo hello | cat | cat should return 0");
}
#[test]
fn test_pipeline_with_redirect() {
// Test pipeline with output redirection
use std::fs;
use tempfile::TempDir;
let temp = TempDir::new().unwrap();
let mut state = crate::state::ShellState::new(temp.path().to_str().unwrap()).unwrap();
let stages = vec![
("echo".to_string(), vec!["test".to_string()]),
("cat".to_string(), vec![]),
];
let redirects = vec![crate::redirection::Redirection::Output {
file: "output.txt".to_string(),
}];
let exit_code = execute_pipeline(&stages, &redirects, &mut state).unwrap();
assert_eq!(exit_code, 0, "Pipeline with redirect should return 0");
// Verify file was created
let output_file = temp.path().join("output.txt");
assert!(output_file.exists(), "Output file should be created");
let content = fs::read_to_string(output_file).unwrap();
assert_eq!(content.trim(), "test", "Output should be 'test'");
}
#[test]
fn test_pipeline_error_empty_stages() {
// Test that empty stages array returns error
use tempfile::TempDir;
let temp = TempDir::new().unwrap();
let mut state = crate::state::ShellState::new(temp.path().to_str().unwrap()).unwrap();
let stages: Vec<(String, Vec<String>)> = vec![];
let result = execute_pipeline(&stages, &[], &mut state);
assert!(result.is_err(), "Empty pipeline should return error");
}
#[test]
fn test_pipeline_single_stage_delegates() {
// Test that single-stage pipeline delegates to execute_external_with_redirects
use tempfile::TempDir;
let temp = TempDir::new().unwrap();
let mut state = crate::state::ShellState::new(temp.path().to_str().unwrap()).unwrap();
let stages = vec![("true".to_string(), vec![])];
let exit_code = execute_pipeline(&stages, &[], &mut state).unwrap();
assert_eq!(exit_code, 0, "Single-stage pipeline should work");
}
}