Compare commits

..

16 commits

14 changed files with 1 additions and 543 deletions

7
Cargo.lock generated
View file

@ -1,7 +0,0 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "rash"
version = "0.6.0"

View file

@ -1,8 +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
[dependencies] [dependencies]

View file

@ -3,21 +3,3 @@
# Why? # Why?
I want to learn Rust and see how much effort I can put into making an interoperable software. I want to learn Rust and see how much effort I can put into making an interoperable software.
# Roadmap
- [x] Execute commands
- [x] Parse commands
- [ ] Variables
- [ ] Environment variables
- [ ] Builtins
- [x] `cd`
- [x] `:`
- [ ] `set`
- [ ] `alias`
- [ ] `type`
- [ ] Command-line flags
- [ ] PS1
- [ ] Execute code from a file
- [ ] Clean error handling
- [ ] Override Ctrl-C

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,50 +0,0 @@
use super::Command;
use crate::exit_code::ExitCode;
pub struct CommandSequence {
command: Option<Box<dyn Command>>,
next_command: Option<Box<CommandSequence>>,
}
impl CommandSequence {
pub fn new() -> Self {
Self {
command: None,
next_command: None,
}
}
pub fn add(&mut self, command: Box<dyn Command>) {
if self.command.is_none() {
self.command = Some(command);
} else if self.next_command.is_none() {
let new_command = Self {
command: Some(command),
next_command: None,
};
self.next_command = Some(Box::new(new_command));
} else {
self.next_command.as_mut().unwrap().add(command);
}
}
pub fn is_empty(&self) -> bool {
self.command.is_none()
}
}
impl Command for CommandSequence {
fn spawn(&mut self) -> ExitCode {
let mut exit_code = ExitCode::success();
if self.command.is_some() {
exit_code = self.command.as_mut().unwrap().spawn();
if self.next_command.is_some() {
exit_code = self.next_command.as_mut().unwrap().spawn();
}
}
exit_code
}
}

View file

@ -1,90 +0,0 @@
mod builtins;
pub mod command_builder;
pub mod command_sequence;
use crate::error;
use crate::error::CommandNotFoundError;
use crate::exit_code::ExitCode;
type BuiltinFunction = fn(&Vec<String>) -> ExitCode;
#[derive(Debug)]
pub struct NoSuchBuiltinError;
pub trait Command {
fn spawn(&mut self) -> ExitCode;
}
pub struct Builtin {
function: BuiltinFunction,
args: Vec<String>,
}
impl Builtin {
pub fn new(argv: &Vec<String>) -> Result<Self, NoSuchBuiltinError> {
let mut args = argv.clone();
let program = args.remove(0);
let function: Option<BuiltinFunction> = match program.as_str() {
"cd" => Some(builtins::cd),
":" => Some(builtins::colon),
_ => None,
};
if function.is_some() {
Ok(Self {
function: function.unwrap(),
args,
})
} else {
Err(NoSuchBuiltinError)
}
}
}
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()
}
}
}

View file

@ -1,31 +0,0 @@
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();
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();
}
} else {
println!();
exit(&current_exit_code);
}
}
}

View file

@ -1,59 +0,0 @@
use std::env;
use std::fmt;
use std::fmt::{Display, Formatter};
use std::path::Path;
type Error = Box<dyn Display>;
pub struct CdError {
entry_name: String,
}
impl CdError {
pub fn new(entry_name: &str) -> Self {
Self {
entry_name: String::from(entry_name),
}
}
}
impl Display for CdError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "cd: no such directory as '{}'", self.entry_name)
}
}
pub struct CommandNotFoundError {
command: String,
}
impl CommandNotFoundError {
pub fn new(command: &str) -> Self {
Self {
command: String::from(command),
}
}
}
impl Display for CommandNotFoundError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}: command not found", self.command)
}
}
pub struct UnmatchedQuoteError {
index: usize,
}
impl Display for UnmatchedQuoteError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "unmatched quote at character {}", self.index)
}
}
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();
eprintln!("{}: {}", name, error);
}

View file

@ -1,21 +0,0 @@
pub struct ExitCode {
exit_code: u8,
}
impl ExitCode {
pub fn new(exit_code: u8) -> Self {
Self { exit_code }
}
pub fn get(&self) -> u8 {
self.exit_code
}
pub fn not_found() -> Self {
Self { exit_code: 127 }
}
pub fn success() -> Self {
Self { exit_code: 0 }
}
}

