Compare commits

...

8 commits

11 changed files with 158 additions and 65 deletions

2
Cargo.lock generated
View file

@ -4,4 +4,4 @@ version = 3
[[package]] [[package]]
name = "rash" name = "rash"
version = "0.6.0" version = "0.7.0"

View file

@ -1,6 +1,6 @@
[package] [package]
name = "rash" name = "rash"
version = "0.6.0" version = "0.7.0"
edition = "2021" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

View file

@ -1,11 +1,13 @@
use crate::error; use crate::error;
use crate::error::CdError; use crate::error::CdError;
use crate::error::IllegalNumberError;
use crate::exit_code::ExitCode; use crate::exit_code::ExitCode;
use crate::variables::Variables;
use std::env; use std::env;
use std::{env::set_current_dir, path::PathBuf}; use std::{env::set_current_dir, path::PathBuf};
pub(super) fn cd(args: &Vec<String>) -> ExitCode { pub(super) fn cd(args: &Vec<String>, _variables: &mut Variables, exit_code: &mut ExitCode) {
let path: Option<PathBuf>; let path: Option<PathBuf>;
if !args.is_empty() { if !args.is_empty() {
@ -17,7 +19,7 @@ pub(super) fn cd(args: &Vec<String>) -> ExitCode {
}; };
} }
let mut exit_code = ExitCode::success(); exit_code.set_success();
if path.is_some() { if path.is_some() {
let path = path.unwrap(); let path = path.unwrap();
let result = set_current_dir(&path); let result = set_current_dir(&path);
@ -25,13 +27,55 @@ pub(super) fn cd(args: &Vec<String>) -> ExitCode {
if result.is_err() { if result.is_err() {
let error = CdError::new(&args[0]); let error = CdError::new(&args[0]);
error::print(Box::new(error)); error::print(Box::new(error));
exit_code = ExitCode::new(2); exit_code.set(2);
}
} }
} }
exit_code pub(super) fn colon(_args: &Vec<String>, _variables: &mut Variables, exit_code: &mut ExitCode) {
exit_code.set_success();
} }
pub(super) fn colon(_args: &Vec<String>) -> ExitCode { pub(crate) fn exit(args: &Vec<String>, _variables: &mut Variables, exit_code: &mut ExitCode) {
ExitCode::success() 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()));
}
}
pub(super) fn unset(args: &Vec<String>, variables: &mut Variables, exit_code: &mut ExitCode) {
if !args.is_empty() {
for variable_name in args.iter() {
variables.unset(variable_name);
}
}
exit_code.set_success();
}
pub(super) fn export(args: &Vec<String>, variables: &mut Variables, exit_code: &mut ExitCode) {
for variable in args.iter() {
let assignation: Vec<&str> = variable.split('=').collect();
if assignation.len() == 2 {
variables.set(&assignation[0], &assignation[1]);
}
variables.export(&assignation[0]);
}
exit_code.set_success();
} }

View file

