diff --git a/README.md b/README.md index ce838da..85b4e71 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,8 @@ Later, I can even make something useful out of it. For example, I could make it * Tests for this history system # Todo -* Other tests for the rest of the features (add test for write_history_line) +* 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 builtin ! like in bash * Get some sleep diff --git a/src/main.rs b/src/main.rs index 005c62a..74633cd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -99,7 +99,7 @@ fn process_line(input: String) -> bool { return false; } -fn write_to_history(command: &str, number: &i32) -> Result<(), std::io::Error> { +fn write_to_history(command: &str) -> Result<(), std::io::Error> { //Write a command to history let filepath = dirs::home_dir().unwrap().join("history.rshell"); let mut file = OpenOptions::new() @@ -108,6 +108,12 @@ fn write_to_history(command: &str, number: &i32) -> Result<(), std::io::Error> { .create(true) .open(&filepath) .unwrap(); + + let number = match get_history_number() { + Ok(n) => n + 1, + Err(_) => 1 + }; + writeln!(file, "{} {}", number, command.trim())?; return Ok(()) } @@ -119,7 +125,6 @@ fn get_history_number() -> Result { let mut reader = BufReader::new(file).lines(); let myline = String::from(reader.last().unwrap()?); let mut number = myline.split(' ').next().expect("???").parse().unwrap(); - //number = number + 1; return Ok(number); } @@ -153,12 +158,7 @@ fn main(){ let mut input = String::new(); stdin().read_line(&mut input).unwrap(); - let number = match get_history_number() { - Ok(n) => n + 1, - Err(_) => 1 - }; - - write_to_history(&input, &number); + write_to_history(&input); if process_line(input) { return } @@ -191,10 +191,21 @@ mod tests { assert_eq!(mycmd, String::from("ls")); } - //test add history line - + #[test] + fn test_writehistline() { + inittests(); + let towrite = String::from("pwd"); + write_to_history(&towrite); + //Now check directly against the file + let filepath = dirs::home_dir().unwrap().join("history.rshell"); + let file = File::open(filepath).expect("Error"); + let mut reader = BufReader::new(file).lines(); + let myline = String::from(reader.last().unwrap().expect("Error")); + let expected = String::from("2 pwd"); + assert_eq!(myline.trim(), expected.trim()); + } }