nativeview-cli 0.1.0-rc.1

Developer CLI (`nv`) for Native View Engine: dev hot-reload, builds, pairing, SDK management, app scaffolding, and docs.
Documentation
//! Cached diff baselines: the last accepted source of every watched `.rs` file plus web asset
//! content hashes, classified atomically per save batch through [`crate::view_diff`].

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;

/// Pre-build snapshot of watched `.rs` file contents and non-`.rs` web asset content hashes so
/// adopting baselines after a Tier-2 build never swallows mid-build edits and never redundantly
/// rebuilds unchanged non-`.rs` web assets on `ForceScan`.
#[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);
        }
    }
}

/// Classified Tier-1 hot-patch output for one watched `.rs` file.
#[derive(Debug, Clone, PartialEq)]
pub struct ClassifiedFilePatch {
    pub path: PathBuf,
    pub logs: Vec<String>,
    pub messages: Vec<nativeview_engine::HotPatchMsg>,
}

/// Classification of one saved `.rs` file against its cached baseline.
pub enum FileDiff {
    /// Comment/whitespace-only or semantically identical save.
    NoOp,
    /// Tier-1 hot-patch messages plus formatted log lines for watch output.
    Tier1 {
        logs: Vec<String>,
        messages: Vec<nativeview_engine::HotPatchMsg>,
    },
    /// Structural/logic edit requiring a Tier-2 rebuild.
    Tier2(String),
}

/// Baselines of every watched `.rs` file, content hashes of watched non-`.rs` web assets, and
/// per-path hashes of the last attempted build so failed Tier-2 builds and repeated `ForceScan`
/// calls don't loop on unchanged files.
#[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()
    }

    /// Creates a watch cache bound to an explicit Cargo `workspace_root` (from `AppContext`) so
    /// workspace-relative `AnchorKey` paths match `view-macros` without manifest heuristics.
    pub fn with_workspace_root(root: impl Into<PathBuf>) -> Self {
        Self {
            workspace_root: Some(normalize_cache_key(&root.into())),
            ..Self::default()
        }
    }

    /// Reads all `.rs` files under `roots` into an in-memory snapshot BEFORE starting `cargo build`.
    pub fn snapshot_roots(roots: &[PathBuf]) -> WatchSnapshot {
        Self::snapshot_roots_with_assets(roots, &[], &[])
    }

    /// Reads all `.rs` files under `roots` and hashes all non-`.rs` asset files under
    /// `asset_paths` (skipping ignored dirs and `excluded_dirs`) BEFORE starting a build.
    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
    }

    /// Adopts a pre-build snapshot as the new Tier-1 good baseline after a successful Tier-2 build.
    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);
        }
    }

    /// Records the exact content hashes attempted in a failed Tier-2 build (without clobbering the
    /// last good Tier-1 baselines) so repeated `nv dev wait` calls don't re-run Cargo on the
    /// same unchanged broken file.
    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);
        }
    }

    /// Recursively loads all `.rs` files under `dir` as Tier-1 diff baselines (lexed lazily).
    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);
            }
        });
    }

    /// Records or replaces the baseline source text for a single file.
    #[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);
    }

    /// Returns the cached baseline source for `path`, if present.
    #[cfg(test)]
    pub fn cached_source(&self, path: &Path) -> Option<&str> {
        self.files
            .get(&normalize_cache_key(path))
            .map(String::as_str)
    }

    /// Number of `.rs` files currently cached.
    pub fn len(&self) -> usize {
        self.files.len()
    }

    /// Returns `true` when no `.rs` files are cached.
    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,
        }
    }

    /// Scans `roots` (or `filter` paths/directories when non-empty) on disk and returns every
    /// watched file whose content changed (or was deleted) since the last attempted cycle.
    pub fn disk_changed_paths(&self, roots: &[PathBuf], filter: &[PathBuf]) -> Vec<PathBuf> {
        self.disk_changed_paths_with_assets(roots, &[], &[], filter)
    }

    /// Scans `.rs` files under `roots` and non-`.rs` web assets under `asset_paths` (or `filter`
    /// paths/directories when non-empty) on disk and returns every changed/deleted file.
    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
    }

    /// Atomic two-phase batch classification through [`crate::view_diff::classify_for_watch`]:
    /// classifies every path WITHOUT mutating any baseline first, and only commits updated
    /// baselines when every file resolves as [`FileDiff::NoOp`] or [`FileDiff::Tier1`]. A
    /// [`FileDiff::Tier2`] keeps every old baseline so broken intermediate syntax never poisons it.
    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)
}