summaryrefslogtreecommitdiffstats
path: root/src/line.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/line.rs')
-rw-r--r--src/line.rs13
1 files changed, 12 insertions, 1 deletions
diff --git a/src/line.rs b/src/line.rs
index 6b93f06..4989734 100644
--- a/src/line.rs
+++ b/src/line.rs
@@ -1,4 +1,5 @@
1use std::io::{self, IsTerminal, Write}; 1use std::io::{self, IsTerminal, Write};
2use std::os::unix::fs::PermissionsExt;
2use std::path::PathBuf; 3use std::path::PathBuf;
3 4
4use crossterm::cursor::{MoveToColumn, MoveUp}; 5use crossterm::cursor::{MoveToColumn, MoveUp};
@@ -324,7 +325,8 @@ fn history_path() -> PathBuf {
324} 325}
325 326
326fn load_history() -> Vec<String> { 327fn load_history() -> Vec<String> {
327 let text = std::fs::read_to_string(history_path()).unwrap_or_default(); 328 let path = history_path();
329 let text = std::fs::read_to_string(&path).unwrap_or_default();
328 let mut lines: Vec<String> = text 330 let mut lines: Vec<String> = text
329 .split('\n') 331 .split('\n')
330 .filter(|line| !line.trim().is_empty() && !line.starts_with('\u{0}')) 332 .filter(|line| !line.trim().is_empty() && !line.starts_with('\u{0}'))
@@ -332,6 +334,11 @@ fn load_history() -> Vec<String> {
332 .collect(); 334 .collect();
333 if lines.len() > HISTORY_LIMIT { 335 if lines.len() > HISTORY_LIMIT {
334 lines.drain(..lines.len() - HISTORY_LIMIT); 336 lines.drain(..lines.len() - HISTORY_LIMIT);
337 // Keep the file from growing without bound, not just the in-memory list.
338 if lines.len() * 2 < text.lines().count() {
339 let body: Vec<String> = lines.iter().map(|line| line.replace('\n', "\u{0}")).collect();
340 let _ = std::fs::write(&path, format!("{}\n", body.join("\n")));
341 }
335 } 342 }
336 lines 343 lines
337} 344}
@@ -341,11 +348,15 @@ fn append_history(line: &str) {
341 if let Some(parent) = path.parent() { 348 if let Some(parent) = path.parent() {
342 let _ = std::fs::create_dir_all(parent); 349 let _ = std::fs::create_dir_all(parent);
343 } 350 }
351 if let Some(parent) = path.parent() {
352 let _ = std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700));
353 }
344 if let Ok(mut file) = std::fs::OpenOptions::new() 354 if let Ok(mut file) = std::fs::OpenOptions::new()
345 .create(true) 355 .create(true)
346 .append(true) 356 .append(true)
347 .open(&path) 357 .open(&path)
348 { 358 {
359 let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600));
349 // One record per line, so newlines inside a prompt are escaped. 360 // One record per line, so newlines inside a prompt are escaped.
350 let _ = writeln!(file, "{}", line.replace('\n', "\u{0}")); 361 let _ = writeln!(file, "{}", line.replace('\n', "\u{0}"));
351 } 362 }