use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use nativeview_abi::xxh64;
pub use super::workspace::workspace_relative_path;
use super::workspace::workspace_relative_path_in;
#[derive(Debug, Default)]
pub struct WatchSnapshot {
rs_files: HashMap<PathBuf, String>,
asset_hashes: HashMap<PathBuf, u64>,
}
pub use nativeview_view_syntax::canonicalize_preserving_missing;
fn is_ignored_dir_name(name: &str) -> bool {
matches!(name, "target" | ".git" | "dist" | "node_modules" | "pkg") || name.starts_with('.')
}
fn is_ignored_file_name(path: &Path) -> bool {
let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
return true;
};
name.starts_with('.') || name.ends_with('~') || name.ends_with(".swp") || name.ends_with(".tmp")
}
fn is_excluded_dir(path: &Path, excluded_dirs: &[PathBuf]) -> bool {
if excluded_dirs.is_empty() {
return false;
}
let canon = canonicalize_preserving_missing(path);
excluded_dirs.iter().any(|ex| canon.starts_with(ex))
}
fn visit_rs_files(dir: &Path, excluded_dirs: &[PathBuf], f: &mut impl FnMut(PathBuf)) {
if is_excluded_dir(dir, excluded_dirs) {
return;
}
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
if let Some(name) = path.file_name().and_then(|n| n.to_str())
&& is_ignored_dir_name(name)
{
continue;
}
visit_rs_files(&path, excluded_dirs, f);
} else if path.extension().and_then(|e| e.to_str()) == Some("rs") {
f(path);
}
}
}
fn visit_asset_files(path: &Path, excluded_dirs: &[PathBuf], f: &mut impl FnMut(PathBuf)) {
if path.is_file() {
if path.extension().and_then(|e| e.to_str()) != Some("rs")
&& !is_ignored_file_name(path)
&& !is_excluded_dir(path, excluded_dirs)
{
f(path.to_path_buf());
}
return;
}
if !path.is_dir() || is_excluded_dir(path, excluded_dirs) {
return;
}
let Ok(entries) = std::fs::read_dir(path) else {
return;
};
for entry in entries.flatten() {
let child = entry.path();
if child.is_dir() {
if let Some(name) = child.file_name().and_then(|n| n.to_str())
&& is_ignored_dir_name(name)
{
continue;
}
visit_asset_files(&child, excluded_dirs, f);
} else if child.extension().and_then(|e| e.to_str()) != Some("rs")
&& !is_ignored_file_name(&child)
{
f(child);
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ClassifiedFilePatch {
pub path: PathBuf,
pub logs: Vec<String>,
pub messages: Vec<nativeview_engine::HotPatchMsg>,
}
pub enum FileDiff {
NoOp,
Tier1 {
logs: Vec<String>,
messages: Vec<nativeview_engine::HotPatchMsg>,
},
Tier2(String),
}
#[derive(Debug, Default)]
pub struct WatchCache {
workspace_root: Option<PathBuf>,
files: HashMap<PathBuf, String>,
asset_hashes: HashMap<PathBuf, u64>,
last_attempted_hashes: HashMap<PathBuf, Option<u64>>,
}
impl WatchCache {
pub fn new() -> Self {
Self::default()
}
pub fn with_workspace_root(root: impl Into<PathBuf>) -> Self {
Self {
workspace_root: Some(normalize_cache_key(&root.into())),
..Self::default()
}
}
pub fn snapshot_roots(roots: &[PathBuf]) -> WatchSnapshot {
Self::snapshot_roots_with_assets(roots, &[], &[])
}
pub fn snapshot_roots_with_assets(
roots: &[PathBuf],
asset_paths: &[PathBuf],
excluded_dirs: &[PathBuf],
) -> WatchSnapshot {
let mut snap = WatchSnapshot::default();
for root in roots {
visit_rs_files(root, excluded_dirs, &mut |path| {
if let Ok(src) = std::fs::read_to_string(&path) {
snap.rs_files.insert(normalize_cache_key(&path), src);
}
});
}
for asset in asset_paths {
visit_asset_files(asset, excluded_dirs, &mut |path| {
if let Ok(bytes) = std::fs::read(&path) {
snap.asset_hashes
.insert(normalize_cache_key(&path), xxh64(&bytes, 0));
}
});
}
snap
}
pub fn adopt_snapshot(&mut self, snap: WatchSnapshot) {
self.files.clear();
self.asset_hashes.clear();
self.last_attempted_hashes.clear();
for (key, src) in snap.rs_files {
let hash = xxh64(src.as_bytes(), 0);
self.last_attempted_hashes.insert(key.clone(), Some(hash));
self.files.insert(key, src);
}
for (key, hash) in snap.asset_hashes {
self.last_attempted_hashes.insert(key.clone(), Some(hash));
self.asset_hashes.insert(key, hash);
}
}
pub fn record_attempted_snapshot(&mut self, snap: &WatchSnapshot, extra_paths: &[PathBuf]) {
for (key, src) in &snap.rs_files {
self.last_attempted_hashes
.insert(key.clone(), Some(xxh64(src.as_bytes(), 0)));
}
for (key, &hash) in &snap.asset_hashes {
self.last_attempted_hashes.insert(key.clone(), Some(hash));
}
for p in extra_paths {
let key = normalize_cache_key(p);
let h = std::fs::read(&key).ok().map(|b| xxh64(&b, 0));
self.last_attempted_hashes.insert(key, h);
}
}
pub fn seed_dir(&mut self, dir: &Path) {
visit_rs_files(dir, &[], &mut |path| {
if let Ok(src) = std::fs::read_to_string(&path) {
let key = normalize_cache_key(&path);
let hash = xxh64(src.as_bytes(), 0);
self.last_attempted_hashes.insert(key.clone(), Some(hash));
self.files.insert(key, src);
}
});
}
#[cfg(test)]
pub fn update_file(&mut self, path: impl AsRef<Path>, source: String) {
let key = normalize_cache_key(path.as_ref());
let hash = xxh64(source.as_bytes(), 0);
self.last_attempted_hashes.insert(key.clone(), Some(hash));
self.files.insert(key, source);
}
#[cfg(test)]
pub fn cached_source(&self, path: &Path) -> Option<&str> {
self.files
.get(&normalize_cache_key(path))
.map(String::as_str)
}
pub fn len(&self) -> usize {
self.files.len()
}
pub fn is_empty(&self) -> bool {
self.files.is_empty()
}
fn disk_differs_from_attempted(&self, key: &Path, disk_bytes: Option<&[u8]>) -> bool {
let disk_hash = disk_bytes.map(|b| xxh64(b, 0));
if let Some(attempted) = self.last_attempted_hashes.get(key) {
return *attempted != disk_hash;
}
if let Some(&asset_hash) = self.asset_hashes.get(key) {
return Some(asset_hash) != disk_hash;
}
match (self.files.get(key), disk_bytes) {
(Some(src), Some(bytes)) => src.as_bytes() != bytes,
(Some(_), None) => true,
(None, Some(_)) => true,
(None, None) => false,
}
}
pub fn disk_changed_paths(&self, roots: &[PathBuf], filter: &[PathBuf]) -> Vec<PathBuf> {
self.disk_changed_paths_with_assets(roots, &[], &[], filter)
}
pub fn disk_changed_paths_with_assets(
&self,
roots: &[PathBuf],
asset_paths: &[PathBuf],
excluded_dirs: &[PathBuf],
filter: &[PathBuf],
) -> Vec<PathBuf> {
let mut changed = Vec::new();
let mut check_single = |path: &Path| {
let key = normalize_cache_key(path);
if !key.exists() {
if (self.files.contains_key(&key)
|| self.asset_hashes.contains_key(&key)
|| self.last_attempted_hashes.contains_key(&key))
&& self.disk_differs_from_attempted(&key, None)
&& !changed.contains(&key)
{
changed.push(key);
}
return;
}
if !key.is_file() || is_excluded_dir(&key, excluded_dirs) {
return;
}
let Ok(bytes) = std::fs::read(&key) else {
return;
};
if self.disk_differs_from_attempted(&key, Some(&bytes)) && !changed.contains(&key) {
changed.push(key);
}
};
if !filter.is_empty() {
for p in filter {
if p.is_dir() {
let dir_key = normalize_cache_key(p);
visit_rs_files(&dir_key, excluded_dirs, &mut |f| check_single(&f));
visit_asset_files(&dir_key, excluded_dirs, &mut |f| check_single(&f));
for cached_key in self.files.keys().chain(self.asset_hashes.keys()) {
if cached_key.starts_with(&dir_key) && !cached_key.exists() {
check_single(cached_key);
}
}
} else {
check_single(p);
}
}
return changed;
}
for root in roots {
visit_rs_files(root, excluded_dirs, &mut |f| check_single(&f));
}
for asset in asset_paths {
visit_asset_files(asset, excluded_dirs, &mut |f| check_single(&f));
}
for cached_key in self.files.keys().chain(self.asset_hashes.keys()) {
if !cached_key.exists() {
check_single(cached_key);
}
}
changed
}
pub fn classify_batch(
&mut self,
paths: &[PathBuf],
generation: u64,
) -> Result<Vec<ClassifiedFilePatch>, String> {
struct Staged {
key: PathBuf,
new_src: String,
patch: Option<(Vec<String>, Vec<nativeview_engine::HotPatchMsg>)>,
}
let mut staged: Vec<Staged> = Vec::with_capacity(paths.len());
let mut seen_keys: HashSet<PathBuf> = HashSet::with_capacity(paths.len());
for path in paths {
if path.extension().and_then(|e| e.to_str()) != Some("rs") {
return Err(format!("non-Rust file changed: {}", path.display()));
}
let key = normalize_cache_key(path);
if !seen_keys.insert(key.clone()) {
continue;
}
let new_src = std::fs::read_to_string(&key)
.map_err(|err| format!("could not read {}: {err}", path.display()))?;
let Some(old_src) = self.files.get(&key) else {
return Err(format!("new uncached Rust file: {}", path.display()));
};
let rel_file = workspace_relative_path_in(&key, self.workspace_root.as_deref());
let patch = match crate::view_diff::classify_for_watch(
&rel_file, old_src, &new_src, generation,
) {
FileDiff::NoOp => None,
FileDiff::Tier1 { logs, messages } => Some((logs, messages)),
FileDiff::Tier2(reason) => return Err(reason),
};
staged.push(Staged {
key,
new_src,
patch,
});
}
let mut patches = Vec::new();
for item in staged {
let hash = xxh64(item.new_src.as_bytes(), 0);
self.last_attempted_hashes.insert(item.key.clone(), Some(hash));
self.files.insert(item.key.clone(), item.new_src);
if let Some((logs, messages)) = item.patch {
patches.push(ClassifiedFilePatch {
path: item.key,
logs,
messages,
});
}
}
Ok(patches)
}
}
fn normalize_cache_key(path: &Path) -> PathBuf {
canonicalize_preserving_missing(path)
}