@ -1,5 +1,6 @@
use super::Command; use super::Command;
use crate::exit_code::ExitCode; use crate::exit_code::ExitCode;
use crate::variables::Variables;
pub struct CommandSequence { pub struct CommandSequence {
command: Option<Box<dyn Command>>, command: Option<Box<dyn Command>>,
@ -34,17 +35,16 @@ impl CommandSequence {
} }
impl Command for CommandSequence { impl Command for CommandSequence {
fn spawn(&mut self) -> ExitCode { fn spawn(&mut self, variables: &mut Variables, exit_code: &mut ExitCode) {
let mut exit_code = ExitCode::success();
if self.command.is_some() { if self.command.is_some() {
exit_code = self.command.as_mut().unwrap().spawn(); self.command.as_mut().unwrap().spawn(variables, exit_code);
if self.next_command.is_some() { if self.next_command.is_some() {
exit_code = self.next_command.as_mut().unwrap().spawn(); self.next_command
.as_mut()
.unwrap()
.spawn(variables, exit_code);
} }
} }
exit_code
} }
} }

View file

@ -1,18 +1,19 @@
mod builtins; pub mod builtins;
pub mod command_builder; pub mod command_builder;
pub mod command_sequence; pub mod command_sequence;
use crate::error; use crate::error;
use crate::error::CommandNotFoundError; use crate::error::CommandNotFoundError;
use crate::exit_code::ExitCode; use crate::exit_code::ExitCode;
use crate::variables::Variables;
type BuiltinFunction = fn(&Vec<String>) -> ExitCode; type BuiltinFunction = fn(&Vec<String>, &mut Variables, &mut ExitCode);
#[derive(Debug)] #[derive(Debug)]
pub struct NoSuchBuiltinError; pub struct NoSuchBuiltinError;
pub trait Command { pub trait Command {
fn spawn(&mut self) -> ExitCode; fn spawn(&mut self, variables: &mut Variables, exit_code: &mut ExitCode);
} }
pub struct Builtin { pub struct Builtin {
@ -27,6 +28,9 @@ impl Builtin {
let function: Option<BuiltinFunction> = match program.as_str() { let function: Option<BuiltinFunction> = match program.as_str() {
"cd" => Some(builtins::cd), "cd" => Some(builtins::cd),
"exit" => Some(builtins::exit),
"unset" => Some(builtins::unset),
"export" => Some(builtins::export),
":" => Some(builtins::colon), ":" => Some(builtins::colon),
_ => None, _ => None,
}; };
@ -43,8 +47,8 @@ impl Builtin {
} }
impl Command for Builtin { impl Command for Builtin {
fn spawn(&mut self) -> ExitCode { fn spawn(&mut self, variables: &mut Variables, exit_code: &mut ExitCode) {
(self.function)(&self.args) (self.function)(&self.args, variables, exit_code)
} }
} }
@ -64,27 +68,25 @@ impl UnixProgram {
} }
impl Command for UnixProgram { impl Command for UnixProgram {
fn spawn(&mut self) -> ExitCode { fn spawn(&mut self, _variables: &mut Variables, exit_code: &mut ExitCode) {
let handle = self.command.spawn(); let handle = self.command.spawn();
if handle.is_ok() { if handle.is_ok() {
let exit_code = handle let raw_exit_code = handle
.unwrap() .unwrap()
.wait() .wait()
.expect("error waiting for the child") .expect("error waiting for the child")
.code() .code()
.unwrap_or(1); .unwrap_or(1);
let exit_code = match u8::try_from(exit_code) { exit_code.set(match u8::try_from(raw_exit_code) {
Ok(code) => ExitCode::new(code), Ok(code) => code,
Err(_e) => ExitCode::new(u8::MAX), Err(_e) => u8::MAX,
}; });
exit_code
} else { } else {
let error = CommandNotFoundError::new(self.command.get_program().to_str().unwrap()); let error = CommandNotFoundError::new(self.command.get_program().to_str().unwrap());
error::print(Box::new(error)); error::print(Box::new(error));
ExitCode::not_found() exit_code.set_command_not_found();
} }
} }
} }

View file

@ -1,31 +1,26 @@
use crate::command::builtins;
use crate::command::Command; use crate::command::Command;
use crate::exit_code::ExitCode; use crate::exit_code::ExitCode;
use crate::interface::get_user_input; use crate::interface::get_user_input;
use crate::parser::parse; use crate::parser::parse;
use crate::variables::Variables; use crate::variables::Variables;
fn exit(code: &ExitCode) {
let code = i32::from(code.get());
println!("exit");
std::process::exit(code);
}
pub fn run() { pub fn run() {
let mut current_exit_code = ExitCode::new(0); let mut current_exit_code = ExitCode::new(0);
let mut variables = Variables::new(); let mut variables = Variables::new();
loop { loop {
let user_input = get_user_input(); let user_input = get_user_input("$ ");
if user_input.is_some() { if user_input.is_some() {
let mut command_sequence = parse(user_input.unwrap(), &variables); let mut command_sequence = parse(user_input.unwrap(), &variables);
if !command_sequence.is_empty() { if !command_sequence.is_empty() {
current_exit_code = command_sequence.spawn(); command_sequence.spawn(&mut variables, &mut current_exit_code);
} }
} else { } else {
println!(); println!();
exit(&current_exit_code); builtins::exit(&vec![], &mut variables, &mut current_exit_code);
} }
} }
} }

View file

@ -5,6 +5,7 @@ use std::path::Path;
type Error = Box<dyn Display>; type Error = Box<dyn Display>;
#[derive(Debug)]
pub struct CdError { pub struct CdError {
entry_name: String, entry_name: String,
} }
@ -23,6 +24,7 @@ impl Display for CdError {
} }
} }
#[derive(Debug)]
pub struct CommandNotFoundError { pub struct CommandNotFoundError {
command: String, command: String,
} }
@ -41,6 +43,7 @@ impl Display for CommandNotFoundError {
} }
} }
#[derive(Debug)]
pub struct UnmatchedQuoteError { pub struct UnmatchedQuoteError {
index: usize, 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) { pub fn print(error: Error) {
let name = env::args().next().unwrap_or(String::from("rash")); let name = env::args().next().unwrap_or(String::from("rash"));
let name = Path::new(&name).file_name().unwrap().to_str().unwrap(); let name = Path::new(&name).file_name().unwrap().to_str().unwrap();

View file

@ -11,11 +11,15 @@ impl ExitCode {
self.exit_code self.exit_code
} }
pub fn not_found() -> Self { pub fn set(&mut self, new_code: u8) {
Self { exit_code: 127 } self.exit_code = new_code;
} }
pub fn success() -> Self { pub fn set_success(&mut self) {
Self { exit_code: 0 } self.exit_code = 0;
}
pub fn set_command_not_found(&mut self) {
self.exit_code = 127;
} }
} }

