Files
lucisv/crates/lucisv_core/src/cache.rs
T

487 lines
18 KiB
Rust

//! The "already formatted" cache: a per-path record of content that a
//! previous run verified is a fixed point, so a repeat run can skip the
//! file entirely.
//!
//! Only the *clean* verdict is ever stored — never an error and never
//! "would reformat" — so a stale, missing or wrong entry can only ever
//! cause work to be redone, never a diagnostic to be lost. See
//! `docs/features/format-cache/README.md` for the key, the storage
//! format and the collision posture.
use std::collections::HashMap;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
/// The default cache directory, resolved against the current directory.
pub const DEFAULT_DIR: &str = ".lucisv_cache";
/// The entry file inside the cache directory.
const FILE: &str = "cache";
/// lucisv's version, part of every entry: a new release may format the same
/// bytes differently, so another version's entries are ignored.
const VERSION: &str = env!("CARGO_PKG_VERSION");
/// What one entry asserts about one path: this content, under these
/// settings, is already formatted.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Entry {
/// FNV-1a hash of the file's bytes as they are on disk.
pub content: u64,
/// The `line-length` that verdict was reached under.
pub line_length: usize,
/// The `indent` that verdict was reached under.
pub indent: usize,
/// The `[format] uvm-utils-indent` that verdict was reached under: it
/// changes the output of a UVM class, so it is part of the key.
pub uvm_utils_indent: bool,
}
/// The cache for one run: loaded once at startup, written once at exit.
pub struct Cache {
/// Where to write at the end of the run; `None` when the cache is off.
path: Option<PathBuf>,
entries: HashMap<String, Entry>,
}
impl Cache {
/// Loads the cache stored in `dir`. Never fails: a missing, unreadable
/// or corrupt file simply yields an empty cache that the run rebuilds.
pub fn load(dir: &Path) -> Cache {
let path = dir.join(FILE);
let entries =
std::fs::read_to_string(&path).ok().and_then(|text| parse(&text)).unwrap_or_default();
Cache { path: Some(path), entries }
}
/// A cache that reads nothing and writes nothing (`--no-cache`).
pub fn disabled() -> Cache {
Cache { path: None, entries: HashMap::new() }
}
/// True when `path`'s current content was already verified formatted
/// under these settings by this version of lucisv.
pub fn is_clean(&self, path: &Path, entry: Entry) -> bool {
key(path).and_then(|k| self.entries.get(k)) == Some(&entry)
}
/// Records that `path` holds content that is a fixed point. A no-op
/// when the cache is off, or when the path cannot be stored.
pub fn record(&mut self, path: &Path, entry: Entry) {
if self.path.is_none() {
return;
}
if let Some(k) = key(path) {
self.entries.insert(k.to_string(), entry);
}
}
/// Writes the cache back, atomically. Failure is deliberately silent:
/// the cache is an optimization, and a run must not change its output
/// or its exit code because a directory happened to be read-only.
pub fn store(&self) {
let Some(path) = &self.path else { return };
let Some(dir) = path.parent() else { return };
if std::fs::create_dir_all(dir).is_err() {
return;
}
// Self-ignoring, the way cargo marks `target/`.
let ignore = dir.join(".gitignore");
if !ignore.exists() {
let _ = std::fs::write(&ignore, "*\n");
}
let _ = crate::atomic::write_atomic(path, self.render().as_bytes());
}
/// The file's text: one line per entry, sorted by path so that two
/// runs over the same tree write byte-identical caches. Entries whose
/// file is gone are dropped, so the file cannot grow forever.
fn render(&self) -> String {
let mut paths: Vec<&String> = self.entries.keys().collect();
paths.sort();
let mut text = String::new();
for path in paths {
if !Path::new(path).exists() {
continue;
}
let entry = &self.entries[path];
let _ = writeln!(
text,
"{:016x}\t{}\t{}\t{}\t{VERSION}\t{path}",
entry.content, entry.line_length, entry.indent, entry.uvm_utils_indent
);
}
text
}
}
/// FNV-1a, 64-bit. Hand-rolled because the hash is written to disk and
/// std's `DefaultHasher` is explicitly not stable across Rust releases;
/// FNV-1a is byte-exactly specified and needs no dependency.
pub fn content_hash(bytes: &[u8]) -> u64 {
const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
const PRIME: u64 = 0x0000_0100_0000_01b3;
let mut hash = OFFSET;
for byte in bytes {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(PRIME);
}
hash
}
/// A path's key in the store, or `None` for one that cannot be written on
/// a line of text (not UTF-8, or containing a tab or newline). Such a file
/// is simply never cached.
fn key(path: &Path) -> Option<&str> {
let text = path.to_str()?;
if text.is_empty() || text.contains('\t') || text.contains('\n') {
return None;
}
Some(text)
}
/// The `(content, line-length, indent)` prefix every store line has ever
/// begun with, or `None` when those three fields are not what lucisv writes.
fn prefix(content: &str, line_length: &str, indent: &str) -> Option<(u64, usize, usize)> {
Some((u64::from_str_radix(content, 16).ok()?, line_length.parse().ok()?, indent.parse().ok()?))
}
/// Parses the store. `None` means "this file is not something lucisv wrote"
/// — one malformed line discards the whole cache, because partial trust in
/// a file already caught lying is not worth the branch. Entries from
/// another lucisv version, and lines written in an older field layout, are
/// dropped individually; that is staleness, not corruption.
fn parse(text: &str) -> Option<HashMap<String, Entry>> {
let mut entries = HashMap::new();
for line in text.lines() {
let fields: Vec<&str> = line.splitn(6, '\t').collect();
match fields[..] {
[content, line_length, indent, uvm, version, path] => {
let (content, line_length, indent) = prefix(content, line_length, indent)?;
let uvm_utils_indent = uvm.parse().ok()?;
if path.is_empty() {
return None;
}
if version == VERSION {
entries.insert(
path.to_string(),
Entry { content, line_length, indent, uvm_utils_indent },
);
}
}
// A store written before `uvm-utils-indent` joined the key: a
// well-formed line of that older shape says nothing about the
// option, so it is dropped individually, exactly like another
// version's entry. (The version field alone already makes such
// a store miss; the codec stays self-describing anyway.)
// Anything else on five fields is corruption and discards the
// file like any other malformed line.
[content, line_length, indent, _version, path] => {
prefix(content, line_length, indent)?;
if path.is_empty() {
return None;
}
}
_ => return None,
}
}
Some(entries)
}
#[cfg(test)]
mod tests {
use super::*;
/// A throwaway directory, removed on drop.
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(tag: &str) -> TempDir {
use std::sync::atomic::{AtomicUsize, Ordering};
static COUNTER: AtomicUsize = AtomicUsize::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let path =
std::env::temp_dir().join(format!("lucisv-cache-{}-{tag}-{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("create temp dir");
TempDir { path }
}
/// Creates a file so that `render`'s existence check keeps it.
fn file(&self, name: &str) -> PathBuf {
let path = self.path.join(name);
std::fs::write(&path, "x").expect("write file");
path
}
fn cache_text(&self) -> String {
std::fs::read_to_string(self.path.join(FILE)).expect("read cache")
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
fn entry(content: u64) -> Entry {
Entry { content, line_length: 100, indent: 2, uvm_utils_indent: false }
}
#[test]
fn fnv_1a_matches_the_published_vectors() {
// The reference values for FNV-1a 64. If this ever changes, every
// cache on every machine silently invalidates — hence the test.
assert_eq!(content_hash(b""), 0xcbf2_9ce4_8422_2325);
assert_eq!(content_hash(b"a"), 0xaf63_dc4c_8601_ec8c);
assert_eq!(content_hash(b"foobar"), 0x8594_4171_f739_67e8);
}
#[test]
fn a_missing_cache_is_empty_not_an_error() {
let dir = TempDir::new("missing");
let cache = Cache::load(&dir.path);
assert!(!cache.is_clean(Path::new("a.sv"), entry(1)));
}
#[test]
fn entries_round_trip_through_the_file() {
let dir = TempDir::new("roundtrip");
let file = dir.file("a.sv");
let mut cache = Cache::load(&dir.path);
cache.record(&file, entry(0xdead));
cache.store();
let reloaded = Cache::load(&dir.path);
assert!(reloaded.is_clean(&file, entry(0xdead)));
// Every field is part of the key.
assert!(!reloaded.is_clean(&file, entry(0xbeef)));
assert!(!reloaded.is_clean(&file, Entry { line_length: 80, ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { indent: 4, ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { uvm_utils_indent: true, ..entry(0xdead) }));
assert!(!reloaded.is_clean(Path::new("other.sv"), entry(0xdead)));
}
#[test]
fn uvm_utils_indent_alone_is_a_different_entry() {
let on = Entry { uvm_utils_indent: true, ..entry(0xdead) };
assert_ne!(entry(0xdead), on, "the option is part of equality");
// …and it survives the round trip through the store, on its own.
let dir = TempDir::new("uvm");
let file = dir.file("a.sv");
let mut cache = Cache::load(&dir.path);
cache.record(&file, on);
cache.store();
assert!(dir.cache_text().contains("\t100\t2\ttrue\t"), "{}", dir.cache_text());
let reloaded = Cache::load(&dir.path);
assert!(reloaded.is_clean(&file, on));
assert!(!reloaded.is_clean(&file, entry(0xdead)), "the option must invalidate the entry");
}
#[test]
fn a_line_without_the_option_is_dropped_but_not_fatal() {
// The five-field shape lucisv wrote before `uvm-utils-indent` joined
// the key: stale, like another version's entry, never corruption.
let dir = TempDir::new("oldshape");
let old = dir.file("old.sv");
let mine = dir.file("mine.sv");
let text = format!(
"{:016x}\t100\t2\t{VERSION}\t{}\n{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n",
1,
old.to_string_lossy(),
2,
mine.to_string_lossy()
);
std::fs::write(dir.path.join(FILE), text).unwrap();
let cache = Cache::load(&dir.path);
assert!(!cache.is_clean(&old, entry(1)), "a line without the option must not be trusted");
assert!(cache.is_clean(&mine, entry(2)), "and it does not discard the rest of the file");
// And it is not carried forward.
cache.store();
assert!(!dir.cache_text().contains("old.sv"), "{}", dir.cache_text());
}
#[test]
fn the_file_is_sorted_and_carries_the_version() {
let dir = TempDir::new("format");
let b = dir.file("b.sv");
let a = dir.file("a.sv");
let mut cache = Cache::load(&dir.path);
cache.record(&b, entry(2));
cache.record(&a, entry(1));
cache.store();
let text = dir.cache_text();
let lines: Vec<&str> = text.lines().collect();
assert_eq!(lines.len(), 2, "{text}");
assert!(lines[0].ends_with("a.sv"), "sorted by path: {text}");
assert!(lines[1].ends_with("b.sv"), "sorted by path: {text}");
assert_eq!(
lines[0],
format!("{:016x}\t100\t2\tfalse\t{VERSION}\t{}", 1, a.to_string_lossy()),
"{text}"
);
}
#[test]
fn the_cache_directory_ignores_itself() {
let dir = TempDir::new("selfignore");
let file = dir.file("a.sv");
let mut cache = Cache::load(&dir.path);
cache.record(&file, entry(1));
cache.store();
assert_eq!(std::fs::read_to_string(dir.path.join(".gitignore")).unwrap(), "*\n");
}
#[test]
fn a_corrupt_file_is_ignored_wholesale() {
for corrupt in [
"garbage\n",
"not-hex\t100\t2\t0.2.0\t/a.sv\n",
"0000000000000001\twide\t2\t0.2.0\t/a.sv\n",
"0000000000000001\t100\t2\t0.2.0\n",
"0000000000000001\t100\t2\t0.2.0\t\n",
"0000000000000001\t100\t2\tyes\t0.2.0\t/a.sv\n",
"0000000000000001\t100\t2\tfalse\t0.2.0\t\n",
"\0\0\0\n",
] {
let dir = TempDir::new("corrupt");
let file = dir.file("a.sv");
// A good line first: a bad one anywhere discards all of them.
let good =
format!("{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n", 1, file.to_string_lossy());
std::fs::write(dir.path.join(FILE), format!("{good}{corrupt}")).unwrap();
let cache = Cache::load(&dir.path);
assert!(!cache.is_clean(&file, entry(1)), "should have been discarded: {corrupt:?}");
}
}
#[test]
fn another_versions_entry_is_dropped_but_not_fatal() {
let dir = TempDir::new("version");
let old = dir.file("old.sv");
let mine = dir.file("mine.sv");
let text = format!(
"{:016x}\t100\t2\tfalse\t0.0.0-not-this-one\t{}\n\
{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n",
1,
old.to_string_lossy(),
2,
mine.to_string_lossy()
);
std::fs::write(dir.path.join(FILE), text).unwrap();
let cache = Cache::load(&dir.path);
assert!(!cache.is_clean(&old, entry(1)), "another version's entry must not be trusted");
assert!(cache.is_clean(&mine, entry(2)), "this version's entry survives alongside it");
// And it is not carried forward.
cache.store();
assert!(!dir.cache_text().contains("old.sv"));
}
#[test]
fn entries_for_deleted_files_are_pruned_on_write() {
let dir = TempDir::new("prune");
let kept = dir.file("kept.sv");
let gone = dir.file("gone.sv");
let mut cache = Cache::load(&dir.path);
cache.record(&kept, entry(1));
cache.record(&gone, entry(2));
std::fs::remove_file(&gone).unwrap();
cache.store();
let text = dir.cache_text();
assert!(text.contains("kept.sv"), "{text}");
assert!(!text.contains("gone.sv"), "{text}");
}
#[test]
fn unvisited_entries_survive_a_later_run() {
let dir = TempDir::new("survive");
let first = dir.file("a.sv");
let second = dir.file("b.sv");
let mut cache = Cache::load(&dir.path);
cache.record(&first, entry(1));
cache.store();
// A second run that only visits b.sv must not forget a.sv.
let mut cache = Cache::load(&dir.path);
cache.record(&second, entry(2));
cache.store();
let reloaded = Cache::load(&dir.path);
assert!(reloaded.is_clean(&first, entry(1)));
assert!(reloaded.is_clean(&second, entry(2)));
}
#[test]
fn a_disabled_cache_reads_and_writes_nothing() {
let dir = TempDir::new("disabled");
let file = dir.file("a.sv");
let mut warm = Cache::load(&dir.path);
warm.record(&file, entry(1));
warm.store();
let before = dir.cache_text();
let mut cache = Cache::disabled();
assert!(!cache.is_clean(&file, entry(1)), "--no-cache must not read");
cache.record(&file, entry(9));
cache.store();
assert_eq!(dir.cache_text(), before, "--no-cache must not write");
}
#[test]
fn nothing_is_created_when_the_cache_is_off() {
let dir = TempDir::new("nothing");
let cache = Cache::disabled();
cache.store();
assert!(!dir.path.join(FILE).exists());
assert!(!dir.path.join(".gitignore").exists());
}
#[test]
fn the_cache_directory_is_created_on_demand() {
let dir = TempDir::new("mkdir");
let file = dir.file("a.sv");
let nested = dir.path.join("deep/inner");
let mut cache = Cache::load(&nested);
cache.record(&file, entry(1));
cache.store();
assert!(Cache::load(&nested).is_clean(&file, entry(1)));
}
#[test]
fn no_temporary_file_is_left_behind() {
let dir = TempDir::new("tmp");
let file = dir.file("a.sv");
let mut cache = Cache::load(&dir.path);
cache.record(&file, entry(1));
cache.store();
let leftovers: Vec<_> = std::fs::read_dir(&dir.path)
.unwrap()
.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n.ends_with(".tmp") || n.ends_with("-tmp"))
.collect();
assert!(leftovers.is_empty(), "{leftovers:?}");
}
#[test]
fn a_path_that_cannot_be_stored_is_simply_not_cached() {
let dir = TempDir::new("weirdpath");
let weird = dir.path.join("a\tb.sv");
let mut cache = Cache::load(&dir.path);
cache.record(&weird, entry(1));
cache.store();
assert!(!Cache::load(&dir.path).is_clean(&weird, entry(1)));
}
}