Compare commits

...

14 commits
main ... dev

14 changed files with 273 additions and 188 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.1.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

112
src/command/builtin.rs Normal file
View file

@ -0,0 +1,112 @@
use super::Command;
use crate::error;
use crate::error::CdError;
use crate::error::IllegalNumberError;
use crate::exit_code::ExitCode;
use crate::variables::Variables;
use std::{env::set_current_dir, path::PathBuf};
type BuiltinFunction = fn(&Vec<String>, &mut Variables, &mut ExitCode);
fn cd(args: &Vec<String>, variables: &mut Variables, exit_code: &mut ExitCode) {
let path: Option<PathBuf>;
if !args.is_empty() {
path = Some(PathBuf::from(&args[0]));
} else {
path = match variables.get("HOME").as_str() {
"" => None,
path => Some(PathBuf::from(path)),
};
}
exit_code.set_success();
if path.is_some() {
let path = path.unwrap();
let result = set_current_dir(&path);
if result.is_err() {
let error = CdError::new(&args[0]);
error::print(Box::new(error));
exit_code.set(2);
}
}
}
fn colon(_args: &Vec<String>, _variables: &mut Variables, exit_code: &mut ExitCode) {
exit_code.set_success();
}
fn exit(args: &Vec<String>, _variables: &mut Variables, exit_code: &mut ExitCode) {
if !args.is_empty() {
let raw_exit_code = match args[0].parse::<usize>() {
Ok(parsed) => Ok(u8::try_from(parsed % 256).unwrap()),
Err(_e) => Err(IllegalNumberError::new("exit", args[0].as_str())),
};
if raw_exit_code.is_ok() {
exit_code.set(raw_exit_code.unwrap());
} else {
error::print(Box::new(raw_exit_code.unwrap_err()));
exit_code.set(2);
()
}
}
crate::control::exit(exit_code);
}
fn unset(args: &Vec<String>, variables: &mut Variables, exit_code: &mut ExitCode) {
for variable_name in args.iter() {
variables.unset(variable_name);
}
exit_code.set_success();
}
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();
}
pub struct Builtin {
function: BuiltinFunction,
args: Vec<String>,
}
impl Builtin {
pub fn new(argv: &Vec<String>) -> Result<Self, ()> {
let mut args = argv.clone();
let program = args.remove(0);
let function: Option<BuiltinFunction> = match program.as_str() {
"cd" => Some(cd),
"exit" => Some(exit),
"unset" => Some(unset),
"export" => Some(export),
":" => Some(colon),
_ => None,
};
match function {
Some(function) => Ok(Self { function, args }),
None => Err(()),
}
}
}
impl Command for Builtin {
fn spawn(&mut self, variables: &mut Variables, exit_code: &mut ExitCode) {
(self.function)(&self.args, variables, exit_code)
}
}

View file

@ -1,41 +0,0 @@
use crate::error;
use crate::error::CdError;
use crate::exit_code::ExitCode;
use std::env;
use std::{env::set_current_dir, path::PathBuf};
pub(super) fn cd(args: &Vec<String>) -> ExitCode {
let path: Option<PathBuf>;
if !args.is_empty() {
path = Some(PathBuf::from(&args[0]));
} else {
path = match env::var("HOME") {
Ok(var) => Some(PathBuf::from(var)),
Err(_e) => None,
};
}
let exit_code: ExitCode;
if path.is_some() {
let path = path.unwrap();
let result = set_current_dir(&path);
if result.is_err() {
let error = CdError::new(&args[0]);
error::print(Box::new(error));
exit_code = ExitCode::new(2);
} else {
exit_code = ExitCode::success();
}
} else {
exit_code = ExitCode::success();
}
exit_code
}
pub(super) fn colon(_args: &Vec<String>) -> ExitCode {
ExitCode::success()
}

View file

