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
//! Source-watch helper utilities and `view!` change classification for `nv dev`.

use std::path::{Component, Path, PathBuf};

use crossbeam_channel::Receiver;
use nativeview_engine::HotPatchMsg;

use crate::cargo_env::{self, AppContext};
use crate::hot_diff;

pub(crate) fn dylib_path_for_package_in(target_dir: &Path, package: &str) -> PathBuf {
    cargo_env::dylib_path_in(target_dir, package, false)
}

/// Resolves canonicalized, deduplicated watch roots for `nv dev`:
/// - Uses explicit `--watch` directories when provided.
/// - Otherwise watches `app.manifest_dir/src` (falling back to `app.manifest_dir` if `src/` does
///   not exist), every transitive non-dev `app.path_deps` crate's `src/` directory, and any
///   optional `extra_paths` (standalone web asset directory or explicit `web.root = "."` files).
pub(crate) fn resolve_watch_roots(
    explicit: &[PathBuf],
    app: &AppContext,
    extra_paths: &[PathBuf],
) -> Vec<PathBuf> {
    let mut raw = Vec::new();
    if !explicit.is_empty() {
        raw.extend(explicit.iter().cloned());
    } else {
        let app_src = app.manifest_dir.join("src");
        if app_src.is_dir() {
            raw.push(app_src);
        } else {
            raw.push(app.manifest_dir.clone());
        }
        for dep_dir in &app.path_deps {
            let dep_src = dep_dir.join("src");
            if dep_src.is_dir() {
                raw.push(dep_src);
            }
        }
        for extra in extra_paths {
            if extra.is_dir() || extra.is_file() {
                raw.push(extra.clone());
            }
        }
    }

    let mut roots = Vec::with_capacity(raw.len());
    for p in raw {
        let canon = hot_diff::cache::canonicalize_preserving_missing(&p);
        if !roots.contains(&canon) {
            roots.push(canon);
        }
    }
    roots
}

pub(crate) fn ws_bind_addr(host: &str, port: u16) -> String {
    crate::pair::format::format_bind_addr(host, port)
}

/// `nv dev` serves `hosts/web-shell`. A bare `/` or `/index.html` (no `ws`, `dev`, `pair` or
/// `bundle` parameter) redirects to itself plus `ws=ws://<request host>:<ws_port>`, which makes
/// `index.html` load the dev bundle connected to this daemon: the dev loop needs no URL flags,
/// and production bundles stay free of hot-reload code.
pub(crate) fn web_dev_redirect(target: &str, host: Option<&str>, ws_port: u16) -> Option<String> {
    let (path, query) = target.split_once('?').unwrap_or((target, ""));
    if path != "/" && path != "/index.html" {
        return None;
    }
    let selects_mode = query.split('&').any(|kv| {
        let key = kv.split_once('=').map_or(kv, |(k, _)| k);
        matches!(key, "ws" | "dev" | "pair" | "bundle")
    });
    if selects_mode {
        return None;
    }
    let hostname = host
        .map(host_without_port)
        .filter(|h| !h.is_empty())
        .unwrap_or("127.0.0.1");
    let sep = if query.is_empty() { "" } else { "&" };
    Some(format!("{path}?{query}{sep}ws=ws://{hostname}:{ws_port}"))
}

fn host_without_port(host: &str) -> &str {
    if host.starts_with('[') {
        return host.find(']').map_or(host, |end| &host[..=end]);
    }
    host.rsplit_once(':').map_or(host, |(h, _)| h)
}

pub(crate) fn should_trigger_rebuild(kind: &notify::EventKind) -> bool {
    matches!(kind, notify::EventKind::Any)
        || kind.is_modify()
        || kind.is_create()
        || kind.is_remove()
}

/// Returns `true` for build-output / VCS / hidden directory components that must never trigger
/// `nv dev` rebuild loops.
pub(crate) fn is_ignored_dir_component(name: &str) -> bool {
    matches!(name, "target" | ".git" | "dist" | "node_modules" | "pkg") || name.starts_with('.')
}

