|
| 1 | +//SPDXFileCopyrightText: 2024 Ryuichi Ueda ryuichiueda@gmail.com |
| 2 | +//SPDXLicense-Identifier: BSD-3-Clause |
| 3 | + |
| 4 | +use crate::ShellCore; |
| 5 | +use rev_lines::RevLines; |
| 6 | +use std::fs::File; |
| 7 | +use std::io::{BufReader, BufWriter, Write}; |
| 8 | +use std::fs::OpenOptions; |
| 9 | + |
| 10 | +impl ShellCore { |
| 11 | + pub fn fetch_history(&mut self, pos: usize, prev: usize, prev_str: String) -> String { |
| 12 | + if prev < self.history.len() { |
| 13 | + self.history[prev] = prev_str; |
| 14 | + }else{ |
| 15 | + self.rewritten_history.insert(prev + 1 - self.history.len(), prev_str); |
| 16 | + } |
| 17 | + |
| 18 | + if pos < self.history.len() { |
| 19 | + self.history[pos].clone() |
| 20 | + }else{ |
| 21 | + self.fetch_history_file(pos + 1 - self.history.len()) |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + pub fn fetch_history_file(&mut self, pos: usize) -> String { |
| 26 | + if let Some(s) = self.rewritten_history.get(&pos) { |
| 27 | + return s.to_string(); |
| 28 | + } |
| 29 | + if pos == 0 { |
| 30 | + return String::new(); |
| 31 | + } |
| 32 | + |
| 33 | + let mut file_line = pos - 1; |
| 34 | + if let Ok(n) = self.data.get_param("HISTFILESIZE").parse::<usize>() { |
| 35 | + file_line %= n; |
| 36 | + } |
| 37 | + |
| 38 | + if let Ok(hist_file) = File::open(self.data.get_param("HISTFILE")){ |
| 39 | + let mut rev_lines = RevLines::new(BufReader::new(hist_file)); |
| 40 | + if let Some(Ok(s)) = rev_lines.nth(file_line) { |
| 41 | + return s; |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + String::new() |
| 46 | + } |
| 47 | + |
| 48 | + pub fn write_history_to_file(&mut self) { |
| 49 | + if ! self.data.flags.contains('i') || self.is_subshell { |
| 50 | + return; |
| 51 | + } |
| 52 | + let filename = self.data.get_param("HISTFILE"); |
| 53 | + if filename == "" { |
| 54 | + eprintln!("sush: HISTFILE is not set"); |
| 55 | + return; |
| 56 | + } |
| 57 | + |
| 58 | + let file = match OpenOptions::new().create(true) |
| 59 | + .write(true).append(true).open(&filename) { |
| 60 | + Ok(f) => f, |
| 61 | + _ => { |
| 62 | + eprintln!("sush: invalid history file"); |
| 63 | + return; |
| 64 | + }, |
| 65 | + }; |
| 66 | + |
| 67 | + let mut f = BufWriter::new(file); |
| 68 | + for h in self.history.iter().rev() { |
| 69 | + if h == "" { |
| 70 | + continue; |
| 71 | + } |
| 72 | + let _ = f.write(h.as_bytes()); |
| 73 | + let _ = f.write(&vec![0x0A]); |
| 74 | + } |
| 75 | + let _ = f.flush(); |
| 76 | + } |
| 77 | +} |
0 commit comments