Compare commits

...

4 commits

4 changed files with 32 additions and 17 deletions

View file

@ -1,15 +1,21 @@
use crate::error;
pub struct ExitCode {
exit_code: u8,
}
pub trait Command {
fn spawn(&self) -> ExitCode;
}
impl ExitCode {
fn new(exit_code: u8) -> Self {
pub fn new(exit_code: u8) -> Self {
Self { exit_code }
}
pub fn get(&self) -> u8 {
self.exit_code
}
}
pub trait Command {
fn spawn(&self) -> ExitCode;
}
pub struct UnixProgram {
@ -32,21 +38,18 @@ impl Command for UnixProgram {
let mut argv = self.argv.clone();
let program = argv.remove(0);
let mut command = std::process::Command::new(program);
let mut command = std::process::Command::new(&program);
command.args(argv);
let handle = command.spawn();
if handle.is_ok() {
let exit_code = match handle
let exit_code = handle
.unwrap()
.wait()
.expect("error waiting for the child")
.code()
{
Some(code) => code,
None => 1,
};
.unwrap_or(1);
let exit_code = match u8::try_from(exit_code) {
Ok(code) => ExitCode::new(code),
@ -55,6 +58,7 @@ impl Command for UnixProgram {
exit_code
} else {
error::print_error(format!("{}: command not found", program));
ExitCode::new(127)
}
}

View file

@ -1,13 +1,15 @@
use crate::command::Command;
use crate::command::UnixProgram;
use crate::command::{Command, ExitCode, UnixProgram};
use crate::interface::{get_user_input, print_prompt};
fn exit() {
fn exit(code: &ExitCode) {
let code = i32::from(code.get());
println!("exit");
std::process::exit(0);
std::process::exit(code);
}
pub fn run() {
let mut current_exit_code = ExitCode::new(0);
loop {
print_prompt();
@ -22,11 +24,11 @@ pub fn run() {
.collect();
if !argv.is_empty() {
UnixProgram::new().argv(argv).spawn();
current_exit_code = UnixProgram::new().argv(argv).spawn();
}
} else {
println!();
exit();
exit(&current_exit_code);
}
}
}

8
src/error.rs Normal file
View file

@ -0,0 +1,8 @@
use std::path::Path;
pub fn print_error(message: String) {
let name = std::env::args().next().unwrap();
let name = Path::new(&name).file_name().unwrap().to_str().unwrap();
eprintln!("{}: {}", name, message);
}

View file

@ -1,5 +1,6 @@
mod command;
mod control;
mod error;
mod interface;
fn main() {