fn has_ignored_ancestor_dir(path: &Path) -> bool {
    let Some(parent) = path.parent() else {
        return false;
    };
    parent.components().any(|c| match c {
        Component::Normal(os) => os.to_str().is_some_and(is_ignored_dir_component),
        _ => false,
    })
}

/// Returns `true` when `path` is a relevant source/asset file that should trigger a watch event,
/// rejecting temp/hidden files, ignored subdirectories (`target`, `.git`, `dist`, `node_modules`,
/// `pkg`, `.*`) relative to the enclosing watch root, and anything under `excluded_dirs` (such as
/// `app.target_directory` or the active web output directory).
pub(crate) fn is_relevant_source_path_in(
    path: &Path,
    watch_roots: &[PathBuf],
    excluded_dirs: &[PathBuf],
) -> bool {
    let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
        return false;
    };
    if name.starts_with('.')
        || name.ends_with('~')
        || name.ends_with(".swp")
        || name.ends_with(".tmp")
    {
        return false;
    }
    if excluded_dirs.iter().any(|ex| path.starts_with(ex)) {
        return false;
    }
    // Check directory components relative to the deepest matching watch root so dot-prefixed
    // worktree ancestors (e.g. `~/.t3/worktrees/...`) do not reject watched files.
    let best_rel = watch_roots
        .iter()
        .filter_map(|root| path.strip_prefix(root).ok())
        .min_by_key(|rel| rel.components().count());
    let inspect = best_rel.unwrap_or(path);
    !has_ignored_ancestor_dir(inspect)
}

#[cfg(test)]
pub(crate) fn is_relevant_source_path(path: &Path) -> bool {
    is_relevant_source_path_in(path, &[], &[])
}

pub(crate) fn make_dylib_reload_msg(
    generation: u64,
    dylib_path: &Path,
    build_ms: u64,
) -> HotPatchMsg {
    HotPatchMsg::DylibReload {
        generation,
        dylib_path: dylib_path.to_string_lossy().into_owned(),
        build_ms,
    }
}

pub(crate) fn collect_relevant_paths(
    event: &notify::Event,
    watch_roots: &[PathBuf],
    excluded_dirs: &[PathBuf],
    out: &mut Vec<PathBuf>,
) {
    if !should_trigger_rebuild(&event.kind) {
        return;
    }
    for p in &event.paths {
        let canon = hot_diff::cache::canonicalize_preserving_missing(p);
        if is_relevant_source_path_in(&canon, watch_roots, excluded_dirs) && !out.contains(&canon) {
            out.push(canon);
        }
    }
}

pub(crate) fn drain_notify_events(
    rx: &Receiver<notify::Result<notify::Event>>,
    watch_roots: &[PathBuf],
    excluded_dirs: &[PathBuf],
    out: &mut Vec<PathBuf>,
) {
    while let Ok(Ok(extra)) = rx.try_recv() {
        collect_relevant_paths(&extra, watch_roots, excluded_dirs, out);
    }
}

pub(crate) fn classify_watch_changes(
    has_built_once: bool,
    changed_paths: &[PathBuf],
    watch_cache: &mut hot_diff::WatchCache,
    next_generation: u64,
) -> (Vec<(PathBuf, Vec<HotPatchMsg>)>, Option<String>) {
    if !has_built_once {
        return (Vec::new(), Some("awaiting first successful build".into()));
    }
    if changed_paths.is_empty() {
        return (Vec::new(), Some("unspecified path event".into()));
    }
    match watch_cache.classify_batch(changed_paths, next_generation) {
        Ok(batch) => {
            let mut tier1_patches = Vec::with_capacity(batch.len());
            for item in batch {
                let file = item.path.display();
                for line in item.logs {
                    println!("[tier-1] {file}: {line}");
                }
                tier1_patches.push((item.path, item.messages));
            }
            (tier1_patches, None)
        }
        Err(reason) => (Vec::new(), Some(reason)),
    }
}