Ajout : modules command control et interface

This commit is contained in:
Ahurac 2024-04-09 17:02:54 +02:00
parent 443d5d50a9
commit c55268e0a9
3 changed files with 86 additions and 0 deletions

33
src/command.rs Normal file
View file

@ -0,0 +1,33 @@
use std::process::ExitStatus;
pub trait Command {
fn spawn(&self) -> ExitStatus;
}
pub struct UnixProgram {
argv: Vec<String>,
}
impl UnixProgram {
pub fn new() -> Self {
Self { argv: Vec::new() }
}
pub fn argv(&mut self, argv: Vec<String>) -> &mut Self {
self.argv = argv;
self
}
}
impl Command for UnixProgram {
fn spawn(&self) -> ExitStatus {
let mut argv = self.argv.clone();
let program = argv.remove(0);
let mut command = std::process::Command::new(program);
command.args(argv);
let mut handle = command.spawn().expect("error spawning the command");
handle.wait().expect("error waiting for the child")
}
}

32
src/control.rs Normal file
View file

@ -0,0 +1,32 @@
use crate::command::Command;
use crate::command::UnixProgram;
use crate::interface::{get_user_input, print_prompt};
fn exit() {
println!("exit");
std::process::exit(0);
}
pub fn run() {
loop {
print_prompt();
let user_input = get_user_input();
if user_input.is_some() {
let user_input = user_input.unwrap();
let argv: Vec<String> = user_input
.split_whitespace()
.map(|s| s.to_string())
.collect();
if !argv.is_empty() {
UnixProgram::new().argv(argv).spawn();
}
} else {
println!();
exit();
}
}
}

21
src/interface.rs Normal file
View file

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