Better history, better prompt

This commit is contained in:
Justine
2022-12-10 13:48:01 +01:00
parent 2cbe00a98b
commit 835772aaa3
4 changed files with 265 additions and 46 deletions

View File

@ -11,31 +11,25 @@ use std::fs::File;
use std::fs::OpenOptions;
use std::fs;
use std::io::{self, prelude::*, BufReader};
use users::{get_user_by_uid, get_current_uid};
use gethostname::gethostname;
//used for home directory
extern crate dirs;
fn process_line(input: String) -> bool {
// must be peekable so we know when we are on the last command
let mut commands = input.trim().split(" | ").peekable();
//Will be used later, in the case of pipes
let mut previous_command = None;
//While have commands to process...
while let Some(command) = commands.next() {
//First command is divided...
let mut parts = command.trim().split_whitespace();
//into a command...
let mut command = parts.next().unwrap();
//and args
let args = parts;
//builtins : exit and cd are special
match command {
"cd" => {
//If a dir is given, we use it by dereferencing
//otherwise it is /
let new_dir = args.peekable().peek().map_or("/", |x| *x);
let root = Path::new(new_dir);
if let Err(e) = env::set_current_dir(&root) {
@ -45,42 +39,28 @@ fn process_line(input: String) -> bool {
previous_command = None;
},
"exit" => return true,
//not builtin: we process it
"history" => {
let stdout = Stdio::inherit();
print_history();
},
command => {
//If we are at the first command (aka previous_command is None)...
let stdin = previous_command.map_or(
//We inherit, meaning stdin gets the stream from its parent
//what I guess that means is that the child (our command)
//inherits the file descriptors (stdin, stdout, stderr)
//from the process of this very own rust program !
Stdio::inherit(),
//otherwise, our input is the output from the last command
//(from converts a ChildStdOut to a Stdio)
|output: Child| Stdio::from(output.stdout.unwrap())
);
let stdout = if commands.peek().is_some() {
// there is another command piped behind this one
// prepare to send output to the next command
Stdio::piped()
} else {
// there are no more commands piped behind this one
// send output to shell stdout
// the child inherits from the parent's file descriptor
Stdio::inherit()
};
//Run the command
let output = Command::new(command)
.args(args)
.stdin(stdin)
.stdout(stdout)
//spawn : execute the command as a child process, returning a handle to it
.spawn();
//Checking for errors
//If it matched, previous_command becomes the output of this to be used
//next loop
match output {
Ok(output) => { previous_command = Some(output); },
Err(e) => {
@ -123,11 +103,21 @@ fn get_history_number() -> Result<i32, std::io::Error> {
let filepath = dirs::home_dir().unwrap().join("history.rshell");
let file = File::open(filepath)?;
let mut reader = BufReader::new(file).lines();
let myline = String::from(reader.last().unwrap()?);
let myline = String::from(reader.last().unwrap_or(Ok(String::from("1")))?);
let mut number = myline.split(' ').next().expect("???").parse().unwrap();
return Ok(number);
}
fn print_history() -> Result<(), std::io::Error> {
let filepath = dirs::home_dir().unwrap().join("history.rshell");
let file = File::open(filepath)?;
let contents = BufReader::new(file).lines();
for line in contents {
println!("{}", line.unwrap());
}
return Ok(());
}
fn get_hist_from_number(number: &i32) -> Option<String> {
//Returns a command from its number in hist file
let filepath = dirs::home_dir().unwrap().join("history.rshell");
@ -159,33 +149,71 @@ fn treat_history_callback(line: &str) -> Option<String> {
get_hist_from_number(&mynbr)
}
fn build_prompt() -> String {
let user = String::from(
get_user_by_uid(get_current_uid())
.unwrap()
.name()
.to_str()
.unwrap()
);
let host = String::from(
gethostname::gethostname()
.to_str()
.unwrap()
);
let current_dir = String::from(
env::current_dir()
.unwrap()
.to_str()
.unwrap()
);
let s = current_dir.split('/');
let dir_last = String::from(
s.last()
.unwrap()
);
let prompt = String::from(format!("[{}@{} in {}] ", user, host, dir_last));
return prompt;
}
fn main(){
loop {
print!("> ");
//stdout().flush();
print!("{}", build_prompt());
stdout().flush();
let mut input = String::new();
stdin().read_line(&mut input).unwrap();
if input.starts_with("!") {
let command_found = treat_history_callback(&input);
match command_found {
Some(c) => {
write_to_history(&c);
process_line(c);
},
None => ()
};
} else {
write_to_history(&input);
if process_line(input) {
return
let bytes = stdin().read_line(&mut input).unwrap();
if (bytes > 0) && (input != String::from("\n")) {
if input.starts_with("!") {
let command_found = treat_history_callback(&input);
match command_found {
Some(c) => {
write_to_history(&c);
process_line(c);
},
None => ()
};
} else {
write_to_history(&input);
if process_line(input) {
return
}
}
} else {
//Command was empty, new line
continue;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@ -226,6 +254,15 @@ mod tests {
assert_eq!(myline.trim(), expected.trim());
}
#[test]
fn test_history_callback() {
inittests();
let expected = String::from("ls");
assert_eq!(treat_history_callback("!1"), Some(expected));
}
}