forked from drewwalton19216801/rush-sh
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuiltin_popd.rs
More file actions
85 lines (75 loc) · 2.44 KB
/
builtin_popd.rs
File metadata and controls
85 lines (75 loc) · 2.44 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
use std::env;
use std::io::Write;
use std::path::Path;
use crate::parser::ShellCommand;
use crate::state::ShellState;
fn print_dir_stack(shell_state: &ShellState, writer: &mut dyn Write) {
// Get current directory
if let Ok(current) = std::env::current_dir() {
let current_str = current.to_string_lossy().to_string();
// Print current directory first
let _ = write!(writer, "{}", current_str);
// Then print stack in reverse order (top of stack first)
for dir in shell_state.dir_stack.iter().rev() {
let _ = write!(writer, " {}", dir);
}
let _ = writeln!(writer);
}
}
pub struct PopdBuiltin;
impl super::Builtin for PopdBuiltin {
fn name(&self) -> &'static str {
"popd"
}
fn names(&self) -> Vec<&'static str> {
vec![self.name()]
}
fn description(&self) -> &'static str {
"Pop directory from stack and change to it"
}
fn run(
&self,
_cmd: &ShellCommand,
shell_state: &mut ShellState,
output_writer: &mut dyn Write,
) -> i32 {
if shell_state.dir_stack.is_empty() {
let _ = writeln!(output_writer, "popd: directory stack empty");
1
} else {
// Pop directory from stack
let dir = shell_state.dir_stack.pop().unwrap();
// Change to that directory
if let Err(e) = env::set_current_dir(Path::new(&dir)) {
let _ = writeln!(output_writer, "popd: {}: {}", dir, e);
1
} else {
// Print the stack
print_dir_stack(shell_state, output_writer);
0
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::builtins::Builtin;
#[test]
fn test_execute_builtin_popd() {
let mut shell_state = crate::state::ShellState::new();
shell_state.dir_stack.push("/tmp".to_string());
let cmd = ShellCommand {
args: vec!["popd".to_string()],
redirections: Vec::new(),
compound: None,
};
let builtin = PopdBuiltin;
let mut output = Vec::new();
let exit_code = builtin.run(&cmd, &mut shell_state, &mut output);
assert_eq!(exit_code, 0);
// Should have popped from stack
assert_eq!(shell_state.dir_stack.len(), 0);
// Note: We don't test actual directory change as it may not work in test environment
}
}