use std::path::{Path, PathBuf};
const MAX_SNAPSHOTS_PER_FILE: usize = 50;
const MERGE_WINDOW_MILLIS: u64 = 10_000;
const SNAP_EXT: &str = "snap";
pub const MAX_SNAPSHOT_BYTES: u64 = 256 * 1024;
pub fn too_large_to_snapshot(len: u64) -> bool {
len > MAX_SNAPSHOT_BYTES
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Snapshot {
pub millis: u64,
pub file: PathBuf,
}
pub fn history_dir() -> PathBuf {
crate::paths::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
}
#[cfg(test)]
pub fn record_in(
root_dir: &Path,
abs_path: &Path,
content: &[u8],
millis: u64,
) -> std::io::Result<()> {
record_impl(root_dir, abs_path, content, millis, false)
}
pub fn record_kept_in(
root_dir: &Path,
abs_path: &Path,
content: &[u8],
millis: u64,
) -> std::io::Result<()> {
record_impl(root_dir, abs_path, content, millis, true)
}
fn is_kept(dir: &Path, millis: u64) -> bool {
keep_path(dir, millis).exists()
}
fn keep_path(dir: &Path, millis: u64) -> PathBuf {
dir.join(format!("{millis}.{KEEP_EXT}"))
}
const KEEP_EXT: &str = "keep";
fn record_impl(
root_dir: &Path,
abs_path: &Path,
content: &[u8],
millis: u64,
keep: bool,
) -> std::io::Result<()> {
if !keep && too_large_to_snapshot(content.len() as u64) {
return Ok(());
}
let dir = dir_for(root_dir, abs_path);
create_private_dir(&dir)?;
if let Some(latest) = entries_in(root_dir, abs_path).first() {
if std::fs::read(&latest.file).is_ok_and(|prev| prev == content) {
if keep {
write_staged(&dir, latest.millis, KEEP_EXT, b"")?;
}
return Ok(());
}
if !keep
&& !is_kept(&dir, latest.millis)
&& millis.saturating_sub(latest.millis) < MERGE_WINDOW_MILLIS
{
let _ = std::fs::remove_file(seats_path(&dir, millis));
write_snapshot(&dir, millis, content)?;
if latest.millis != millis {
let _ = std::fs::remove_file(&latest.file);
let _ = std::fs::remove_file(seats_path(&dir, latest.millis));
}
return Ok(());
}
}
let mut millis = millis;
while dir.join(format!("{millis}.{SNAP_EXT}")).exists() {
millis += 1;
}
let _ = std::fs::remove_file(seats_path(&dir, millis));
if !keep {
let _ = std::fs::remove_file(keep_path(&dir, millis));
}
write_snapshot(&dir, millis, content)?;
if keep {
write_staged(&dir, millis, KEEP_EXT, b"")?;
}
prune_in(root_dir, abs_path);
Ok(())
}
fn create_private_dir(dir: &Path) -> std::io::Result<()> {
let mut builder = std::fs::DirBuilder::new();
builder.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt;
builder.mode(0o700);
}
builder.create(dir)?;
#[cfg(unix)]
{
if let Some(root) = dir.parent() {
make_owner_only(root, false);
}
make_owner_only(dir, true);
}
Ok(())
}
#[cfg(unix)]
fn make_owner_only(dir: &Path, files: bool) {
use std::os::unix::fs::PermissionsExt;
let Ok(meta) = std::fs::metadata(dir) else {
return;
};
if meta.permissions().mode() & 0o077 == 0 {
return;
}
let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
if !files {
return;
}
for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
if entry.file_type().is_ok_and(|t| t.is_file()) {
let _ = std::fs::set_permissions(entry.path(), std::fs::Permissions::from_mode(0o600));
}
}
}
fn write_snapshot(dir: &Path, millis: u64, content: &[u8]) -> std::io::Result<()> {
write_staged(dir, millis, SNAP_EXT, content)
}
fn write_staged(dir: &Path, millis: u64, ext: &str, content: &[u8]) -> std::io::Result<()> {
use std::io::Write as _;
let final_path = dir.join(format!("{millis}.{ext}"));
let tmp = staging_path(dir, millis);
let written = (|| {
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create(true).truncate(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o600);
}
let mut file = opts.open(&tmp)?;
file.lock()?;
file.write_all(content)?;
#[cfg(windows)]
drop(file);
std::fs::rename(&tmp, &final_path)?;
#[cfg(not(windows))]
drop(file);
Ok(())
})();
if written.is_err() {
let _ = std::fs::remove_file(&tmp);
}
written
}
const STAGING_EXT: &str = "tmp";
const STAGING_ABANDONED_AFTER: std::time::Duration = std::time::Duration::from_secs(60);
fn staging_path(dir: &Path, millis: u64) -> PathBuf {
static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let pid = std::process::id();
dir.join(format!("{millis}.{SNAP_EXT}.{pid}-{seq}.{STAGING_EXT}"))
}
fn sweep_abandoned_staging(dir: &Path, now: std::time::SystemTime) {
let Ok(read) = std::fs::read_dir(dir) else {
return;
};
for entry in read.filter_map(|e| e.ok()) {
let path = entry.path();
if path.extension().and_then(|x| x.to_str()) != Some(STAGING_EXT) {
continue;
}
let old_enough = entry
.metadata()
.and_then(|m| m.modified())
.ok()
.and_then(|at| now.duration_since(at).ok())
.is_some_and(|age| age > STAGING_ABANDONED_AFTER);
if !old_enough {
continue;
}
let Ok(file) = std::fs::File::open(&path) else {
continue;
};
if file.try_lock().is_ok() {
let _ = std::fs::remove_file(&path);
}
}
}
const SEATS_EXT: &str = "seats";
fn record_seats_in(
root_dir: &Path,
abs_path: &Path,
millis: u64,
seats: &crate::provenance::Provenance,
) -> std::io::Result<()> {
if seats.attributed() == 0 {
return Ok(());
}
let dir = dir_for(root_dir, abs_path);
let json = serde_json::to_vec(seats).map_err(std::io::Error::other)?;
create_private_dir(&dir)?;
write_staged(&dir, millis, SEATS_EXT, &json)
}
pub fn record_with_seats_in(
root_dir: &Path,
abs_path: &Path,
content: &[u8],
millis: u64,
seats: &crate::provenance::Provenance,
) -> std::io::Result<()> {
record_seated(root_dir, abs_path, content, millis, seats, false)
}
pub fn record_kept_with_seats_in(
root_dir: &Path,
abs_path: &Path,
content: &[u8],
millis: u64,
seats: &crate::provenance::Provenance,
) -> std::io::Result<()> {
record_seated(root_dir, abs_path, content, millis, seats, true)
}
fn record_seated(
root_dir: &Path,
abs_path: &Path,
content: &[u8],
millis: u64,
seats: &crate::provenance::Provenance,
keep: bool,
) -> std::io::Result<()> {
if !keep && too_large_to_snapshot(content.len() as u64) {
return Ok(());
}
record_impl(root_dir, abs_path, content, millis, keep)?;
if seats.attributed() == 0 {
return Ok(());
}
let Some(holder) = entries_in(root_dir, abs_path)
.into_iter()
.find(|snap| std::fs::read(&snap.file).is_ok_and(|bytes| bytes == content))
else {
return Ok(());
};
record_seats_in(root_dir, abs_path, holder.millis, seats)
}
pub fn seats_for(
root_dir: &Path,
abs_path: &Path,
millis: u64,
) -> Option<crate::provenance::Provenance> {
let bytes = std::fs::read(seats_path(&dir_for(root_dir, abs_path), millis)).ok()?;
serde_json::from_slice(&bytes).ok()
}
fn seats_path(dir: &Path, millis: u64) -> PathBuf {
dir.join(format!("{millis}.{SEATS_EXT}"))
}
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 dir = dir_for(root_dir, abs_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);
let _ = std::fs::remove_file(seats_path(&dir, old.millis));
let _ = std::fs::remove_file(keep_path(&dir, old.millis));
}
sweep_abandoned_staging(&dir, std::time::SystemTime::now());
}
pub fn move_path(root_dir: &Path, old: &Path, new: &Path) {
let is_dir = std::fs::symlink_metadata(new).is_ok_and(|m| m.is_dir());
if is_dir {
let Ok(read) = std::fs::read_dir(new) else {
return;
};
for entry in read.filter_map(|e| e.ok()) {
let name = entry.file_name();
move_path(root_dir, &old.join(&name), &new.join(&name));
}
return;
}
let from = dir_for(root_dir, old);
if !from.is_dir() {
return;
}
let to = dir_for(root_dir, new);
if !to.exists() && std::fs::rename(&from, &to).is_ok() {
return;
}
if create_private_dir(&to).is_err() {
return;
}
let taken: std::collections::HashSet<u64> = entries_in(root_dir, new)
.into_iter()
.map(|s| s.millis)
.collect();
if let Ok(read) = std::fs::read_dir(&from) {
for entry in read.filter_map(|e| e.ok()) {
let file = entry.path();
let millis = file
.file_stem()
.and_then(|s| s.to_str())
.and_then(|s| s.parse::<u64>().ok());
if millis.is_some_and(|m| taken.contains(&m)) {
continue;
}
let _ = std::fs::rename(&file, to.join(entry.file_name()));
}
}
let _ = std::fs::remove_dir_all(&from);
prune_in(root_dir, new);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn kept_snapshots_are_never_merged_away_and_history_is_owner_only() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let f = Path::new("/work/.env");
record_in(root, f, b"v2", 1000).unwrap();
record_kept_in(root, f, b"v2", 3000).unwrap();
record_kept_in(root, f, b"v1", 3001).unwrap();
record_in(root, f, b"v1 edited", 4000).unwrap();
let held: Vec<Vec<u8>> = entries_in(root, f)
.iter()
.map(|s| std::fs::read(&s.file).unwrap())
.collect();
assert_eq!(
held,
vec![b"v1 edited".to_vec(), b"v1".to_vec(), b"v2".to_vec()]
);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let dir = dir_for(root, f);
assert_eq!(
std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777,
0o700
);
let snap = &entries_in(root, f)[0].file;
assert_eq!(
std::fs::metadata(snap).unwrap().permissions().mode() & 0o777,
0o600
);
}
}
#[test]
fn a_kept_record_in_the_same_millisecond_does_not_overwrite_the_newest() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let f = Path::new("/work/a.rs");
record_kept_in(root, f, b"before restore", 5000).unwrap();
record_kept_in(root, f, b"restored", 5000).unwrap();
let held: Vec<(u64, Vec<u8>)> = entries_in(root, f)
.iter()
.map(|s| (s.millis, std::fs::read(&s.file).unwrap()))
.collect();
assert_eq!(
held,
vec![
(5001, b"restored".to_vec()),
(5000, b"before restore".to_vec())
]
);
assert!(is_kept(&dir_for(root, f), 5000) && is_kept(&dir_for(root, f), 5001));
}
#[cfg(unix)]
#[test]
fn history_left_open_by_an_older_build_becomes_owner_only() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("history");
let f = Path::new("/work/.env");
let dir = root.join(key_for(f));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("1000.snap"), b"SECRET=1").unwrap();
for (p, mode) in [
(&root, 0o755),
(&dir, 0o755),
(&dir.join("1000.snap"), 0o644),
] {
std::fs::set_permissions(p, std::fs::Permissions::from_mode(mode)).unwrap();
}
record_in(&root, f, b"SECRET=2", 1500).unwrap();
let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
assert_eq!(mode(&root), 0o700);
assert_eq!(mode(&dir), 0o700);
for snap in entries_in(&root, f) {
assert_eq!(mode(&snap.file), 0o600, "{}", snap.file.display());
}
}
#[test]
fn a_snapshot_is_staged_under_a_name_the_listing_ignores() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let f = Path::new("/work/a.rs");
record_in(root, f, b"v1", 1000).unwrap();
let dir = dir_for(root, f);
std::fs::write(staging_path(&dir, 2000), b"half").unwrap();
let snaps = entries_in(root, f);
assert_eq!(snaps.len(), 1, "the staging file is not listed: {snaps:?}");
assert_eq!(snaps[0].millis, 1000);
let names: Vec<String> = std::fs::read_dir(&dir)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.collect();
assert!(names.contains(&String::from("1000.snap")), "{names:?}");
assert!(
!names.iter().any(|n| n.starts_with("1000.snap.")),
"a completed record leaves no staging file: {names:?}"
);
}
#[test]
fn each_writer_stages_under_its_own_name() {
let dir = Path::new("/store");
let a = staging_path(dir, 1000);
let b = staging_path(dir, 1000);
assert_ne!(a, b, "two writers, two staging files");
for p in [&a, &b] {
assert_eq!(p.extension().and_then(|x| x.to_str()), Some(STAGING_EXT));
let name = p.file_name().unwrap().to_string_lossy().into_owned();
assert!(
name.starts_with(&format!("1000.{SNAP_EXT}.{}-", std::process::id())),
"{name}"
);
}
}
#[test]
fn an_abandoned_staging_file_is_swept_but_a_live_one_is_left() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let f = Path::new("/work/a.rs");
record_in(root, f, b"v1", 1000).unwrap();
let dir = dir_for(root, f);
let stale = staging_path(&dir, 900);
std::fs::write(&stale, b"half").unwrap();
let long_ago = std::time::SystemTime::now() - STAGING_ABANDONED_AFTER * 10;
std::fs::File::options()
.write(true)
.open(&stale)
.unwrap()
.set_modified(long_ago)
.unwrap();
let fresh = staging_path(&dir, 950);
std::fs::write(&fresh, b"half").unwrap();
record_in(root, f, b"v2", 120_000).unwrap();
assert!(!stale.exists(), "the abandoned staging file was swept");
assert!(fresh.exists(), "the live one was left alone");
assert_eq!(entries_in(root, f).len(), 2, "and the snapshots are intact");
}
#[cfg(not(windows))]
#[test]
fn a_slow_writer_keeps_its_staging_file_however_old_it_looks() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let f = Path::new("/work/a.rs");
record_in(root, f, b"v1", 1000).unwrap();
let dir = dir_for(root, f);
let paused = staging_path(&dir, 900);
let holder = std::fs::File::create(&paused).unwrap();
holder.lock().unwrap();
holder
.set_modified(std::time::SystemTime::now() - STAGING_ABANDONED_AFTER * 10)
.unwrap();
record_in(root, f, b"v2", 120_000).unwrap();
assert!(
paused.exists(),
"a locked staging file is not swept, whatever its age"
);
drop(holder);
record_in(root, f, b"v3", 240_000).unwrap();
assert!(
!paused.exists(),
"released, it is swept like any abandoned one"
);
}
#[test]
fn a_record_that_cannot_land_leaves_no_staging_file_behind() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let f = Path::new("/work/a.rs");
let dir = dir_for(root, f);
std::fs::create_dir_all(dir.join("1000.snap")).unwrap();
assert!(
record_in(root, f, b"v1", 1000).is_err(),
"a snapshot that cannot land is reported"
);
let leftovers: Vec<String> = std::fs::read_dir(&dir)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.filter(|n| n.ends_with(STAGING_EXT))
.collect();
assert!(
leftovers.is_empty(),
"and its staging file is gone: {leftovers:?}"
);
}
#[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 a_save_past_the_size_cap_takes_no_snapshot() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let cap = MAX_SNAPSHOT_BYTES as usize;
let big = Path::new("/work/dump.sql");
record_in(root, big, &vec![b'x'; cap + 1], 60_000).unwrap();
let seats = crate::provenance::Provenance::new();
record_with_seats_in(root, big, &vec![b'y'; cap + 1], 120_000, &seats).unwrap();
assert!(entries_in(root, big).is_empty());
record_kept_in(root, big, &vec![b'z'; cap + 1], 180_000).unwrap();
assert_eq!(entries_in(root, big).len(), 1, "a kept record is taken");
let edge = Path::new("/work/edge.txt");
record_in(root, edge, &vec![b'x'; cap], 60_000).unwrap();
assert_eq!(entries_in(root, edge).len(), 1, "the cap itself is allowed");
}
#[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");
}
#[test]
fn seats_are_recorded_beside_their_snapshot_and_read_back() {
use crate::provenance::{Provenance, Seat};
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let f = tmp.path().join("a.txt");
record_in(root, &f, b"one\ntwo\n", 1_000).unwrap();
let mut seats = Provenance::new();
seats.record(0..1, Seat::Navigator);
seats.record(1..2, Seat::Peer(String::from("ada")));
record_seats_in(root, &f, 1_000, &seats).unwrap();
let back = seats_for(root, &f, 1_000).expect("the record is read back");
assert_eq!(back.seat(0), Some(&Seat::Navigator));
assert_eq!(back.seat(1), Some(&Seat::Peer(String::from("ada"))));
assert_eq!(back.seat(2), None);
assert!(
seats_for(root, &f, 2_000).is_none(),
"a timestamp with no record reads as nothing"
);
}
#[test]
fn a_superseded_snapshot_takes_its_seats_with_it() {
use crate::provenance::{Provenance, Seat};
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let f = tmp.path().join("a.txt");
let mut seats = Provenance::new();
seats.record(0..1, Seat::Navigator);
record_in(root, &f, b"v1\n", 1_000).unwrap();
record_seats_in(root, &f, 1_000, &seats).unwrap();
assert!(
seats_for(root, &f, 1_000).is_some(),
"control: the sidecar was written"
);
record_in(root, &f, b"v2\n", 5_000).unwrap();
assert!(
seats_for(root, &f, 1_000).is_none(),
"the superseded snapshot's seats are gone"
);
}
#[test]
fn a_pruned_snapshot_takes_its_seats_with_it() {
use crate::provenance::{Provenance, Seat};
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let f = tmp.path().join("a.txt");
let mut seats = Provenance::new();
seats.record(0..1, Seat::Me);
for n in 0..=MAX_SNAPSHOTS_PER_FILE as u64 {
let millis = 60_000 * (n + 1);
record_in(root, &f, format!("v{n}\n").as_bytes(), millis).unwrap();
record_seats_in(root, &f, millis, &seats).unwrap();
}
assert!(
seats_for(root, &f, 60_000).is_none(),
"the evicted first snapshot's seats are gone"
);
let newest = 60_000 * (MAX_SNAPSHOTS_PER_FILE as u64 + 1);
assert!(
seats_for(root, &f, newest).is_some(),
"the newest keeps its seats"
);
}
#[test]
fn seats_attach_to_the_snapshot_holding_the_bytes_and_an_empty_map_writes_nothing() {
use crate::provenance::{Provenance, Seat};
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let f = tmp.path().join("a.txt");
record_in(root, &f, b"v1\n", 1_000).unwrap();
let mut seats = Provenance::new();
seats.record(0..1, Seat::Generated);
record_with_seats_in(root, &f, b"v1\n", 60_000, &seats).unwrap();
assert!(
seats_for(root, &f, 1_000).is_some(),
"attached to the holder"
);
assert!(
seats_for(root, &f, 60_000).is_none(),
"nothing at the skipped time"
);
let g = tmp.path().join("b.txt");
record_with_seats_in(root, &g, b"plain\n", 1_000, &Provenance::new()).unwrap();
let dir = dir_for(root, &g);
let sidecars = std::fs::read_dir(&dir)
.unwrap()
.flatten()
.filter(|e| e.path().extension().and_then(|x| x.to_str()) == Some(SEATS_EXT))
.count();
assert_eq!(sidecars, 0, "an unattributed map writes no sidecar");
}
fn snap_millis(root: &Path, f: &Path) -> Vec<u64> {
entries_in(root, f).iter().map(|s| s.millis).collect()
}
#[test]
fn move_path_carries_a_files_snapshots_to_its_new_name() {
let hist = tempfile::tempdir().unwrap();
let work = tempfile::tempdir().unwrap();
let (old, new) = (
work.path().join("notes.txt"),
work.path().join("journal.txt"),
);
std::fs::write(&new, b"v3").unwrap();
record_in(hist.path(), &old, b"v1", 1_000).unwrap();
record_kept_in(hist.path(), &old, b"v2", 60_000).unwrap();
move_path(hist.path(), &old, &new);
assert_eq!(snap_millis(hist.path(), &new), vec![60_000, 1_000]);
assert!(
is_kept(&dir_for(hist.path(), &new), 60_000),
"sidecars travel too"
);
assert!(entries_in(hist.path(), &old).is_empty());
}
#[test]
fn move_path_carries_every_file_under_a_moved_folder() {
let hist = tempfile::tempdir().unwrap();
let work = tempfile::tempdir().unwrap();
let (old, new) = (work.path().join("docs"), work.path().join("notes"));
std::fs::create_dir_all(new.join("deep")).unwrap();
std::fs::write(new.join("a.md"), b"a").unwrap();
std::fs::write(new.join("deep").join("b.md"), b"b").unwrap();
record_in(hist.path(), &old.join("a.md"), b"a0", 1_000).unwrap();
record_in(hist.path(), &old.join("deep").join("b.md"), b"b0", 2_000).unwrap();
move_path(hist.path(), &old, &new);
assert_eq!(snap_millis(hist.path(), &new.join("a.md")), vec![1_000]);
assert_eq!(
snap_millis(hist.path(), &new.join("deep").join("b.md")),
vec![2_000]
);
assert!(entries_in(hist.path(), &old.join("a.md")).is_empty());
}
#[test]
fn move_path_merges_into_the_targets_existing_history() {
let hist = tempfile::tempdir().unwrap();
let work = tempfile::tempdir().unwrap();
let (old, new) = (work.path().join("a.txt"), work.path().join("b.txt"));
std::fs::write(&new, b"x").unwrap();
record_in(hist.path(), &old, b"old-1", 1_000).unwrap();
record_kept_in(hist.path(), &old, b"old-clash", 50_000).unwrap();
record_in(hist.path(), &new, b"new-clash", 50_000).unwrap();
move_path(hist.path(), &old, &new);
assert_eq!(snap_millis(hist.path(), &new), vec![50_000, 1_000]);
let clash = snapshot_file_in(hist.path(), &new, 50_000).unwrap();
assert_eq!(std::fs::read(clash).unwrap(), b"new-clash");
assert!(
!is_kept(&dir_for(hist.path(), &new), 50_000),
"the losing snapshot's sidecar does not attach to the winner"
);
assert!(entries_in(hist.path(), &old).is_empty());
}
#[test]
fn move_path_leaves_other_files_history_alone() {
let hist = tempfile::tempdir().unwrap();
let work = tempfile::tempdir().unwrap();
let (old, new) = (work.path().join("a.txt"), work.path().join("b.txt"));
let other = work.path().join("c.txt");
std::fs::write(&new, b"x").unwrap();
record_in(hist.path(), &other, b"c", 1_000).unwrap();
move_path(hist.path(), &old, &new);
assert_eq!(snap_millis(hist.path(), &other), vec![1_000]);
assert!(entries_in(hist.path(), &new).is_empty());
}
}