use anyhow::{Context, Result};
use sha2::{Digest, Sha256};
use std::borrow::Cow;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;
const IGNORED: &[&str] = &[".git", ".gitignore"];
pub(crate) fn is_regenerable(name: &str) -> bool {
matches!(name, "__pycache__" | ".DS_Store" | "Thumbs.db") || name.ends_with(".pyc")
}
fn is_ignored(name: &str) -> bool {
IGNORED.contains(&name) || is_regenerable(name)
}
const DEPENDENCY_DIRS: &[&str] = &["node_modules", ".venv", "venv"];
pub struct ContentEntry {
pub relative_path: String,
pub path: PathBuf,
pub exec_bits: Option<u32>,
pub modified_ms: Option<i64>,
}
impl ContentEntry {
pub fn is_executable(&self) -> bool {
self.exec_bits.is_some_and(|bits| bits != 0)
}
}
#[cfg(unix)]
fn exec_bits_of(path: &Path) -> Option<u32> {
use std::os::unix::fs::PermissionsExt;
path.metadata().ok().map(|m| m.permissions().mode() & 0o111)
}
#[cfg(not(unix))]
fn exec_bits_of(_path: &Path) -> Option<u32> {
None
}
pub fn list_content_files(dir: &Path) -> Vec<ContentEntry> {
walk_content_files(dir, false, false).unwrap_or_default()
}
pub fn list_content_files_strict(dir: &Path) -> Result<Vec<ContentEntry>> {
walk_content_files(dir, true, false)
}
fn walk_content_files(dir: &Path, strict: bool, skip_deps: bool) -> Result<Vec<ContentEntry>> {
let mut entries = Vec::new();
for result in WalkDir::new(dir).into_iter().filter_entry(|e| {
let name = e.file_name().to_string_lossy();
!is_ignored(&name)
&& !(skip_deps
&& e.depth() > 0
&& e.file_type().is_dir()
&& DEPENDENCY_DIRS.contains(&name.as_ref()))
}) {
match result {
Ok(entry) if entry.file_type().is_file() => entries.push(entry),
Ok(_) => {}
Err(err) if strict => {
return Err(
anyhow::Error::new(err).context(format!("failed to walk {}", dir.display()))
);
}
Err(_) => {}
}
}
entries.sort_by(|a, b| a.path().cmp(b.path()));
let mapped = entries
.into_iter()
.map(|entry| {
let relative_path = entry
.path()
.strip_prefix(dir)
.unwrap_or(entry.path())
.to_string_lossy()
.into_owned();
#[cfg(windows)]
let relative_path = relative_path.replace('\\', "/");
let exec_bits = exec_bits_of(entry.path());
let modified_ms = entry
.metadata()
.ok()
.and_then(|m| m.modified().ok())
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as i64);
ContentEntry {
relative_path,
path: entry.into_path(),
exec_bits,
modified_ms,
}
})
.collect();
Ok(mapped)
}
pub fn hash_entries(entries: &[ContentEntry]) -> String {
let mut hasher = Sha256::new();
for entry in entries {
hasher.update(entry.relative_path.as_bytes());
if let Ok(content) = std::fs::read(&entry.path) {
hasher.update(&content);
}
#[cfg(unix)]
if let Some(bits) = entry.exec_bits {
hasher.update(bits.to_le_bytes());
}
}
hex::encode(hasher.finalize())
}
pub fn latest_modified_ms(entries: &[ContentEntry]) -> Option<i64> {
entries.iter().filter_map(|e| e.modified_ms).max()
}
pub fn hash_directory(dir: &Path) -> Result<String> {
Ok(hash_entries(&list_content_files(dir)))
}
fn is_foldable_text(content: &[u8]) -> bool {
!content.contains(&0) && std::str::from_utf8(content).is_ok()
}
fn fold_crlf(content: &[u8]) -> Cow<'_, [u8]> {
if !is_foldable_text(content) || !content.windows(2).any(|pair| pair == b"\r\n") {
return Cow::Borrowed(content);
}
let mut folded = Vec::with_capacity(content.len());
let mut index = 0;
while index < content.len() {
if content[index] == b'\r' && content.get(index + 1) == Some(&b'\n') {
index += 1; continue;
}
folded.push(content[index]);
index += 1;
}
Cow::Owned(folded)
}
pub fn hash_entries_eol_insensitive(entries: &[ContentEntry]) -> Result<String> {
let mut hasher = Sha256::new();
for entry in entries {
let path = entry.relative_path.as_bytes();
hasher.update((path.len() as u64).to_le_bytes());
hasher.update(path);
let content = std::fs::read(&entry.path)
.with_context(|| format!("failed to read {}", entry.path.display()))?;
let folded = fold_crlf(&content);
hasher.update((folded.len() as u64).to_le_bytes());
hasher.update(folded.as_ref());
#[cfg(unix)]
if let Some(bits) = entry.exec_bits {
hasher.update(bits.to_le_bytes());
}
}
Ok(hex::encode(hasher.finalize()))
}
pub fn hash_directory_eol_insensitive(dir: &Path) -> Result<String> {
let entries = walk_content_files(dir, true, true)?;
if entries.is_empty() {
anyhow::bail!("no content files under {}", dir.display());
}
hash_entries_eol_insensitive(&entries)
}
#[cfg(test)]
mod tests;