@ -1,26 +0,0 @@
use super::Builtin;
use super::Command;
use super::UnixProgram;
pub struct CommandBuilder {
argv: Vec<String>,
}
impl CommandBuilder {
pub fn new(argv: Vec<String>) -> Self {
Self { argv }
}
pub fn build(&self) -> Box<dyn Command> {
let builtin = Builtin::new(&self.argv);
let command: Box<dyn Command>;
if builtin.is_err() {
command = Box::from(UnixProgram::new(&self.argv));
} else {
command = Box::from(builtin.unwrap());
}
command
}
}

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,90 +1,35 @@
mod builtins; pub mod builtin;
pub mod command_builder;
pub mod command_sequence; pub mod command_sequence;
pub mod unix_program;
use crate::error;
use crate::error::CommandNotFoundError;
use crate::exit_code::ExitCode; use crate::exit_code::ExitCode;
use crate::variables::Variables;
type BuiltinFunction = fn(&Vec<String>) -> ExitCode; use builtin::Builtin;
use unix_program::UnixProgram;
#[derive(Debug)]
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 CommandBuilder {
function: BuiltinFunction, argv: Vec<String>,
args: Vec<String>,
} }
impl Builtin { impl CommandBuilder {
pub fn new(argv: &Vec<String>) -> Result<Self, NoSuchBuiltinError> { pub fn new(argv: Vec<String>) -> Self {
let mut args = argv.clone(); Self { argv }
let program = args.remove(0); }
let function: Option<BuiltinFunction> = match program.as_str() { pub fn build(&self) -> Box<dyn Command> {
"cd" => Some(builtins::cd), let builtin = Builtin::new(&self.argv);
":" => Some(builtins::colon), let command: Box<dyn Command>;
_ => None,
};
if function.is_some() { if builtin.is_err() {
Ok(Self { command = Box::from(UnixProgram::new(&self.argv));
function: function.unwrap(),
args,
})
} else { } else {
Err(NoSuchBuiltinError) command = Box::from(builtin.unwrap());
}
}
}
impl Command for Builtin {
fn spawn(&mut self) -> ExitCode {
(self.function)(&self.args)
}
}
pub struct UnixProgram {
command: std::process::Command,
}
impl UnixProgram {
pub fn new(argv: &Vec<String>) -> Self {
let mut argv = argv.clone();
let program = argv.remove(0);
let mut command = std::process::Command::new(&program);
command.args(argv);
Self { command }
}
}
impl Command for UnixProgram {
fn spawn(&mut self) -> ExitCode {
let handle = self.command.spawn();
if handle.is_ok() {
let exit_code = handle
.unwrap()
.wait()
.expect("error waiting for the child")
.code()
.unwrap_or(1);
let exit_code = match u8::try_from(exit_code) {
Ok(code) => ExitCode::new(code),
Err(_e) => ExitCode::new(u8::MAX),
};
exit_code
} else {
let error = CommandNotFoundError::new(self.command.get_program().to_str().unwrap());
error::print(Box::new(error));
ExitCode::not_found()
} }
command
} }
} }

View file

@ -0,0 +1,44 @@
use super::Command;
use crate::error;
use crate::error::CommandNotFoundError;
use crate::exit_code::ExitCode;
use crate::variables::Variables;
pub struct UnixProgram {
command: std::process::Command,
}
impl UnixProgram {
pub fn new(argv: &Vec<String>) -> Self {
let mut argv = argv.clone();
let program = argv.remove(0);
let mut command = std::process::Command::new(&program);
command.args(argv);
Self { command }
}
}
impl Command for UnixProgram {
fn spawn(&mut self, _variables: &mut Variables, exit_code: &mut ExitCode) {
let handle = self.command.spawn();
if handle.is_ok() {
let raw_exit_code = handle
.unwrap()
.wait()
.expect("error waiting for the child")
.code()
.unwrap_or(1);
exit_code.set(match u8::try_from(raw_exit_code) {
Ok(code) => code,
Err(_e) => u8::MAX,
});
} else {
let error = CommandNotFoundError::new(self.command.get_program().to_str().unwrap());
error::print(Box::new(error));
exit_code.set_command_not_found();
}
}
}

View file

@ -4,28 +4,27 @@ 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) { pub fn exit(exit_code: &mut ExitCode) {
let code = i32::from(code.get());
println!("exit"); println!("exit");
std::process::exit(code); std::process::exit(i32::from(exit_code.get()));
} }
pub fn run() { pub fn run() {
let mut current_exit_code = ExitCode::new(0); let mut current_exit_code = ExitCode::new();
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); exit(&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

@ -3,19 +3,23 @@ pub struct ExitCode {
} }
impl ExitCode { impl ExitCode {
pub fn new(exit_code: u8) -> Self { pub fn new() -> Self {
Self { exit_code } Self { exit_code: 0 }
} }
pub fn get(&self) -> u8 { pub fn get(&self) -> u8 {
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_sequence::CommandSequence; use crate::command::command_sequence::CommandSequence;
use crate::command::CommandBuilder;
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>,