use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::UNIX_EPOCH;
use rayon::prelude::*;
use cccc_core::report::{FileReport, FunctionReport};
const VERSION: &str = env!("CARGO_PKG_VERSION");
#[derive(Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Sig {
size: u64,
mtime_ns: u128,
blob_sha: [u8; 20],
}
pub fn sig_for(bytes: &[u8], mtime_ns: u128) -> Sig {
Sig {
size: bytes.len() as u64,
mtime_ns,
blob_sha: git_blob_sha1(bytes),
}
}
fn git_blob_sha1(bytes: &[u8]) -> [u8; 20] {
let mut h = sha1_smol::Sha1::new();
h.update(format!("blob {}\0", bytes.len()).as_bytes());
h.update(bytes);
h.digest().bytes()
}
pub struct GitIndex {
shas: HashMap<PathBuf, [u8; 20]>,
}
impl GitIndex {
fn sha_of(&self, path: &Path) -> Option<[u8; 20]> {
self.shas.get(&std::path::absolute(path).ok()?).copied()
}
}
pub struct LazyGitIndex {
index: std::sync::OnceLock<Option<GitIndex>>,
source: std::sync::Mutex<Option<GitIndexSource>>,
}
enum GitIndexSource {
Pending(PathBuf),
Running(std::thread::JoinHandle<Option<GitIndex>>),
}
impl LazyGitIndex {
pub fn new(root: PathBuf) -> Self {
let source = if std::env::var("CI").is_ok_and(|v| !v.is_empty() && v != "false") {
GitIndexSource::Running(std::thread::spawn(move || git_index(&root)))
} else {
GitIndexSource::Pending(root)
};
Self {
index: std::sync::OnceLock::new(),
source: std::sync::Mutex::new(Some(source)),
}
}
fn get(&self) -> Option<&GitIndex> {
self.index
.get_or_init(
|| match self.source.lock().ok().and_then(|mut s| s.take())? {
GitIndexSource::Pending(root) => git_index(&root),
GitIndexSource::Running(handle) => handle.join().ok().flatten(),
},
)
.as_ref()
}
}
impl Drop for LazyGitIndex {
fn drop(&mut self) {
if let Ok(mut source) = self.source.lock()
&& let Some(GitIndexSource::Running(handle)) = source.take()
{
let _ = handle.join();
}
}
}
pub fn git_index(root: &Path) -> Option<GitIndex> {
let toplevel = PathBuf::from(git(root, &["rev-parse", "--show-toplevel"])?.trim_end());
let mut shas = HashMap::new();
for entry in git(root, &["ls-files", "-s", "-z"])?
.split('\0')
.filter(|e| !e.is_empty())
{
let Some((meta, path)) = entry.split_once('\t') else {
continue;
};
let mut fields = meta.split(' ');
let (Some(mode), Some(sha), Some("0")) = (fields.next(), fields.next(), fields.next())
else {
continue;
};
if !mode.starts_with("100") {
continue;
}
let Some(sha) = decode_sha1(sha) else {
continue;
};
shas.insert(toplevel.join(path), sha);
}
for entry in git(
root,
&["status", "--porcelain", "-z", "-uno", "--no-renames"],
)?
.split('\0')
.filter(|e| !e.is_empty())
{
let Some(path) = entry.get(3..) else { continue };
shas.remove(&toplevel.join(path));
}
Some(GitIndex { shas })
}
fn git(dir: &Path, args: &[&str]) -> Option<String> {
let out = std::process::Command::new("git")
.arg("-C")
.arg(dir)
.args(args)
.stderr(std::process::Stdio::null())
.output()
.ok()?;
if !out.status.success() {
return None;
}
String::from_utf8(out.stdout).ok()
}
fn decode_sha1(hex: &str) -> Option<[u8; 20]> {
let hex = hex.as_bytes();
if hex.len() != 40 {
return None;
}
let mut out = [0u8; 20];
for (i, b) in out.iter_mut().enumerate() {
let hi = (hex[2 * i] as char).to_digit(16)?;
let lo = (hex[2 * i + 1] as char).to_digit(16)?;
*b = (hi * 16 + lo) as u8;
}
Some(out)
}
pub fn mtime_ns(path: &Path) -> Option<u128> {
mtime_of(&std::fs::metadata(path).ok()?)
}
fn mtime_of(md: &std::fs::Metadata) -> Option<u128> {
Some(
md.modified()
.ok()?
.duration_since(UNIX_EPOCH)
.ok()?
.as_nanos(),
)
}
#[derive(serde::Serialize, serde::Deserialize)]
struct IndexEntry {
lang: String,
sig: Sig,
offset: u64,
len: u64,
}
#[derive(serde::Serialize, serde::Deserialize)]
struct CacheFun {
name: String,
kind: String,
line: u32,
cognitive: u32,
cyclomatic: u32,
children: Vec<CacheFun>,
}
#[derive(serde::Serialize, serde::Deserialize)]
struct CacheReport {
path: String,
cognitive: u32,
cyclomatic: u32,
functions: Vec<CacheFun>,
parse_errors: Vec<String>,
}
pub struct Hit {
pub report: FileReport,
pub sig: Sig,
pub refreshed: bool,
}
pub struct Cache {
index: HashMap<String, IndexEntry>,
blobs: Vec<u8>,
}
pub fn load(path: &Path) -> Option<Cache> {
let bytes = std::fs::read(path).ok()?;
let (version, index, blobs): (String, Vec<(String, IndexEntry)>, Vec<u8>) =
bincode::deserialize(&bytes).ok()?;
if version != VERSION {
return None;
}
Some(Cache {
index: index.into_iter().collect(),
blobs,
})
}
impl Cache {
pub fn entry_count(&self) -> usize {
self.index.len()
}
pub fn lookup(&self, path: &Path, lang: &str, git: Option<&LazyGitIndex>) -> Option<Hit> {
let entry = self.index.get(&path.display().to_string())?;
if entry.lang != lang {
return None;
}
let md = std::fs::metadata(path).ok()?;
if md.len() != entry.sig.size {
return None;
}
let mtime = mtime_of(&md)?;
let sig = if mtime == entry.sig.mtime_ns {
entry.sig
} else if git.and_then(|g| g.get()).and_then(|g| g.sha_of(path)) == Some(entry.sig.blob_sha)
{
Sig {
mtime_ns: mtime,
..entry.sig
}
} else {
let sig = sig_for(&std::fs::read(path).ok()?, mtime);
if sig.size != entry.sig.size || sig.blob_sha != entry.sig.blob_sha {
return None;
}
sig
};
Some(Hit {
report: self.decode(entry)?,
refreshed: sig.mtime_ns != entry.sig.mtime_ns,
sig,
})
}
fn decode(&self, entry: &IndexEntry) -> Option<FileReport> {
let blob = self
.blobs
.get(entry.offset as usize..(entry.offset + entry.len) as usize)?;
let report: CacheReport = bincode::deserialize(blob).ok()?;
Some(from_cache(report))
}
}
pub fn store(
path: &Path,
entries: &[(FileReport, Option<Sig>)],
lang_for: &(dyn Fn(&Path) -> Option<&'static str> + Sync),
) {
let encoded: Vec<(String, IndexEntry, Vec<u8>)> = entries
.par_iter()
.filter_map(|(r, sig)| {
let sig = (*sig)?;
let lang = lang_for(Path::new(&r.path))?;
let blob = bincode::serialize(&to_cache(r)).ok()?;
let entry = IndexEntry {
lang: lang.to_string(),
sig,
offset: 0, len: blob.len() as u64,
};
Some((r.path.clone(), entry, blob))
})
.collect();
let mut index = Vec::with_capacity(encoded.len());
let mut blobs = Vec::new();
for (key, mut entry, blob) in encoded {
entry.offset = blobs.len() as u64;
blobs.extend_from_slice(&blob);
index.push((key, entry));
}
let Ok(bytes) = bincode::serialize(&(VERSION, index, blobs)) else {
crate::output::warn("cccc: warning: failed to encode results cache");
return;
};
let Some(name) = path.file_name() else { return };
let tmp = path.with_file_name(format!("{}.tmp", name.to_string_lossy()));
let written = std::fs::write(&tmp, &bytes).and_then(|()| std::fs::rename(&tmp, path));
if let Err(e) = written {
crate::output::warn(&format!(
"cccc: warning: failed to write results cache {}: {e}",
path.display()
));
}
}
fn to_cache_funs(fns: &[FunctionReport]) -> Vec<CacheFun> {
fns.iter()
.map(|f| CacheFun {
name: f.name.clone(),
kind: f.kind.clone(),
line: f.line,
cognitive: f.cognitive,
cyclomatic: f.cyclomatic,
children: to_cache_funs(&f.children),
})
.collect()
}
fn from_cache_funs(fns: Vec<CacheFun>) -> Vec<FunctionReport> {
fns.into_iter()
.map(|f| FunctionReport {
name: f.name,
kind: f.kind,
line: f.line,
cognitive: f.cognitive,
cyclomatic: f.cyclomatic,
children: from_cache_funs(f.children),
})
.collect()
}
fn to_cache(r: &FileReport) -> CacheReport {
CacheReport {
path: r.path.clone(),
cognitive: r.cognitive,
cyclomatic: r.cyclomatic,
functions: to_cache_funs(&r.functions),
parse_errors: r.parse_errors.clone(),
}
}
fn from_cache(c: CacheReport) -> FileReport {
FileReport {
path: c.path,
cognitive: c.cognitive,
cyclomatic: c.cyclomatic,
functions: from_cache_funs(c.functions),
parse_errors: c.parse_errors,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sample_report(path: &str) -> FileReport {
FileReport {
path: path.to_string(),
cognitive: 3,
cyclomatic: 2,
functions: vec![FunctionReport {
name: "f".to_string(),
kind: "function".to_string(),
line: 1,
cognitive: 3,
cyclomatic: 2,
children: vec![FunctionReport {
name: "g".to_string(),
kind: "arrow".to_string(),
line: 2,
cognitive: 0,
cyclomatic: 1,
children: Vec::new(),
}],
}],
parse_errors: vec!["boom".to_string()],
}
}
fn store_one(cache_file: &Path, src: &Path, lang: &'static str) {
let sig = sig_for(&std::fs::read(src).unwrap(), mtime_ns(src).unwrap());
store(
cache_file,
&[(sample_report(&src.display().to_string()), Some(sig))],
&move |_| Some(lang),
);
}
#[test]
fn roundtrip_hits_for_unchanged_file() {
let dir = std::env::temp_dir().join("cccc_cache_unit_roundtrip");
std::fs::create_dir_all(&dir).unwrap();
let src = dir.join("a.ts");
std::fs::write(&src, "function f() {}").unwrap();
let cache_file = dir.join("cache.bin");
store_one(&cache_file, &src, "es");
let cache = load(&cache_file).expect("cache loads");
let hit = cache.lookup(&src, "es", None).expect("unchanged file hits");
assert!(!hit.refreshed, "a stat hit needs no rewrite");
assert_eq!(hit.report.cognitive, 3);
assert_eq!(hit.report.functions[0].children[0].name, "g");
assert_eq!(hit.report.parse_errors, vec!["boom".to_string()]);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn changed_file_and_changed_language_miss() {
let dir = std::env::temp_dir().join("cccc_cache_unit_invalidate");
std::fs::create_dir_all(&dir).unwrap();
let src = dir.join("a.ts");
std::fs::write(&src, "function f() { return 1 }").unwrap();
let cache_file = dir.join("cache.bin");
store_one(&cache_file, &src, "es");
let cache = load(&cache_file).unwrap();
assert!(
cache.lookup(&src, "rust", None).is_none(),
"other language misses"
);
std::fs::write(&src, "function f() { return 2 }").unwrap();
assert!(
cache.lookup(&src, "es", None).is_none(),
"same-size edit misses via hash"
);
std::fs::write(&src, "function f() {}").unwrap();
assert!(
cache.lookup(&src, "es", None).is_none(),
"resized file misses"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn mtime_only_change_hits_via_hash_and_refreshes() {
let dir = std::env::temp_dir().join("cccc_cache_unit_touch");
std::fs::create_dir_all(&dir).unwrap();
let src = dir.join("a.ts");
std::fs::write(&src, "function f() {}").unwrap();
let cache_file = dir.join("cache.bin");
store_one(&cache_file, &src, "es");
let bumped = std::time::SystemTime::now() + std::time::Duration::from_secs(10);
std::fs::File::options()
.write(true)
.open(&src)
.unwrap()
.set_modified(bumped)
.unwrap();
let cache = load(&cache_file).unwrap();
let hit = cache.lookup(&src, "es", None).expect("content match hits");
assert!(hit.refreshed, "a hash hit asks for a rewrite");
assert_eq!(hit.report.cognitive, 3);
store(&cache_file, &[(hit.report, Some(hit.sig))], &|_| Some("es"));
let hit = load(&cache_file).unwrap().lookup(&src, "es", None).unwrap();
assert!(!hit.refreshed, "refreshed mtime now stat-hits");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn git_blob_sha1_matches_git() {
let hex = |sha: [u8; 20]| sha.iter().map(|b| format!("{b:02x}")).collect::<String>();
assert_eq!(
hex(git_blob_sha1(b"")),
"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"
);
assert_eq!(
hex(git_blob_sha1(b"hello\n")),
"ce013625030ba8dba906f756967f9e9ca394464a"
);
}
#[test]
fn git_blob_sha1_agrees_with_git_hash_object() {
let git_hash_object = |bytes: &[u8]| -> String {
use std::io::Write;
let mut child = std::process::Command::new("git")
.args(["hash-object", "--stdin"])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.spawn()
.unwrap();
child.stdin.take().unwrap().write_all(bytes).unwrap();
let out = child.wait_with_output().unwrap();
assert!(out.status.success(), "git hash-object failed");
String::from_utf8(out.stdout)
.unwrap()
.trim_end()
.to_string()
};
let hex = |sha: [u8; 20]| sha.iter().map(|b| format!("{b:02x}")).collect::<String>();
let mut big = Vec::with_capacity(8192);
for i in 0..8192u32 {
big.push((i.wrapping_mul(2654435761) >> 24) as u8);
}
let contents: Vec<&[u8]> = vec![
b"",
b"x",
"関数の複雑度 → スコア\n".as_bytes(),
b"line one\r\nline two\r\n",
b"nul\x00in the middle",
&big,
];
for bytes in contents {
assert_eq!(
hex(git_blob_sha1(bytes)),
git_hash_object(bytes),
"blob SHA must match git's for {} bytes",
bytes.len()
);
}
}
#[test]
fn git_index_vouches_for_clean_files_only() {
let dir = std::env::temp_dir().join("cccc_cache_unit_gitindex");
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let dir = dir.canonicalize().unwrap();
let src = dir.join("a.ts");
std::fs::write(&src, "function f() {}").unwrap();
let run_git = |args: &[&str]| {
assert!(
std::process::Command::new("git")
.arg("-C")
.arg(&dir)
.args(args)
.output()
.unwrap()
.status
.success()
);
};
run_git(&["init", "-q"]);
run_git(&["add", "."]);
run_git(&[
"-c",
"user.name=t",
"-c",
"user.email=t@t",
"commit",
"-q",
"-m",
"x",
]);
let cache_file = dir.join("cache.bin");
store_one(&cache_file, &src, "es");
let cache = load(&cache_file).unwrap();
let bumped = std::time::SystemTime::now() - std::time::Duration::from_secs(3600);
std::fs::File::options()
.write(true)
.open(&src)
.unwrap()
.set_modified(bumped)
.unwrap();
run_git(&["update-index", "--refresh"]);
#[cfg(unix)]
let perms = {
use std::os::unix::fs::PermissionsExt;
let orig = std::fs::metadata(&src).unwrap().permissions();
std::fs::set_permissions(&src, std::fs::Permissions::from_mode(0o000)).unwrap();
orig
};
let git = LazyGitIndex::new(dir.clone());
let hit = cache
.lookup(&src, "es", Some(&git))
.expect("clean file hits via git");
assert!(hit.refreshed, "a git hit persists the fresh mtime");
assert_eq!(hit.report.cognitive, 3);
#[cfg(unix)]
std::fs::set_permissions(&src, perms).unwrap();
std::fs::write(&src, "function f() { return 9 }").unwrap();
let git = LazyGitIndex::new(dir.clone());
assert!(
cache.lookup(&src, "es", Some(&git)).is_none(),
"dirty file must not hit via the stale index SHA"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[cfg(unix)]
#[test]
fn filtered_file_is_never_vouched_by_the_index() {
use std::os::unix::fs::PermissionsExt;
let dir = std::env::temp_dir().join("cccc_cache_unit_gitfilter");
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let dir = dir.canonicalize().unwrap();
let src = dir.join("a.ts");
std::fs::write(&src, "function f() {\r\n}\r\n").unwrap();
std::fs::write(dir.join(".gitattributes"), "*.ts text\n").unwrap();
let run_git = |args: &[&str]| {
assert!(
std::process::Command::new("git")
.arg("-C")
.arg(&dir)
.args(["-c", "core.autocrlf=false"])
.args(args)
.output()
.unwrap()
.status
.success()
);
};
run_git(&["init", "-q"]);
run_git(&["add", "."]);
run_git(&[
"-c",
"user.name=t",
"-c",
"user.email=t@t",
"commit",
"-q",
"-m",
"x",
]);
let cache_file = dir.join("cache.bin");
store_one(&cache_file, &src, "es");
let cache = load(&cache_file).unwrap();
let bumped = std::time::SystemTime::now() - std::time::Duration::from_secs(3600);
std::fs::File::options()
.write(true)
.open(&src)
.unwrap()
.set_modified(bumped)
.unwrap();
run_git(&["update-index", "--refresh"]);
let perms = std::fs::metadata(&src).unwrap().permissions();
std::fs::set_permissions(&src, std::fs::Permissions::from_mode(0o000)).unwrap();
let git = LazyGitIndex::new(dir.clone());
assert!(
cache.lookup(&src, "es", Some(&git)).is_none(),
"the index's normalized blob SHA must not validate raw CRLF bytes"
);
std::fs::set_permissions(&src, perms).unwrap();
let git = LazyGitIndex::new(dir.clone());
let hit = cache
.lookup(&src, "es", Some(&git))
.expect("hash fallback still hits");
assert!(hit.refreshed);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn corrupt_cache_degrades_to_cold() {
let dir = std::env::temp_dir().join("cccc_cache_unit_corrupt");
std::fs::create_dir_all(&dir).unwrap();
let cache_file = dir.join("cache.bin");
std::fs::write(&cache_file, b"not a cache").unwrap();
assert!(load(&cache_file).is_none());
let _ = std::fs::remove_dir_all(&dir);
}
}