use std::io::Write;
use std::path::{Path, PathBuf};
pub const HISTORY_MAX: usize = 10_000;
fn canon_host(h: &str) -> &str {
if h.is_empty() || h.eq_ignore_ascii_case("localhost") || is_local_hostname(h) {
""
} else {
h
}
}
pub fn is_local_host(h: &str) -> bool {
canon_host(h).is_empty()
}
fn is_local_hostname(h: &str) -> bool {
static LOCAL: std::sync::OnceLock<String> = std::sync::OnceLock::new();
let local = LOCAL.get_or_init(|| {
let mut buf = [0u8; 256];
let ok = unsafe { libc::gethostname(buf.as_mut_ptr().cast(), buf.len()) } == 0;
if !ok {
return String::new();
}
let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
String::from_utf8_lossy(&buf[..end]).to_string()
});
if local.is_empty() {
return false;
}
let norm = |s: &str| {
let s = s.to_ascii_lowercase();
s.strip_suffix(".local").map(String::from).unwrap_or(s)
};
let h_n = norm(h);
let l_n = norm(local);
if h_n == l_n {
return true;
}
!h_n.contains('.') && Some(h_n.as_str()) == l_n.split('.').next()
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct HistoryEntry {
pub cmd: String,
#[serde(default)]
pub cwd: String,
#[serde(default)]
pub host: String,
#[serde(default)]
pub exit: Option<i32>,
#[serde(default)]
pub dur_ms: u64,
#[serde(default)]
pub ts: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum HistoryScope {
#[default]
All,
Dir,
Failed,
}
impl HistoryScope {
pub fn next(self) -> Self {
match self {
Self::All => Self::Dir,
Self::Dir => Self::Failed,
Self::Failed => Self::All,
}
}
}
pub fn history_path() -> PathBuf {
crate::paths::config_dir().join("command_history.jsonl")
}
pub struct CommandHistory {
path: PathBuf,
pub entries: Vec<HistoryEntry>,
disk_lines: usize,
}
impl CommandHistory {
pub fn load(path: &Path) -> Self {
let raw = std::fs::read_to_string(path).unwrap_or_default();
let mut entries: Vec<HistoryEntry> = raw
.lines()
.filter_map(|l| serde_json::from_str(l).ok())
.collect();
let disk_lines = entries.len();
if entries.len() > HISTORY_MAX {
let drop = entries.len() - HISTORY_MAX;
entries.drain(..drop);
}
Self {
path: path.to_path_buf(),
entries,
disk_lines,
}
}
#[cfg_attr(not(test), allow(dead_code))]
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn append(&mut self, entry: HistoryEntry) {
if entry.cmd.trim().is_empty() {
return;
}
let line = match serde_json::to_string(&entry) {
Ok(l) => l,
Err(_) => return,
};
self.entries.push(entry);
if self.entries.len() > HISTORY_MAX {
let drop = self.entries.len() - HISTORY_MAX;
self.entries.drain(..drop);
}
self.disk_lines += 1;
if self.disk_lines > HISTORY_MAX * 2 {
self.rewrite();
return;
}
if let Some(dir) = self.path.parent() {
let _ = std::fs::create_dir_all(dir);
}
if let Ok(mut f) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&self.path)
{
let _ = writeln!(f, "{line}");
}
}
fn rewrite(&mut self) {
let mut out = String::new();
for e in &self.entries {
if let Ok(l) = serde_json::to_string(e) {
out.push_str(&l);
out.push('\n');
}
}
if let Some(dir) = self.path.parent() {
let _ = std::fs::create_dir_all(dir);
}
let _ = std::fs::write(&self.path, out);
self.disk_lines = self.entries.len();
}
pub fn suggest(&self, typed: &str, cwd: &str, host: &str) -> Option<&str> {
if typed.trim().is_empty() {
return None;
}
let extends = |e: &&HistoryEntry| e.cmd.len() > typed.len() && e.cmd.starts_with(typed);
let ok = |e: &&HistoryEntry| e.exit.is_none_or(|c| c == 0);
let here = |e: &&HistoryEntry| e.cwd == cwd && canon_host(&e.host) == canon_host(host);
let newest = || self.entries.iter().rev().filter(extends);
newest()
.find(|e| ok(e) && here(e))
.or_else(|| newest().find(ok))
.or_else(|| newest().next())
.map(|e| e.cmd.as_str())
}
pub fn search(
&self,
query: &str,
scope: HistoryScope,
cwd: &str,
host: &str,
) -> Vec<HistoryEntry> {
let q = query.to_lowercase();
let mut seen = std::collections::HashSet::new();
let mut out = Vec::new();
for e in self.entries.iter().rev() {
match scope {
HistoryScope::All => {}
HistoryScope::Dir => {
if e.cwd != cwd || canon_host(&e.host) != canon_host(host) {
continue;
}
}
HistoryScope::Failed => {
if e.exit == Some(0) {
continue;
}
}
}
if !q.is_empty() && !e.cmd.to_lowercase().contains(&q) {
continue;
}
if seen.insert(e.cmd.clone()) {
out.push(e.clone());
}
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn entry(cmd: &str, cwd: &str, exit: Option<i32>, ts: u64) -> HistoryEntry {
HistoryEntry {
cmd: cmd.to_string(),
cwd: cwd.to_string(),
host: String::new(),
exit,
dur_ms: 42,
ts,
}
}
fn store(entries: Vec<HistoryEntry>) -> CommandHistory {
CommandHistory {
path: PathBuf::from("/dev/null"),
entries,
disk_lines: 0,
}
}
#[test]
fn a_suggestion_prefers_success_in_this_directory_then_success_then_any() {
let h = store(vec![
entry("cargo test --lib", "/p", Some(0), 1),
entry("cargo test --doc", "/other", Some(0), 2),
entry("cargo test --broken", "/p", Some(101), 3),
]);
assert_eq!(h.suggest("cargo t", "/p", ""), Some("cargo test --lib"));
assert_eq!(
h.suggest("cargo t", "/elsewhere", ""),
Some("cargo test --doc"),
"the newest success anywhere"
);
let failed_only = store(vec![entry("make fail", "/p", Some(2), 1)]);
assert_eq!(
failed_only.suggest("make", "/p", ""),
Some("make fail"),
"then any"
);
}
#[test]
fn nothing_is_suggested_for_blank_input_or_an_exact_match() {
let h = store(vec![entry("ls -la", "/p", Some(0), 1)]);
assert_eq!(h.suggest("", "/p", ""), None);
assert_eq!(h.suggest("ls -la", "/p", ""), None, "nothing left to add");
assert_eq!(h.suggest("git", "/p", ""), None);
}
#[test]
fn a_remote_fqdn_sharing_the_short_name_is_not_local() {
let out = std::process::Command::new("hostname").output().unwrap();
let local = String::from_utf8_lossy(&out.stdout).trim().to_string();
if local.is_empty() {
return;
}
let first = local.split('.').next().unwrap().to_string();
assert!(
!is_local_host(&format!("{first}.remote.example")),
"an unrelated FQDN sharing the first label is another machine"
);
assert!(is_local_host(&local), "the machine's own name is local");
assert!(is_local_host(&first), "the bare short name is local");
assert!(
is_local_host(&format!("{first}.local")),
"the mDNS spelling is local"
);
assert!(
is_local_host(&first.to_uppercase()),
"hostname comparison is case-insensitive"
);
}
#[test]
fn dir_scope_separates_hosts_sharing_a_path() {
let tmp = tempfile::tempdir().unwrap();
let mut h = CommandHistory::load(&tmp.path().join("h.jsonl"));
h.append(entry("local-build", "/x", Some(0), 1));
let mut remote = entry("remote-build", "/x", Some(0), 2);
remote.host = String::from("prod-box");
h.append(remote);
let local = h.search("", HistoryScope::Dir, "/x", "");
assert_eq!(local.len(), 1, "only the local /x command");
assert_eq!(local[0].cmd, "local-build");
let remote = h.search("", HistoryScope::Dir, "/x", "prod-box");
assert_eq!(remote.len(), 1, "only the remote /x command");
assert_eq!(remote[0].cmd, "remote-build");
let mut shimmed = entry("shimmed-build", "/x", Some(0), 3);
shimmed.host = String::from("localhost");
h.append(shimmed);
let seen = h.search("", HistoryScope::Dir, "/x", "localhost");
let cmds: Vec<&str> = seen.iter().map(|e| e.cmd.as_str()).collect();
assert!(
cmds.contains(&"local-build") && cmds.contains(&"shimmed-build"),
"legacy and shim-reported local entries are one history: {cmds:?}"
);
assert!(!cmds.contains(&"remote-build"));
let re = CommandHistory::load(&h.path);
let back = re.entries.iter().find(|e| e.cmd == "remote-build").unwrap();
assert_eq!(back.host, "prod-box", "the host survives the reload");
let legacy: HistoryEntry =
serde_json::from_str(r#"{"cmd":"old","cwd":"/x","exit":0,"dur_ms":1,"ts":1}"#).unwrap();
assert_eq!(legacy.host, "", "a pre-host record defaults to local");
}
#[test]
fn append_persists_and_load_round_trips() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("h.jsonl");
let mut h = CommandHistory::load(&path);
assert!(h.is_empty());
h.append(entry("cargo test", "/repo", Some(0), 100));
h.append(entry("ls -la", "/tmp", Some(0), 101));
h.append(entry(" ", "/tmp", Some(0), 102)); let re = CommandHistory::load(&path);
assert_eq!(re.entries.len(), 2, "blank commands are never recorded");
assert_eq!(re.entries[0].cmd, "cargo test");
assert_eq!(re.entries[1].cwd, "/tmp");
std::fs::write(
&path,
format!(
"not json at all\n{}\n",
serde_json::to_string(&entry("ok", "/x", Some(1), 103)).unwrap()
),
)
.unwrap();
let re = CommandHistory::load(&path);
assert_eq!(re.entries.len(), 1);
assert_eq!(re.entries[0].cmd, "ok");
}
#[test]
fn search_dedups_newest_first_and_honours_scopes() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("h.jsonl");
let mut h = CommandHistory::load(&path);
h.append(entry("cargo test", "/repo", Some(0), 1));
h.append(entry("cargo build", "/repo", Some(101), 2));
h.append(entry("ls", "/tmp", Some(0), 3));
h.append(entry("cargo test", "/repo", Some(1), 4));
let all = h.search("", HistoryScope::All, "", "");
assert_eq!(
all.iter().map(|e| e.cmd.as_str()).collect::<Vec<_>>(),
vec!["cargo test", "ls", "cargo build"],
"newest first, duplicate command texts collapse to the newest run"
);
assert_eq!(all[0].exit, Some(1), "the newest occurrence wins");
let q = h.search("CARGO", HistoryScope::All, "", "");
assert_eq!(q.len(), 2, "query is case-insensitive substring");
let dir = h.search("", HistoryScope::Dir, "/tmp", "");
assert_eq!(
dir.iter().map(|e| e.cmd.as_str()).collect::<Vec<_>>(),
vec!["ls"]
);
let failed = h.search("", HistoryScope::Failed, "", "");
assert_eq!(
failed.iter().map(|e| e.cmd.as_str()).collect::<Vec<_>>(),
vec!["cargo test", "cargo build"],
"failed-only keeps non-zero exits"
);
}
#[test]
fn the_file_compacts_once_it_doubles_past_the_cap() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("h.jsonl");
let mut h = CommandHistory::load(&path);
h.disk_lines = HISTORY_MAX * 2;
for i in 0..3 {
h.append(entry(&format!("cmd-{i}"), "/", Some(0), i as u64));
}
let lines = std::fs::read_to_string(&path).unwrap().lines().count();
assert!(
lines <= HISTORY_MAX,
"compaction must rewrite the file down to the in-memory entries, got {lines} lines"
);
assert_eq!(h.disk_lines, h.entries.len());
}
}