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
//! `cargo nv docs build` — delegates static SSR + WASM site builds to the selected docs site
//! package binary (`--site-package`, auto-detecting `nativeview-docs-site` inside the workspace).

use std::path::PathBuf;
use std::process::Command;

use crate::cargo_env::{self, CargoMetadata, CargoPackageInfo};

const DEFAULT_WORKSPACE_DOCS_SITE_PKG: &str = "nativeview-docs-site";

/// Build configuration for `cargo nv docs build`.
#[derive(Debug, Clone)]
pub(crate) struct BuildOptions {
    pub content: PathBuf,
    pub out: PathBuf,
    pub base_path: String,
    pub site_url: String,
    pub skip_wasm: bool,
    pub web_shell_dist: Option<PathBuf>,
    pub with_examples: bool,
    pub site_package: Option<String>,
}

/// Pre-built docs site binary resolved once per `nv docs` invocation so `docs dev` never
/// re-invokes `cargo metadata` or `cargo build` on `.mdx` content edits.
#[derive(Debug, Clone)]
pub(crate) struct SitePackageBin {
    pub package: String,
    pub bin_path: PathBuf,
    pub target_dir: PathBuf,
}

/// Selects the binary target of a docs site package: a binary matching `pkg.name`, or the single
/// declared binary.
pub(crate) fn select_site_bin_target(pkg: &CargoPackageInfo) -> Result<&str, String> {
    let bin_name = if let Some(exact) = pkg.bin_names.iter().find(|b| b.as_str() == pkg.name) {
        exact.as_str()
    } else if let [only] = pkg.bin_names.as_slice() {
        only.as_str()
    } else if pkg.bin_names.is_empty() {
        return Err(format!(
            "docs site package '{}' declares no binary target",
            pkg.name
        ));
    } else {
        return Err(format!(
            "docs site package '{}' declares multiple binary targets ({}) and none matches the package name",
            pkg.name,
            pkg.bin_names.join(", ")
        ));
    };
    Ok(bin_name)
}

/// Resolves and builds the site builder binary ONCE using preloaded `CargoMetadata`.
pub(crate) fn resolve_site_package_bin(
    meta: Option<&CargoMetadata>,
    explicit_pkg: Option<&str>,
) -> Result<Option<SitePackageBin>, String> {
    let owned_meta;
    let resolved_meta = match meta {
        Some(m) => m,
        None => match cargo_env::load_cargo_metadata(None) {
            Ok(m) => {
                owned_meta = m;
                &owned_meta
            }
            Err(err) => {
                if explicit_pkg.is_some() {
                    return Err(err);
                }
                return Ok(None);
            }
        },
    };

    let (pkg, is_explicit) = if let Some(pkg_name) = explicit_pkg {
        let found = cargo_env::find_package(resolved_meta, pkg_name).ok_or_else(|| {
            format!("docs site package '{pkg_name}' not found in `cargo metadata`")
        })?;
        (found, true)
    } else if let Some(found) =
        cargo_env::find_package(resolved_meta, DEFAULT_WORKSPACE_DOCS_SITE_PKG)
    {
        (found, false)
    } else {
        return Ok(None);
    };

    let bin_name = match select_site_bin_target(pkg) {
        Ok(sel) => sel,
        Err(err) if is_explicit => return Err(err),
        Err(_) => return Ok(None),
    };

    let bin_path =
        cargo_env::build_workspace_bin_in(resolved_meta, &pkg.name, bin_name)?;
    Ok(Some(SitePackageBin {
        package: pkg.name.clone(),
        bin_path,
        target_dir: resolved_meta.target_directory.clone(),
    }))
}

/// Executes a static docs build using an already-built [`SitePackageBin`] (zero Cargo calls).
pub(crate) fn run_build_with_bin(
    site_bin: &SitePackageBin,
    opts: &BuildOptions,
) -> Result<(), String> {
    let mut cmd = Command::new(&site_bin.bin_path);
    cmd.arg("build")
        .arg("--content")
        .arg(&opts.content)
        .arg("--out")
        .arg(&opts.out)
        .arg("--base-path")
        .arg(&opts.base_path)
        .arg("--site-url")
        .arg(&opts.site_url)
        .arg("--target-dir")
        .arg(&site_bin.target_dir);
    if opts.skip_wasm {
        cmd.arg("--skip-wasm");
    }
    if let Some(dist) = &opts.web_shell_dist {
        cmd.arg("--web-shell-dist").arg(dist);
    }
    if opts.with_examples {
        cmd.arg("--with-examples");
    }

    let status = cmd.status().map_err(|e| {
        format!(
            "failed to run docs site binary '{}' ({}): {e}",
            site_bin.bin_path.display(),
            site_bin.package
        )
    })?;
    if status.success() {
        Ok(())
    } else {
        Err(format!("`{} build` exited with {status}", site_bin.package))
    }
}

/// Executes the static documentation site build via the resolved site package binary.
pub(crate) fn run_build(opts: &BuildOptions) -> Result<(), String> {
    let meta = cargo_env::load_cargo_metadata(None).ok();
    let Some(site_bin) = resolve_site_package_bin(meta.as_ref(), opts.site_package.as_deref())?
    else {
        return Err(
            "no docs site package found in workspace; pass `--site-package <cargo-pkg>` (or run `nv docs check --generic --content <dir>` for standalone MDX validation)".to_owned(),
        );
    };
    run_build_with_bin(&site_bin, opts)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn pkg(name: &str, bins: &[&str], features: &[&str]) -> CargoPackageInfo {
        CargoPackageInfo {
            id: format!("path+file:///repo/{name}#0.1.0"),
            name: name.to_owned(),
            version: "0.1.0".to_owned(),
            manifest_path: PathBuf::from(format!("/repo/{name}/Cargo.toml")),
            cdylib_name: None,
            bin_names: bins.iter().map(|s| (*s).to_owned()).collect(),
            features: features.iter().map(|s| (*s).to_owned()).collect(),
            path_deps: Vec::new(),
            host_module: None,
        }
    }

    #[test]
    fn select_site_bin_target_auto_selects_matching_or_single_bin() {
        let default_site = pkg("nativeview-docs-site", &["helper", "nativeview-docs-site"], &["default"]);
        assert_eq!(select_site_bin_target(&default_site).unwrap(), "nativeview-docs-site");

        let custom_single = pkg("acme-docs", &["build-docs"], &["default"]);
        assert_eq!(select_site_bin_target(&custom_single).unwrap(), "build-docs");

        let no_bins = pkg("acme-docs", &[], &[]);
        assert!(select_site_bin_target(&no_bins).is_err());

        let ambiguous = pkg("acme-docs", &["one", "two"], &[]);
        assert!(select_site_bin_target(&ambiguous).is_err());
    }
}