View file

@ -1,22 +0,0 @@
use std::io::Write;
use std::io::{stdin, stdout};
fn print_prompt() {
print!("$ ");
stdout().flush().unwrap();
}
pub fn get_user_input() -> Option<String> {
print_prompt();
let mut user_input = String::new();
let bytes_read = stdin()
.read_line(&mut user_input)
.expect("error reading user input");
match bytes_read {
0 => None,
_ => Some(user_input),
}
}

View file

@ -1,11 +0,0 @@
mod command;
mod control;
mod error;
mod exit_code;
mod interface;
mod parser;
mod variables;
fn main() {
control::run();
}

View file

@ -1,108 +0,0 @@
use crate::command::command_builder::CommandBuilder;
use crate::command::command_sequence::CommandSequence;
use crate::variables::Variables;
fn parse_variable(characters: &mut Vec<char>, variables: &Variables) -> String {
if characters.is_empty() {
String::new()
} else {
let mut current_char = characters.pop().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();
}
variables.get(var_name.as_str())
}
}
fn parse_quote(characters: &mut Vec<char>) -> String {
let mut quoted = String::new();
if !characters.is_empty() {
let mut current_char = characters.pop().unwrap();
while !characters.is_empty() && current_char != '\'' {
quoted.push(current_char);
current_char = characters.pop().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(),
};
escaped_char
}
fn parse_main(
characters: &mut Vec<char>,
current_arg: &mut String,
variables: &Variables,
) -> Vec<String> {
if characters.is_empty() {
let mut last_arg = vec![];
if !current_arg.is_empty() {
last_arg.push(current_arg.clone());
}
last_arg
} else {
let current_char = characters.pop().unwrap();
if current_char.is_whitespace() {
if !current_arg.is_empty() {
let mut argv: Vec<String> = vec![current_arg.clone()];
argv.append(&mut parse_main(characters, &mut String::new(), variables));
argv
} else {
parse_main(characters, current_arg, variables)
}
} else if current_char == '\\' {
current_arg.push_str(parse_backslash(characters).as_str());
parse_main(characters, current_arg, variables)
} else if current_char == '$' {
current_arg.push_str(parse_variable(characters, variables).as_str());
parse_main(characters, current_arg, variables)
} else if current_char == '\'' {
current_arg.push_str(parse_quote(characters).as_str());
parse_main(characters, current_arg, variables)
} else if current_char == ';' {
let mut argv: Vec<String> = vec![];
if !current_arg.is_empty() {
argv.push(current_arg.clone());
}
argv
} else {
current_arg.push(current_char);
parse_main(characters, current_arg, variables)
}
}
}
pub fn parse(line: String, variables: &Variables) -> CommandSequence {
let mut characters: Vec<char> = line.chars().rev().collect();
let mut command_sequence = CommandSequence::new();
while !characters.is_empty() {
let argv = parse_main(&mut characters, &mut String::new(), variables);
if !argv.is_empty() {
let command = CommandBuilder::new(argv).build();
command_sequence.add(command);
}
}
command_sequence
}

View file

@ -1,56 +0,0 @@
use std::collections::HashMap;
use std::env::{self, args};
pub struct Variables {
variables: HashMap<String, String>,
}
impl Variables {
pub fn new() -> Self {
Self {
variables: HashMap::new(),
}
}
pub fn get(&self, key: &str) -> String {
let arg_index = String::from(key).parse::<usize>();
match arg_index {
Ok(index) => match env::args().nth(index) {
Some(value) => value,
None => String::new(),
},
Err(_e) => match self.variables.get(key) {
Some(value) => value.clone(),
None => match env::var(key) {
Ok(value) => value,
Err(_e) => String::new(),
},
},
}
}
pub fn unset(&mut self, key: &str) {
let old_value = self.variables.remove(key);
if old_value.is_none() {
env::remove_var(key);
}
}
pub fn set(&mut self, key: &str, value: &str) {
self.variables
.insert(String::from(key), String::from(value));
}
pub fn export(&mut self, key: &str) {
let var_to_export = self.variables.get(key);
if var_to_export.is_some() {
env::set_var(key, var_to_export.unwrap());
self.variables.remove(key);
} else {
env::set_var(key, "");
}
}
}