builtins : ajout exit

This commit is contained in:
Ahurac 2024-04-19 11:03:49 +02:00
parent 74fb3573be
commit 8906ac7c70
4 changed files with 53 additions and 8 deletions

View file

@ -1,5 +1,6 @@
use crate::error;
use crate::error::CdError;
use crate::error::IllegalNumberError;
use crate::exit_code::ExitCode;
use std::env;
@ -33,3 +34,23 @@ pub(super) fn cd(args: &Vec<String>, exit_code: &mut ExitCode) {
pub(super) fn colon(_args: &Vec<String>, exit_code: &mut ExitCode) {
exit_code.set_success();
}
pub(crate) fn exit(args: &Vec<String>, exit_code: &mut ExitCode) {
let raw_exit_code: Result<i32, IllegalNumberError>;
if args.is_empty() {
raw_exit_code = Ok(i32::from(exit_code.get()));
} else {
raw_exit_code = match args[0].parse::<usize>() {
Ok(parsed) => Ok(i32::try_from(parsed % 256).unwrap()),
Err(_e) => Err(IllegalNumberError::new("exit", args[0].as_str())),
};
}
if raw_exit_code.is_ok() {
println!("exit");
std::process::exit(raw_exit_code.unwrap());
} else {
error::print(Box::new(raw_exit_code.unwrap_err()));
}
}

View file

@ -1,4 +1,4 @@
mod builtins;
pub mod builtins;
pub mod command_builder;
pub mod command_sequence;
@ -27,6 +27,7 @@ impl Builtin {
let function: Option<BuiltinFunction> = match program.as_str() {
"cd" => Some(builtins::cd),
"exit" => Some(builtins::exit),
":" => Some(builtins::colon),
_ => None,
};

View file

@ -1,15 +1,10 @@
use crate::command::builtins;
use crate::command::Command;
use crate::exit_code::ExitCode;
use crate::interface::get_user_input;
use crate::parser::parse;
use crate::variables::Variables;
fn exit(code: &ExitCode) {
let code = i32::from(code.get());
println!("exit");
std::process::exit(code);
}
pub fn run() {
let mut current_exit_code = ExitCode::new(0);
let mut variables = Variables::new();
@ -25,7 +20,7 @@ pub fn run() {
}
} else {
println!();
exit(&current_exit_code);
builtins::exit(&vec![], &mut current_exit_code);
}
}
}

View file

@ -5,6 +5,7 @@ use std::path::Path;
type Error = Box<dyn Display>;
#[derive(Debug)]
pub struct CdError {
entry_name: String,
}
@ -23,6 +24,7 @@ impl Display for CdError {
}
}
#[derive(Debug)]
pub struct CommandNotFoundError {
command: String,
}
@ -41,6 +43,7 @@ impl Display for CommandNotFoundError {
}
}
#[derive(Debug)]
pub struct UnmatchedQuoteError {
index: usize,
}
@ -51,6 +54,31 @@ impl Display for UnmatchedQuoteError {
}
}
#[derive(Debug)]
pub struct IllegalNumberError {
command_invoked: String,
illegal_number: String,
}
impl IllegalNumberError {
pub fn new(command_invoked: &str, illegal_number: &str) -> Self {
Self {
command_invoked: String::from(command_invoked),
illegal_number: String::from(illegal_number),
}
}
}
impl Display for IllegalNumberError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(
f,
"{}: '{}' is not a valid number",
self.command_invoked, self.illegal_number
)
}
}
pub fn print(error: Error) {
let name = env::args().next().unwrap_or(String::from("rash"));
let name = Path::new(&name).file_name().unwrap().to_str().unwrap();