Add basic redirection support

This commit is contained in:
pjht 2024-11-24 07:44:03 -06:00
parent e6838b3837
commit 74e0b7876a
Signed by: pjht
GPG Key ID: CA239FC6934E6F3A

View File

@ -1,5 +1,5 @@
use std::{
env::{current_dir, set_current_dir}, io::{self, Write}, path::PathBuf, process::Command
env::{current_dir, set_current_dir}, fs::File, io::{self, Write}, path::PathBuf, process::Command,
};
use clap::Parser;
@ -31,10 +31,21 @@ fn main() {
if line.is_empty() {
continue;
}
let Some(cmd) = shlex::split(line) else {
let Some(mut cmd) = shlex::split(line) else {
println!("Syntax error");
continue;
};
let redirect = if cmd.len() >= 3 {
if cmd[cmd.len() - 2] == ">" {
let redirect = cmd.pop().unwrap();
cmd.pop();
Some(redirect)
} else {
None
}
} else {
None
};
match cmd[0].as_str() {
"pwd" => println!("{}", current_dir().unwrap().to_string_lossy()),
"cd" => {
@ -69,7 +80,19 @@ fn main() {
} else {
format!("/bin/{}", cmd[0])
};
let mut proc = match Command::new(path).args(&cmd[1..]).spawn() {
let mut command = Command::new(path);
command.args(&cmd[1..]);
if let Some(redirect) = redirect {
let redirect = match File::create(&redirect) {
Ok(x) => x,
Err(e) => {
println!("psh: {}: {}", redirect, e);
continue;
}
};
command.stdout(redirect);
}
let mut proc = match command.spawn() {
Ok(x) => x,
Err(e) => {
println!("psh: {}: {}", cmd[0], e);