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]]
name = "rash"
version = "0.6.0"
version = "0.7.0"

View file

@ -1,6 +1,6 @@
[package]
name = "rash"
version = "0.6.0"
version = "0.7.0"
edition = "2021"
# 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::CdError;
use crate::error::IllegalNumberError;
use crate::exit_code::ExitCode;
use crate::variables::Variables;
use std::env;
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>;
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() {
let path = path.unwrap();
let result = set_current_dir(&path);
@ -25,13 +27,55 @@ pub(super) fn cd(args: &Vec<String>) -> ExitCode {
if result.is_err() {
let error = CdError::new(&args[0]);
error::print(Box::new(error));
exit_code = ExitCode::new(2);
exit_code.set(2);
}
}
}
pub(super) fn colon(_args: &Vec<String>, _variables: &mut Variables, exit_code: &mut ExitCode) {
exit_code.set_success();
}
pub(crate) fn exit(args: &Vec<String>, _variables: &mut Variables, 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()));
}
}
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
exit_code.set_success();
}
pub(super) fn colon(_args: &Vec<String>) -> ExitCode {
ExitCode::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 crate::exit_code::ExitCode;
use crate::variables::Variables;
pub struct CommandSequence {
command: Option<Box<dyn Command>>,
@ -34,17 +35,16 @@ impl CommandSequence {
}
impl Command for CommandSequence {
fn spawn(&mut self) -> ExitCode {
let mut exit_code = ExitCode::success();
fn spawn(&mut self, variables: &mut Variables, exit_code: &mut ExitCode) {
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() {
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_sequence;
use crate::error;
use crate::error::CommandNotFoundError;
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)]
pub struct NoSuchBuiltinError;
pub trait Command {
fn spawn(&mut self) -> ExitCode;
fn spawn(&mut self, variables: &mut Variables, exit_code: &mut ExitCode);
}
pub struct Builtin {
@ -27,6 +28,9 @@ impl Builtin {
let function: Option<BuiltinFunction> = match program.as_str() {
"cd" => Some(builtins::cd),
"exit" => Some(builtins::exit),
"unset" => Some(builtins::unset),
"export" => Some(builtins::export),
":" => Some(builtins::colon),
_ => None,
};
@ -43,8 +47,8 @@ impl Builtin {
}
impl Command for Builtin {
fn spawn(&mut self) -> ExitCode {
(self.function)(&self.args)
fn spawn(&mut self, variables: &mut Variables, exit_code: &mut ExitCode) {
(self.function)(&self.args, variables, exit_code)
}
}
@ -64,27 +68,25 @@ impl 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();
if handle.is_ok() {
let exit_code = handle
let raw_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
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));
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::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();
loop {
let user_input = get_user_input();
let user_input = get_user_input("$ ");
if user_input.is_some() {
let mut command_sequence = parse(user_input.unwrap(), &variables);
if !command_sequence.is_empty() {
current_exit_code = command_sequence.spawn();
command_sequence.spawn(&mut variables, &mut current_exit_code);
}
} else {
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>;
#[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();

View file

@ -11,11 +11,15 @@ impl ExitCode {
self.exit_code
}
pub fn not_found() -> Self {
Self { exit_code: 127 }
pub fn set(&mut self, new_code: u8) {
self.exit_code = new_code;
}
pub fn success() -> Self {
Self { exit_code: 0 }
pub fn set_success(&mut self) {
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::{stdin, stdout};
fn print_prompt() {
print!("$ ");
pub fn get_user_input(prompt: &str) -> Option<String> {
print!("{}", prompt);
stdout().flush().unwrap();
}
pub fn get_user_input() -> Option<String> {
print_prompt();
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::interface::get_user_input;
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() {
String::new()
} else {
let mut current_char = characters.pop().unwrap();
let mut current_char = characters.pop_front().unwrap();
let mut var_name = String::new();
while !characters.is_empty() && !current_char.is_whitespace() {
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())
}
}
fn parse_quote(characters: &mut Vec<char>) -> String {
fn parse_quote(characters: &mut VecDeque<char>) -> String {
let mut quoted = String::new();
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);
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
}
fn parse_backslash(characters: &mut Vec<char>) -> String {
let escaped_char = match characters.is_empty() {
false => String::from(characters.pop().unwrap()),
true => String::new(),
};
fn parse_backslash(characters: &mut VecDeque<char>) -> String {
let next_character: char;
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(
characters: &mut Vec<char>,
characters: &mut VecDeque<char>,
current_arg: &mut String,
variables: &Variables,
) -> Vec<String> {
@ -56,7 +80,7 @@ fn parse_main(
last_arg
} else {
let current_char = characters.pop().unwrap();
let current_char = characters.pop_front().unwrap();
if current_char.is_whitespace() {
if !current_arg.is_empty() {
@ -92,7 +116,7 @@ fn parse_main(
}
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();
while !characters.is_empty() {

View file

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