use std::path::{Path, PathBuf};
const MAX_SNAPSHOTS_PER_FILE: usize = 50;
const MERGE_WINDOW_MILLIS: u64 = 10_000;
const SNAP_EXT: &str = "snap";
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Snapshot {
pub millis: u64,
pub file: PathBuf,
}
pub fn history_dir() -> PathBuf {
crate::prefs::config_dir().join("history")
}
pub const LOCAL_PREFIX: &str = "local:";
pub fn to_timeline_entries(
snaps: &[Snapshot],
now_millis: u64,
) -> Vec<crate::git::FileHistoryEntry> {
snaps
.iter()
.map(|s| crate::git::FileHistoryEntry {
short_hash: format!("{LOCAL_PREFIX}{}", s.millis),
summary: "Local snapshot".to_string(),
author: "You".to_string(),
age_secs: (now_millis.saturating_sub(s.millis) / 1000) as i64,
})
.collect()
}
pub fn merged_timeline(
commits: Vec<crate::git::FileHistoryEntry>,
snaps: &[Snapshot],
now_millis: u64,
) -> Vec<crate::git::FileHistoryEntry> {
let mut all = commits;
all.extend(to_timeline_entries(snaps, now_millis));
all.sort_by_key(|e| e.age_secs);
all
}
pub fn snapshot_millis(short_hash: &str) -> Option<u64> {
short_hash.strip_prefix(LOCAL_PREFIX)?.parse().ok()
}
pub fn snapshot_file_in(root_dir: &Path, abs_path: &Path, millis: u64) -> Option<PathBuf> {
let file = dir_for(root_dir, abs_path).join(format!("{millis}.{SNAP_EXT}"));
file.is_file().then_some(file)
}
fn key_for(abs_path: &Path) -> String {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for b in abs_path.to_string_lossy().as_bytes() {
h ^= u64::from(*b);
h = h.wrapping_mul(0x100_0000_01b3);
}
format!("{h:016x}")
}
fn legacy_key_for(abs_path: &Path) -> String {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
abs_path.to_string_lossy().hash(&mut h);
format!("{:016x}", h.finish())
}
fn dir_for(root_dir: &Path, abs_path: &Path) -> PathBuf {
let dir = root_dir.join(key_for(abs_path));
if !dir.exists() {
let legacy = root_dir.join(legacy_key_for(abs_path));
if legacy.is_dir() {
let _ = std::fs::rename(&legacy, &dir);
}
}
dir
}
pub fn record_in(
root_dir: &Path,
abs_path: &Path,
content: &[u8],
millis: u64,
) -> std::io::Result<()> {
let dir = dir_for(root_dir, abs_path);
if let Some(latest) = entries_in(root_dir, abs_path).first() {
if std::fs::read(&latest.file).is_ok_and(|prev| prev == content) {
return Ok(());
}
if millis.saturating_sub(latest.millis) < MERGE_WINDOW_MILLIS {
std::fs::write(dir.join(format!("{millis}.{SNAP_EXT}")), content)?;
if latest.millis != millis {
let _ = std::fs::remove_file(&latest.file);
}
return Ok(());
}
}
std::fs::create_dir_all(&dir)?;
std::fs::write(dir.join(format!("{millis}.{SNAP_EXT}")), content)?;
prune_in(root_dir, abs_path);
Ok(())
}
pub fn entries_in(root_dir: &Path, abs_path: &Path) -> Vec<Snapshot> {
let dir = dir_for(root_dir, abs_path);
let Ok(read) = std::fs::read_dir(&dir) else {
return Vec::new();
};
let mut out: Vec<Snapshot> = read
.filter_map(|e| e.ok())
.filter_map(|e| {
let file = e.path();
if file.extension().and_then(|x| x.to_str()) != Some(SNAP_EXT) {
return None;
}
let millis: u64 = file.file_stem()?.to_str()?.parse().ok()?;
Some(Snapshot { millis, file })
})
.collect();
out.sort_by_key(|s| std::cmp::Reverse(s.millis));
out
}
fn prune_in(root_dir: &Path, abs_path: &Path) {
let all = entries_in(root_dir, abs_path);
for old in all.into_iter().skip(MAX_SNAPSHOTS_PER_FILE) {
let _ = std::fs::remove_file(&old.file);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn records_and_lists_snapshots_newest_first() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let f = Path::new("/work/a.rs");
record_in(root, f, b"v1", 1000).unwrap();
record_in(root, f, b"v2", 60_000).unwrap();
record_in(root, f, b"v3", 120_000).unwrap();
let e = entries_in(root, f);
assert_eq!(e.len(), 3);
assert_eq!(e[0].millis, 120_000, "newest first");
assert_eq!(e[2].millis, 1000);
assert_eq!(std::fs::read_to_string(&e[0].file).unwrap(), "v3");
}
#[test]
fn identical_consecutive_saves_are_deduplicated() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let f = Path::new("/work/a.rs");
record_in(root, f, b"same", 1000).unwrap();
record_in(root, f, b"same", 60_000).unwrap();
assert_eq!(
entries_in(root, f).len(),
1,
"an unchanged save must not add a snapshot"
);
record_in(root, f, b"different", 120_000).unwrap();
assert_eq!(entries_in(root, f).len(), 2);
}
#[test]
fn distinct_files_never_share_a_key() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
record_in(root, Path::new("/work/a.rs"), b"a", 1).unwrap();
record_in(root, Path::new("/work/b.rs"), b"b", 1).unwrap();
assert_eq!(entries_in(root, Path::new("/work/a.rs")).len(), 1);
assert_eq!(entries_in(root, Path::new("/work/b.rs")).len(), 1);
assert_eq!(
std::fs::read_to_string(&entries_in(root, Path::new("/work/a.rs"))[0].file).unwrap(),
"a"
);
}
#[test]
fn old_snapshots_are_pruned_beyond_the_cap() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let f = Path::new("/work/a.rs");
for i in 0..(MAX_SNAPSHOTS_PER_FILE as u64 + 10) {
record_in(root, f, format!("v{i}").as_bytes(), (i + 1) * 60_000).unwrap();
}
let e = entries_in(root, f);
assert_eq!(e.len(), MAX_SNAPSHOTS_PER_FILE, "capped");
assert_eq!(
e[0].millis,
(MAX_SNAPSHOTS_PER_FILE as u64 + 10) * 60_000,
"the newest survives"
);
assert!(
e.last().unwrap().millis > 10 * 60_000,
"the oldest snapshots were pruned, not the newest"
);
}
#[test]
fn entries_for_an_unknown_file_is_empty() {
let tmp = tempfile::tempdir().unwrap();
assert!(entries_in(tmp.path(), Path::new("/nope.rs")).is_empty());
}
#[test]
fn saves_within_the_merge_window_replace_the_newest_snapshot() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let f = Path::new("/work/a.rs");
record_in(root, f, b"v1", 1_000).unwrap();
record_in(root, f, b"v2", 60_000).unwrap();
record_in(root, f, b"v3", 65_000).unwrap();
let e = entries_in(root, f);
assert_eq!(e.len(), 2, "the within-window save must merge, not append");
assert_eq!(e[0].millis, 65_000);
assert_eq!(std::fs::read(&e[0].file).unwrap(), b"v3");
assert_eq!(
std::fs::read(&e[1].file).unwrap(),
b"v1",
"history older than the window survives the churn"
);
}
#[test]
fn snapshots_hold_raw_bytes_so_non_utf8_files_have_history_too() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let f = Path::new("/work/u16.txt");
let utf16 = b"\xff\xfeh\x00i\x00";
record_in(root, f, utf16, 1_000).unwrap();
let e = entries_in(root, f);
assert_eq!(std::fs::read(&e[0].file).unwrap(), utf16);
}
#[test]
fn the_store_key_is_a_stable_hash_not_default_hasher() {
assert_eq!(key_for(Path::new("/work/a.rs")), "04a67ef4ed166070");
}
#[test]
fn a_default_hasher_keyed_store_is_migrated_to_the_stable_key() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let f = Path::new("/work/a.rs");
let old_dir = root.join(legacy_key_for(f));
std::fs::create_dir_all(&old_dir).unwrap();
std::fs::write(old_dir.join("1000.snap"), b"old").unwrap();
let e = entries_in(root, f);
assert_eq!(e.len(), 1, "pre-FNV snapshots must be found via migration");
assert!(
root.join(key_for(f)).is_dir() && !old_dir.exists(),
"the legacy directory must be renamed to the stable key"
);
}
#[test]
fn to_timeline_entries_tags_local_rows_and_dates_them() {
let snaps = vec![
Snapshot {
millis: 9000,
file: PathBuf::from("/x/9000.snap"),
},
Snapshot {
millis: 3000,
file: PathBuf::from("/x/3000.snap"),
},
];
let rows = to_timeline_entries(&snaps, 10_000);
assert_eq!(rows[0].short_hash, "local:9000");
assert_eq!(rows[0].author, "You");
assert_eq!(rows[0].summary, "Local snapshot");
assert_eq!(rows[0].age_secs, 1, "(10000-9000)/1000 = 1s");
assert_eq!(rows[1].age_secs, 7);
assert_eq!(snapshot_millis("local:9000"), Some(9000));
assert_eq!(
snapshot_millis("abc123"),
None,
"a git hash is not a snapshot"
);
}
#[test]
fn merged_timeline_interleaves_commits_and_snapshots_newest_first() {
use crate::git::FileHistoryEntry;
let commits = vec![
FileHistoryEntry {
short_hash: "c1".into(),
summary: "new".into(),
author: "a".into(),
age_secs: 2,
},
FileHistoryEntry {
short_hash: "c2".into(),
summary: "old".into(),
author: "a".into(),
age_secs: 100,
},
];
let snaps = vec![Snapshot {
millis: 5000,
file: PathBuf::from("/x/5000.snap"),
}];
let merged = merged_timeline(commits, &snaps, 10_000);
let hashes: Vec<&str> = merged.iter().map(|e| e.short_hash.as_str()).collect();
assert_eq!(hashes, vec!["c1", "local:5000", "c2"], "sorted by age");
}
}