Merge pull request 'feature/error_handling' (#8) from feature/error_handling into main

Reviewed-on: https://gitea.ahur.ac/ahurac/rash/pulls/8
This commit is contained in:
Ahurac 2023-12-13 19:45:01 +01:00
commit b6b1ad629d
4 changed files with 23 additions and 2 deletions

View file

@ -21,3 +21,4 @@
- [ ] Positional variables - [ ] Positional variables
- [ ] `RANDOM` - [ ] `RANDOM`
- [ ] Handle signals - [ ] Handle signals
- [x] Handle when command is not found

View file

@ -2,6 +2,7 @@ use std::io as stdio;
use stdio::stdin; use stdio::stdin;
use crate::parser; use crate::parser;
use crate::job; use crate::job;
use crate::error::command_not_found;
pub struct Buffer { pub struct Buffer {
buffer: String, buffer: String,
@ -34,6 +35,7 @@ impl Buffer {
pub fn try_spawn(&mut self) -> Option<i32> { pub fn try_spawn(&mut self) -> Option<i32> {
if ! self.buffer.is_empty() { if ! self.buffer.is_empty() {
self.argv = parser::parse(&self.buffer); self.argv = parser::parse(&self.buffer);
let command_name = self.argv[0].to_string();
let result = job::execute(&mut self.argv); let result = job::execute(&mut self.argv);
if result.is_ok() { if result.is_ok() {
@ -43,8 +45,7 @@ impl Buffer {
return Some(result.code().unwrap()); return Some(result.code().unwrap());
} }
} else { } else {
eprintln!("{}", result.unwrap_err()); return Some(command_not_found(&command_name));
return Some(127);
} }
} }

18
src/error.rs Normal file
View file

@ -0,0 +1,18 @@
use std::env;
use std::path::Path;
fn error(message: &str) {
let argv0: String = env::args().next().unwrap();
let program_name = Path::new(&argv0)
.file_name()
.unwrap()
.to_str()
.unwrap();
eprintln!("{}: {}", program_name, message);
}
pub fn command_not_found(command: &String) -> i32 {
let message = command.to_owned() + ": command not found";
error(&message);
127
}

View file

@ -2,6 +2,7 @@ mod buffer;
mod parser; mod parser;
mod job; mod job;
mod variables; mod variables;
mod error;
use std::process::exit; use std::process::exit;
use variables::Variables; use variables::Variables;