View file

@ -1,13 +1,9 @@
use std::io::Write; use std::io::Write;
use std::io::{stdin, stdout}; use std::io::{stdin, stdout};
fn print_prompt() { pub fn get_user_input(prompt: &str) -> Option<String> {
print!("$ "); print!("{}", prompt);
stdout().flush().unwrap(); stdout().flush().unwrap();
}
pub fn get_user_input() -> Option<String> {
print_prompt();
let mut user_input = String::new(); let mut user_input = String::new();

View file

@ -1,49 +1,73 @@
use crate::command::command_builder::CommandBuilder; use crate::command::command_builder::CommandBuilder;
use crate::command::command_sequence::CommandSequence; use crate::command::command_sequence::CommandSequence;
use crate::interface::get_user_input;
use crate::variables::Variables; use crate::variables::Variables;
use std::collections::VecDeque;
fn parse_variable(characters: &mut Vec<char>, variables: &Variables) -> String { fn parse_variable(characters: &mut VecDeque<char>, variables: &Variables) -> String {
if characters.is_empty() { if characters.is_empty() {
String::new() String::new()
} else { } else {
let mut current_char = characters.pop().unwrap(); let mut current_char = characters.pop_front().unwrap();
let mut var_name = String::new(); let mut var_name = String::new();
while !characters.is_empty() && !current_char.is_whitespace() { while !characters.is_empty() && !current_char.is_whitespace() {
var_name.push(current_char); var_name.push(current_char);
current_char = characters.pop().unwrap(); current_char = characters.pop_front().unwrap();
}
if current_char.is_whitespace() {
characters.push_front(current_char);
} }
variables.get(var_name.as_str()) variables.get(var_name.as_str())
} }
} }
fn parse_quote(characters: &mut Vec<char>) -> String { fn parse_quote(characters: &mut VecDeque<char>) -> String {
let mut quoted = String::new(); let mut quoted = String::new();
if !characters.is_empty() { if !characters.is_empty() {
let mut current_char = characters.pop().unwrap(); let mut current_char = characters.pop_front().unwrap();
while !characters.is_empty() && current_char != '\'' { while current_char != '\'' {
quoted.push(current_char); quoted.push(current_char);
current_char = characters.pop().unwrap();
if characters.is_empty() {
let mut new_characters: VecDeque<char> =
get_user_input("> ").unwrap().chars().collect();
characters.append(&mut new_characters);
}
current_char = characters.pop_front().unwrap();
} }
} }
quoted quoted
} }
fn parse_backslash(characters: &mut Vec<char>) -> String { fn parse_backslash(characters: &mut VecDeque<char>) -> String {
let escaped_char = match characters.is_empty() { let next_character: char;
false => String::from(characters.pop().unwrap()),
true => String::new(),
};
escaped_char if !characters.is_empty() {
next_character = characters.pop_front().unwrap();
if next_character == '\n' {
let mut new_characters: VecDeque<char> =
get_user_input("> ").unwrap().chars().collect();
characters.append(&mut new_characters);
String::new()
} else {
String::from(next_character)
}
} else {
String::new()
}
} }
fn parse_main( fn parse_main(
characters: &mut Vec<char>, characters: &mut VecDeque<char>,
current_arg: &mut String, current_arg: &mut String,
variables: &Variables, variables: &Variables,
) -> Vec<String> { ) -> Vec<String> {
@ -56,7 +80,7 @@ fn parse_main(
last_arg last_arg
} else { } else {
let current_char = characters.pop().unwrap(); let current_char = characters.pop_front().unwrap();
if current_char.is_whitespace() { if current_char.is_whitespace() {
if !current_arg.is_empty() { if !current_arg.is_empty() {
@ -92,7 +116,7 @@ fn parse_main(
} }
pub fn parse(line: String, variables: &Variables) -> CommandSequence { pub fn parse(line: String, variables: &Variables) -> CommandSequence {
let mut characters: Vec<char> = line.chars().rev().collect(); let mut characters: VecDeque<char> = line.chars().collect();
let mut command_sequence = CommandSequence::new(); let mut command_sequence = CommandSequence::new();
while !characters.is_empty() { while !characters.is_empty() {

View file

@ -1,5 +1,5 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::env::{self, args}; use std::env;
pub struct Variables { pub struct Variables {
variables: HashMap<String, String>, variables: HashMap<String, String>,