Compare commits

..

18 commits

Author SHA1 Message Date
142d7211bc Cargo : 0.3.0 -> 0.4.0 2024-04-14 17:21:32 +02:00
ba9340ccb6 parser : mise en commentaire du branchement des backslashes pour éviter tout crash 2024-04-14 17:20:48 +02:00
066530d406 parser : ajout backslash 2024-04-14 17:18:41 +02:00
ddcbf4d7ef parser : prise en compte de ';' 2024-04-14 17:06:51 +02:00
f0f137d18f src : grand remaniement 2024-04-14 16:18:46 +02:00
08b7b57943 builtin : organisation du code 2024-04-14 15:11:52 +02:00
bb5598aee7 parser : prise en compte des simple quotes 2024-04-14 12:40:09 +02:00
04fd13b801 parser : gestion des whitespaces 2024-04-14 12:07:42 +02:00
62b2dd8065 README : ajout case 2024-04-12 10:25:38 +02:00
bb31375d25 command_builder : suppression fonction argv inutile 2024-04-12 10:23:21 +02:00
3fd8e3289d Cargo : passage à la version 0.3.0 2024-04-11 21:38:57 +02:00
8194f61b2c command_sequence : autorisation temporaire de code mort pour la fonction add encore inutilisée 2024-04-11 21:36:37 +02:00
705e11fcab exit_code : ajout d'un nouveau nombre magique success 2024-04-11 21:35:00 +02:00
534de54613 error : print_error attend maintenant &str 2024-04-11 21:34:41 +02:00
47b6985816 command_builder : implémentation des builtins 2024-04-11 21:34:04 +02:00
d094decaf9 Ajout : module command::builtin 2024-04-11 21:33:04 +02:00
fe54c24916 Ajout : patterne CommandBuilder 2024-04-11 19:09:19 +02:00
bf92de25b6 Ajout : module command_builder 2024-04-11 19:07:12 +02:00
12 changed files with 247 additions and 73 deletions

2
Cargo.lock generated
View file

@ -4,4 +4,4 @@ version = 3
[[package]] [[package]]
name = "rash" name = "rash"
version = "0.2.2" version = "0.4.0"

View file

@ -1,6 +1,6 @@
[package] [package]
name = "rash" name = "rash"
version = "0.2.2" version = "0.4.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

@ -17,3 +17,4 @@ I want to learn Rust and see how much effort I can put into making an interopera
- [ ] `type` - [ ] `type`
- [ ] Command-line flags - [ ] Command-line flags
- [ ] PS1 - [ ] PS1
- [ ] Execute code from a file

33
src/command/builtins.rs Normal file
View file

@ -0,0 +1,33 @@
use crate::{error::print_error, exit_code::ExitCode};
use std::env;
use std::{env::set_current_dir, path::PathBuf};
pub 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() {
exit_code = match set_current_dir(path.unwrap()) {
Ok(()) => ExitCode::success(),
Err(_e) => ExitCode::new(2),
};
} else {
exit_code = ExitCode::success();
}
if exit_code.get() != 0 {
print_error("lol");
}
exit_code
}

View file

@ -0,0 +1,26 @@
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

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

View file

@ -1,8 +1,94 @@
mod builtins;
pub mod command_builder;
pub mod command_sequence; pub mod command_sequence;
pub mod unix_program;
use crate::error::print_error;
use crate::exit_code::ExitCode; use crate::exit_code::ExitCode;
type BuiltinFunction = fn(&Vec<String>) -> ExitCode;
#[derive(Debug)]
pub struct NoSuchBuiltinError;
pub trait Command { pub trait Command {
fn spawn(&mut self) -> ExitCode; 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);
if program == "cd" {
Ok(Self {
function: builtins::cd,
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 message = format!(
"{}: command not found",
self.command.get_program().to_str().unwrap()
);
print_error(message.as_str());
ExitCode::not_found()
}
}
}
struct Nothing;
impl Command for Nothing {
fn spawn(&mut self) -> ExitCode {
ExitCode::success()
}
}

View file

@ -1,46 +0,0 @@
use crate::command::Command;
use crate::error::print_error;
use crate::exit_code::ExitCode;
pub struct UnixProgram {
command: std::process::Command,
}
impl UnixProgram {
pub fn new(mut argv: Vec<String>) -> Self {
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 message = format!(
"{}: command not found",
self.command.get_program().to_str().unwrap()
);
print_error(message);
ExitCode::not_found()
}
}
}

