Skip to content

Commit

Permalink
修复历史命令记录错误 (#40)
Browse files Browse the repository at this point in the history
  • Loading branch information
MemoryShore authored Apr 10, 2024
1 parent a066b0a commit dcf4503
Showing 1 changed file with 12 additions and 11 deletions.
23 changes: 12 additions & 11 deletions src/shell/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ impl fmt::Display for Prompt {
}
}

const DEFAULT_HISTORY_COMMANDS_PATH: &str = "/history_commands.txt";

pub struct Shell {
history_commands: Vec<Rc<RefCell<Vec<u8>>>>,
history_path: String,
Expand All @@ -59,7 +61,7 @@ impl Shell {
pub fn new() -> Shell {
let mut shell = Shell {
history_commands: Vec::new(),
history_path: "history_commands.txt".to_string(),
history_path: DEFAULT_HISTORY_COMMANDS_PATH.to_string(),
printer: Printer::new(&Rc::new(RefCell::new(Vec::new()))),
};
shell.read_commands();
Expand Down Expand Up @@ -90,7 +92,8 @@ impl Shell {
break;
}
let command_bytes = self.printer.buf.borrow().clone();
if !command_bytes.starts_with(&[b' '])
if !command_bytes.is_empty()
&& !command_bytes.starts_with(&[b' '])
&& command_bytes
!= self
.history_commands
Expand All @@ -101,7 +104,7 @@ impl Shell {
{
self.history_commands
.push(Rc::new(RefCell::new(command_bytes.clone())));
self.write_commands();
self.write_commands(&command_bytes);
};
if !command_bytes.iter().all(|&byte| byte == b' ') {
self.exec_commands_in_line(&command_bytes);
Expand Down Expand Up @@ -134,16 +137,14 @@ impl Shell {
self.history_commands = history;
}

fn write_commands(&self) {
fn write_commands(&self, command_bytes: &Vec<u8>) {
let mut file = OpenOptions::new()
.write(true)
.truncate(true)
.open("history_commands.txt")
.append(true)
.open(self.history_path.as_str())
.unwrap();
for command_line in &self.history_commands {
file.write_all(&command_line.borrow()[..]).unwrap();
file.write_all(&[SpecialKeycode::LF.into()]).unwrap();
}
file.write_all(&command_bytes)
.expect("failed to write history command");
file.write_all(&[SpecialKeycode::LF.into()]).unwrap();
}

fn read_char() -> u8 {
Expand Down

0 comments on commit dcf4503

Please sign in to comment.