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

88
Cargo.lock generated
View File

@ -7,6 +7,8 @@ name = "Rshell"
version = "0.1.0"
dependencies = [
"dirs",
"gethostname",
"users",
]
[[package]]
@ -41,6 +43,16 @@ dependencies = [
"winapi",
]
[[package]]
name = "gethostname"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a329e22866dd78b35d2c639a4a23d7b950aeae300dfd79f4fb19f74055c2404"
dependencies = [
"libc",
"windows",
]
[[package]]
name = "getrandom"
version = "0.2.8"
@ -58,6 +70,15 @@ version = "0.2.138"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db6d7e329c562c5dfab7a46a2afabc8b987ab9a4834c9d1ca04dc54c1546cef8"
[[package]]
name = "log"
version = "0.4.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e"
dependencies = [
"cfg-if",
]
[[package]]
name = "proc-macro2"
version = "1.0.47"
@ -133,6 +154,16 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3"
[[package]]
name = "users"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24cc0f6d6f267b73e5a2cadf007ba8f9bc39c6a6f9666f8cf25ea809a153b032"
dependencies = [
"libc",
"log",
]
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
@ -160,3 +191,60 @@ name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windows"
version = "0.43.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04662ed0e3e5630dfa9b26e4cb823b817f1a9addda855d973a9458c236556244"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d2aa71f6f0cbe00ae5167d90ef3cfe66527d6f613ca78ac8024c3ccab9a19e"
[[package]]
name = "windows_aarch64_msvc"
version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd0f252f5a35cac83d6311b2e795981f5ee6e67eb1f9a7f64eb4500fbc4dcdb4"
[[package]]
name = "windows_i686_gnu"
version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fbeae19f6716841636c28d695375df17562ca208b2b7d0dc47635a50ae6c5de7"
[[package]]
name = "windows_i686_msvc"
version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84c12f65daa39dd2babe6e442988fc329d6243fdce47d7d2d155b8d874862246"
[[package]]
name = "windows_x86_64_gnu"
version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf7b1b21b5362cbc318f686150e5bcea75ecedc74dd157d874d754a2ca44b0ed"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09d525d2ba30eeb3297665bd434a54297e4170c7f1a44cad4ef58095b4cd2028"
[[package]]
name = "windows_x86_64_msvc"
version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f40009d85759725a34da6d89a94e63d7bdc50a862acf0dbc7c8e488f1edcb6f5"

View File

@ -3,7 +3,11 @@ name = "Rshell"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[profile.release]
lto = true
codegen-units = 1
[dependencies]
dirs = "4.0.0"
users = "0.11.0"
gethostname = "0.4.1"

View File

@ -22,6 +22,96 @@ Later, I can even make something useful out of it. For example, I could make it
* Add a function that gets the path of the history file, rather than copying it every time
* Other tests for the rest of the features
* Add a builtin history command
* Add a test for the treat_history_callback function
* Get some sleep
* Order the file (modules...)
# Annotated process_line
```rust
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) {
eprintln!("{}", e);
}
previous_command = None;
},
"exit" => return true,
"history" => {
let stdout = Stdio::inherit();
println!("Insert history here");
},
//not builtin: we process it
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) => {
previous_command = None;
eprintln!("{}", e);
},
};
}
}
}
if let Some(mut final_command) = previous_command {
// block until the final command has finished
final_command.wait();
}
return false;
}
```

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));
}
}