View file

@ -1,7 +1,7 @@
use crate::command::Command; use crate::command::Command;
use crate::exit_code::ExitCode; use crate::exit_code::ExitCode;
use crate::interface::{get_user_input, print_prompt}; use crate::interface::{get_user_input, print_prompt};
use crate::parser::parse_command_line; use crate::parser::parse;
fn exit(code: &ExitCode) { fn exit(code: &ExitCode) {
let code = i32::from(code.get()); let code = i32::from(code.get());
@ -17,10 +17,10 @@ pub fn run() {
let user_input = get_user_input(); let user_input = get_user_input();
if user_input.is_some() { if user_input.is_some() {
let command_sequence = parse_command_line(user_input.unwrap()); let mut command_sequence = parse(user_input.unwrap());
if command_sequence.is_some() { if !command_sequence.is_empty() {
current_exit_code = command_sequence.unwrap().spawn(); current_exit_code = command_sequence.spawn();
} }
} else { } else {
println!(); println!();

View file

@ -1,6 +1,6 @@
use std::path::Path; use std::path::Path;
pub fn print_error(message: String) { pub fn print_error(message: &str) {
let name = std::env::args().next().unwrap(); let name = std::env::args().next().unwrap();
let name = Path::new(&name).file_name().unwrap().to_str().unwrap(); let name = Path::new(&name).file_name().unwrap().to_str().unwrap();

View file

@ -14,4 +14,8 @@ impl ExitCode {
pub fn not_found() -> Self { pub fn not_found() -> Self {
Self { exit_code: 127 } Self { exit_code: 127 }
} }
pub fn success() -> Self {
Self { exit_code: 0 }
}
} }

View file

@ -1,15 +1,71 @@
use crate::command::command_builder::CommandBuilder;
use crate::command::command_sequence::CommandSequence; use crate::command::command_sequence::CommandSequence;
use crate::command::unix_program::UnixProgram;
pub fn parse_command_line(line: String) -> Option<CommandSequence> { fn parse_quote(characters: &mut Vec<char>) -> Result<String, UnmatchedQuoteError> {
let argv: Vec<String> = line.split_whitespace().map(|s| s.to_string()).collect(); if characters.is_empty() {
Err(UnmatchedQuoteError)
if !argv.is_empty() {
let command = UnixProgram::new(argv);
let command_sequence = CommandSequence::new(command);
Some(command_sequence)
} else { } else {
None let mut quoted_arg = String::default();
let mut current_char = characters.pop().unwrap();
while !characters.is_empty() && current_char != '\'' {
quoted_arg.push(current_char);
current_char = characters.pop().unwrap();
}
Ok(quoted_arg)
} }
} }
fn parse_main(characters: &mut Vec<char>, current_arg: &mut String) -> Vec<String> {
if characters.is_empty() {
vec![]
} 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::from("")));
argv
} else {
parse_main(characters, current_arg)
}
/*
} else if current_char == '\\' {
current_arg.push(characters.pop().unwrap());
parse_main(characters, current_arg)
*/
} else if current_char == '\'' {
let mut argv = vec![parse_quote(characters).unwrap()];
argv.append(&mut parse_main(characters, &mut String::default()));
argv
} else if current_char == ';' {
vec![]
} else {
current_arg.push(current_char);
parse_main(characters, current_arg)
}
}
}
pub fn parse(line: String) -> 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::default());
if !argv.is_empty() {
let command = CommandBuilder::new(argv).build();
command_sequence.add(command);
}
}
command_sequence
}
#[derive(Debug)]
struct UnmatchedQuoteError;