Skip to main content

nativeview_cli/hot_diff/
cache.rs

1//! Cached diff baselines: the last accepted source of every watched `.rs` file plus web asset
2//! content hashes, classified atomically per save batch through [`crate::view_diff`].
3
4use std::collections::{HashMap, HashSet};
5use std::path::{Path, PathBuf};
6
7use nativeview_abi::xxh64;
8
9pub use super::workspace::workspace_relative_path;
10use super::workspace::workspace_relative_path_in;
11
12/// Pre-build snapshot of watched `.rs` file contents and non-`.rs` web asset content hashes so
13/// adopting baselines after a Tier-2 build never swallows mid-build edits and never redundantly
14/// rebuilds unchanged non-`.rs` web assets on `ForceScan`.
15#[derive(Debug, Default)]
16pub struct WatchSnapshot {
17    rs_files: HashMap<PathBuf, String>,
18    asset_hashes: HashMap<PathBuf, u64>,
19}
20
21pub use nativeview_view_syntax::canonicalize_preserving_missing;
22
23fn is_ignored_dir_name(name: &str) -> bool {
24    matches!(name, "target" | ".git" | "dist" | "node_modules" | "pkg") || name.starts_with('.')
25}
26
27fn is_ignored_file_name(path: &Path) -> bool {
28    let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
29        return true;
30    };
31    name.starts_with('.') || name.ends_with('~') || name.ends_with(".swp") || name.ends_with(".tmp")
32}
33
34fn is_excluded_dir(path: &Path, excluded_dirs: &[PathBuf]) -> bool {
35    if excluded_dirs.is_empty() {
36        return false;
37    }
38    let canon = canonicalize_preserving_missing(path);
39    excluded_dirs.iter().any(|ex| canon.starts_with(ex))
40}
41
42fn visit_rs_files(dir: &Path, excluded_dirs: &[PathBuf], f: &mut impl FnMut(PathBuf)) {
43    if is_excluded_dir(dir, excluded_dirs) {
44        return;
45    }
46    let Ok(entries) = std::fs::read_dir(dir) else {
47        return;
48    };
49    for entry in entries.flatten() {
50        let path = entry.path();
51        if path.is_dir() {
52            if let Some(name) = path.file_name().and_then(|n| n.to_str())
53                && is_ignored_dir_name(name)
54            {
55                continue;
56            }
57            visit_rs_files(&path, excluded_dirs, f);
58        } else if path.extension().and_then(|e| e.to_str()) == Some("rs") {
59            f(path);
60        }
61    }
62}
63
64fn visit_asset_files(path: &Path, excluded_dirs: &[PathBuf], f: &mut impl FnMut(PathBuf)) {
65    if path.is_file() {
66        if path.extension().and_then(|e| e.to_str()) != Some("rs")
67            && !is_ignored_file_name(path)
68            && !is_excluded_dir(path, excluded_dirs)
69        {
70            f(path.to_path_buf());
71        }
72        return;
73    }
74    if !path.is_dir() || is_excluded_dir(path, excluded_dirs) {
75        return;
76    }
77    let Ok(entries) = std::fs::read_dir(path) else {
78        return;
79    };
80    for entry in entries.flatten() {
81        let child = entry.path();
82        if child.is_dir() {
83            if let Some(name) = child.file_name().and_then(|n| n.to_str())
84                && is_ignored_dir_name(name)
85            {
86                continue;
87            }
88            visit_asset_files(&child, excluded_dirs, f);
89        } else if child.extension().and_then(|e| e.to_str()) != Some("rs")
90            && !is_ignored_file_name(&child)
91        {
92            f(child);
93        }
94    }
95}
96
97/// Classified Tier-1 hot-patch output for one watched `.rs` file.
98#[derive(Debug, Clone, PartialEq)]
99pub struct ClassifiedFilePatch {
100    pub path: PathBuf,
101    pub logs: Vec<String>,
102    pub messages: Vec<nativeview_engine::HotPatchMsg>,
103}
104
105/// Classification of one saved `.rs` file against its cached baseline.
106pub enum FileDiff {
107    /// Comment/whitespace-only or semantically identical save.
108    NoOp,
109    /// Tier-1 hot-patch messages plus formatted log lines for watch output.
110    Tier1 {
111        logs: Vec<String>,
112        messages: Vec<nativeview_engine::HotPatchMsg>,
113    },
114    /// Structural/logic edit requiring a Tier-2 rebuild.
115    Tier2(String),
116}
117
118/// Baselines of every watched `.rs` file, content hashes of watched non-`.rs` web assets, and
119/// per-path hashes of the last attempted build so failed Tier-2 builds and repeated `ForceScan`
120/// calls don't loop on unchanged files.
121#[derive(Debug, Default)]
122pub struct WatchCache {
123    workspace_root: Option<PathBuf>,
124    files: HashMap<PathBuf, String>,
125    asset_hashes: HashMap<PathBuf, u64>,
126    last_attempted_hashes: HashMap<PathBuf, Option<u64>>,
127}
128
129impl WatchCache {
130    pub fn new() -> Self {
131        Self::default()
132    }
133
134    /// Creates a watch cache bound to an explicit Cargo `workspace_root` (from `AppContext`) so
135    /// workspace-relative `AnchorKey` paths match `view-macros` without manifest heuristics.
136    pub fn with_workspace_root(root: impl Into<PathBuf>) -> Self {
137        Self {
138            workspace_root: Some(normalize_cache_key(&root.into())),
139            ..Self::default()
140        }
141    }
142
143    /// Reads all `.rs` files under `roots` into an in-memory snapshot BEFORE starting `cargo build`.
144    pub fn snapshot_roots(roots: &[PathBuf]) -> WatchSnapshot {
145        Self::snapshot_roots_with_assets(roots, &[], &[])
146    }
147
148    /// Reads all `.rs` files under `roots` and hashes all non-`.rs` asset files under
149    /// `asset_paths` (skipping ignored dirs and `excluded_dirs`) BEFORE starting a build.
150    pub fn snapshot_roots_with_assets(
151        roots: &[PathBuf],
152        asset_paths: &[PathBuf],
153        excluded_dirs: &[PathBuf],
154    ) -> WatchSnapshot {
155        let mut snap = WatchSnapshot::default();
156        for root in roots {
157            visit_rs_files(root, excluded_dirs, &mut |path| {
158                if let Ok(src) = std::fs::read_to_string(&path) {
159                    snap.rs_files.insert(normalize_cache_key(&path), src);
160                }
161            });
162        }
163        for asset in asset_paths {
164            visit_asset_files(asset, excluded_dirs, &mut |path| {
165                if let Ok(bytes) = std::fs::read(&path) {
166                    snap.asset_hashes
167                        .insert(normalize_cache_key(&path), xxh64(&bytes, 0));
168                }
169            });
170        }
171        snap
172    }
173
174    /// Adopts a pre-build snapshot as the new Tier-1 good baseline after a successful Tier-2 build.
175    pub fn adopt_snapshot(&mut self, snap: WatchSnapshot) {
176        self.files.clear();
177        self.asset_hashes.clear();
178        self.last_attempted_hashes.clear();
179        for (key, src) in snap.rs_files {
180            let hash = xxh64(src.as_bytes(), 0);
181            self.last_attempted_hashes.insert(key.clone(), Some(hash));
182            self.files.insert(key, src);
183        }
184        for (key, hash) in snap.asset_hashes {
185            self.last_attempted_hashes.insert(key.clone(), Some(hash));
186            self.asset_hashes.insert(key, hash);
187        }
188    }
189
190    /// Records the exact content hashes attempted in a failed Tier-2 build (without clobbering the
191    /// last good Tier-1 baselines) so repeated `nv dev wait` calls don't re-run Cargo on the
192    /// same unchanged broken file.
193    pub fn record_attempted_snapshot(&mut self, snap: &WatchSnapshot, extra_paths: &[PathBuf]) {
194        for (key, src) in &snap.rs_files {
195            self.last_attempted_hashes
196                .insert(key.clone(), Some(xxh64(src.as_bytes(), 0)));
197        }
198        for (key, &hash) in &snap.asset_hashes {
199            self.last_attempted_hashes.insert(key.clone(), Some(hash));
200        }
201        for p in extra_paths {
202            let key = normalize_cache_key(p);
203            let h = std::fs::read(&key).ok().map(|b| xxh64(&b, 0));
204            self.last_attempted_hashes.insert(key, h);
205        }
206    }
207
208    /// Recursively loads all `.rs` files under `dir` as Tier-1 diff baselines (lexed lazily).
209    pub fn seed_dir(&mut self, dir: &Path) {
210        visit_rs_files(dir, &[], &mut |path| {
211            if let Ok(src) = std::fs::read_to_string(&path) {
212                let key = normalize_cache_key(&path);
213                let hash = xxh64(src.as_bytes(), 0);
214                self.last_attempted_hashes.insert(key.clone(), Some(hash));
215                self.files.insert(key, src);
216            }
217        });
218    }
219
220    /// Records or replaces the baseline source text for a single file.
221    #[cfg(test)]
222    pub fn update_file(&mut self, path: impl AsRef<Path>, source: String) {
223        let key = normalize_cache_key(path.as_ref());
224        let hash = xxh64(source.as_bytes(), 0);
225        self.last_attempted_hashes.insert(key.clone(), Some(hash));
226        self.files.insert(key, source);
227    }
228
229    /// Returns the cached baseline source for `path`, if present.
230    #[cfg(test)]
231    pub fn cached_source(&self, path: &Path) -> Option<&str> {
232        self.files
233            .get(&normalize_cache_key(path))
234            .map(String::as_str)
235    }
236
237    /// Number of `.rs` files currently cached.
238    pub fn len(&self) -> usize {
239        self.files.len()
240    }
241
242    /// Returns `true` when no `.rs` files are cached.
243    pub fn is_empty(&self) -> bool {
244        self.files.is_empty()
245    }
246
247    fn disk_differs_from_attempted(&self, key: &Path, disk_bytes: Option<&[u8]>) -> bool {
248        let disk_hash = disk_bytes.map(|b| xxh64(b, 0));
249        if let Some(attempted) = self.last_attempted_hashes.get(key) {
250            return *attempted != disk_hash;
251        }
252        if let Some(&asset_hash) = self.asset_hashes.get(key) {
253            return Some(asset_hash) != disk_hash;
254        }
255        match (self.files.get(key), disk_bytes) {
256            (Some(src), Some(bytes)) => src.as_bytes() != bytes,
257            (Some(_), None) => true,
258            (None, Some(_)) => true,
259            (None, None) => false,
260        }
261    }
262
263    /// Scans `roots` (or `filter` paths/directories when non-empty) on disk and returns every
264    /// watched file whose content changed (or was deleted) since the last attempted cycle.
265    pub fn disk_changed_paths(&self, roots: &[PathBuf], filter: &[PathBuf]) -> Vec<PathBuf> {
266        self.disk_changed_paths_with_assets(roots, &[], &[], filter)
267    }
268
269    /// Scans `.rs` files under `roots` and non-`.rs` web assets under `asset_paths` (or `filter`
270    /// paths/directories when non-empty) on disk and returns every changed/deleted file.
271    pub fn disk_changed_paths_with_assets(
272        &self,
273        roots: &[PathBuf],
274        asset_paths: &[PathBuf],
275        excluded_dirs: &[PathBuf],
276        filter: &[PathBuf],
277    ) -> Vec<PathBuf> {
278        let mut changed = Vec::new();
279        let mut check_single = |path: &Path| {
280            let key = normalize_cache_key(path);
281            if !key.exists() {
282                if (self.files.contains_key(&key)
283                    || self.asset_hashes.contains_key(&key)
284                    || self.last_attempted_hashes.contains_key(&key))
285                    && self.disk_differs_from_attempted(&key, None)
286                    && !changed.contains(&key)
287                {
288                    changed.push(key);
289                }
290                return;
291            }
292            if !key.is_file() || is_excluded_dir(&key, excluded_dirs) {
293                return;
294            }
295            let Ok(bytes) = std::fs::read(&key) else {
296                return;
297            };
298            if self.disk_differs_from_attempted(&key, Some(&bytes)) && !changed.contains(&key) {
299                changed.push(key);
300            }
301        };
302
303        if !filter.is_empty() {
304            for p in filter {
305                if p.is_dir() {
306                    let dir_key = normalize_cache_key(p);
307                    visit_rs_files(&dir_key, excluded_dirs, &mut |f| check_single(&f));
308                    visit_asset_files(&dir_key, excluded_dirs, &mut |f| check_single(&f));
309                    for cached_key in self.files.keys().chain(self.asset_hashes.keys()) {
310                        if cached_key.starts_with(&dir_key) && !cached_key.exists() {
311                            check_single(cached_key);
312                        }
313                    }
314                } else {
315                    check_single(p);
316                }
317            }
318            return changed;
319        }
320
321        for root in roots {
322            visit_rs_files(root, excluded_dirs, &mut |f| check_single(&f));
323        }
324        for asset in asset_paths {
325            visit_asset_files(asset, excluded_dirs, &mut |f| check_single(&f));
326        }
327        for cached_key in self.files.keys().chain(self.asset_hashes.keys()) {
328            if !cached_key.exists() {
329                check_single(cached_key);
330            }
331        }
332        changed
333    }
334
335    /// Atomic two-phase batch classification through [`crate::view_diff::classify_for_watch`]:
336    /// classifies every path WITHOUT mutating any baseline first, and only commits updated
337    /// baselines when every file resolves as [`FileDiff::NoOp`] or [`FileDiff::Tier1`]. A
338    /// [`FileDiff::Tier2`] keeps every old baseline so broken intermediate syntax never poisons it.
339    pub fn classify_batch(
340        &mut self,
341        paths: &[PathBuf],
342        generation: u64,
343    ) -> Result<Vec<ClassifiedFilePatch>, String> {
344        struct Staged {
345            key: PathBuf,
346            new_src: String,
347            patch: Option<(Vec<String>, Vec<nativeview_engine::HotPatchMsg>)>,
348        }
349        let mut staged: Vec<Staged> = Vec::with_capacity(paths.len());
350        let mut seen_keys: HashSet<PathBuf> = HashSet::with_capacity(paths.len());
351
352        for path in paths {
353            if path.extension().and_then(|e| e.to_str()) != Some("rs") {
354                return Err(format!("non-Rust file changed: {}", path.display()));
355            }
356            let key = normalize_cache_key(path);
357            if !seen_keys.insert(key.clone()) {
358                continue;
359            }
360            let new_src = std::fs::read_to_string(&key)
361                .map_err(|err| format!("could not read {}: {err}", path.display()))?;
362            let Some(old_src) = self.files.get(&key) else {
363                return Err(format!("new uncached Rust file: {}", path.display()));
364            };
365            let rel_file = workspace_relative_path_in(&key, self.workspace_root.as_deref());
366            let patch = match crate::view_diff::classify_for_watch(
367                &rel_file, old_src, &new_src, generation,
368            ) {
369                FileDiff::NoOp => None,
370                FileDiff::Tier1 { logs, messages } => Some((logs, messages)),
371                FileDiff::Tier2(reason) => return Err(reason),
372            };
373            staged.push(Staged {
374                key,
375                new_src,
376                patch,
377            });
378        }
379
380        let mut patches = Vec::new();
381        for item in staged {
382            let hash = xxh64(item.new_src.as_bytes(), 0);
383            self.last_attempted_hashes.insert(item.key.clone(), Some(hash));
384            self.files.insert(item.key.clone(), item.new_src);
385            if let Some((logs, messages)) = item.patch {
386                patches.push(ClassifiedFilePatch {
387                    path: item.key,
388                    logs,
389                    messages,
390                });
391            }
392        }
393        Ok(patches)
394    }
395}
396
397fn normalize_cache_key(path: &Path) -> PathBuf {
398    canonicalize_preserving_missing(path)
399}