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
//! Real Mach-O macOS `.app` bundle packager (zero bash wrappers).
//!
//! Layout emitted under `<out_dir>/<Executable>.app`:
//! - `Contents/MacOS/<Executable>`          (real Mach-O shell binary, chmod 0755)
//! - `Contents/Frameworks/libnv_app.dylib` (app cdylib with `@rpath/libnv_app.dylib` install_name)
//! - `Contents/Info.plist`                  (generated from `nativeview.toml`, linted via `plutil -lint`)
//!
//! Signed bottom-up with ad-hoc `codesign` (dylib first, then `.app` with `--identifier` and
//! optional entitlements) and verified with `codesign --verify --deep --strict`.

use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::UNIX_EPOCH;

use nativeview_abi::xxh64;
use nativeview_cli::manifest::{ManifestAppInfo, NvManifest};

use crate::build::host_cache::HostShell;

const DEV_BUNDLE_STAMP_SEED: u64 = 0x4E56_4544_4556_4231;

/// Resolved paths inside a packaged macOS `.app` bundle.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct MacosBundleOutput {
    pub app_bundle: PathBuf,
    pub executable_path: PathBuf,
    pub dylib_path: PathBuf,
    pub plist_path: PathBuf,
    pub bundle_id: String,
}

/// Returns `true` when `nv run` on macOS should exec `Contents/MacOS/<Executable>` directly
/// (forwarding stdio, cwd, exit codes, and SIGINT) instead of launching via `open -W -n`.
pub(crate) fn should_direct_exec_macos(direct: bool, shell_args: &[String]) -> bool {
    direct
        || shell_args.iter().any(|a| {
            a == "--screenshot" || a.starts_with("--screenshot=") || a == "--help" || a == "-h"
        })
}

/// Computes the macOS `CFBundleIdentifier` (`<id>` for `--shell macos`, `<id>.skia` for `--shell skia`).
pub(crate) fn macos_bundle_id(
    manifest: &NvManifest,
    info: &ManifestAppInfo,
    shell: HostShell,
) -> String {
    let base = manifest.resolved_id(info);
    if shell == HostShell::Skia {
        format!("{base}.skia")
    } else {
        base
    }
}

struct TempFileGuard(Option<PathBuf>);

impl Drop for TempFileGuard {
    fn drop(&mut self) {
        if let Some(p) = self.0.take() {
            let _ = fs::remove_file(p);
        }
    }
}

pub(crate) fn run_checked(program: &str, args: &[String]) -> Result<(), String> {
    let out = Command::new(program)
        .args(args)
        .output()
        .map_err(|e| format!("failed to run `{program}`: {e}"))?;
    if !out.status.success() {
        let stderr = String::from_utf8_lossy(&out.stderr);
        let stdout = String::from_utf8_lossy(&out.stdout);
        let detail = if !stderr.trim().is_empty() { stderr.trim() } else { stdout.trim() };
        return Err(if detail.is_empty() {
            format!("`{program} {}` failed with {}", args.join(" "), out.status)
        } else {
            format!("`{program} {}` failed with {}: {detail}", args.join(" "), out.status)
        });
    }
    Ok(())
}

#[cfg(unix)]
pub(crate) fn set_mode(path: &Path, mode: u32) -> Result<(), String> {
    use std::os::unix::fs::PermissionsExt;
    let perms = fs::Permissions::from_mode(mode);
    fs::set_permissions(path, perms)
        .map_err(|e| format!("failed to chmod '{}' to {mode:o}: {e}", path.display()))
}

#[cfg(not(unix))]
pub(crate) fn set_mode(_path: &Path, _mode: u32) -> Result<(), String> {
    Ok(())
}

/// Ad-hoc signs an Apple `.app` bundle bottom-up (optional embedded dylib first, then the `.app`
/// with `--identifier` and optional linted entitlements) and verifies with `--deep --strict`.
pub(crate) fn sign_apple_bundle(
    out_dir: &Path,
    app_bundle: &Path,
    executable: &str,
    bundle_id: &str,
    dylib_path: Option<&Path>,
    entitlements_xml: Option<&str>,
) -> Result<(), String> {
    let ent_guard = match entitlements_xml {
        Some(ent_xml) => {
            let tmp_ent = out_dir.join(format!(
                ".{executable}.entitlements-{}.plist",
                std::process::id()
            ));
            fs::write(&tmp_ent, ent_xml)
                .map_err(|e| format!("failed to write '{}': {e}", tmp_ent.display()))?;
            let guard = TempFileGuard(Some(tmp_ent.clone()));
            run_checked("plutil", &["-lint".to_owned(), tmp_ent.display().to_string()])?;
            guard
        }
        None => TempFileGuard(None),
    };

    if let Some(dylib) = dylib_path {
        run_checked(
            "codesign",
            &[
                "--force".to_owned(),
                "--sign".to_owned(),
                "-".to_owned(),
                dylib.display().to_string(),
            ],
        )?;
    }

    let mut app_sign_args = vec![
        "--force".to_owned(),
        "--sign".to_owned(),
        "-".to_owned(),
        "--identifier".to_owned(),
        bundle_id.to_owned(),
    ];
    if let Some(ent_path) = ent_guard.0.as_ref() {
        app_sign_args.push("--entitlements".to_owned());
        app_sign_args.push(ent_path.display().to_string());
    }
    app_sign_args.push(app_bundle.display().to_string());
    run_checked("codesign", &app_sign_args)?;
    run_checked(
        "codesign",
        &[
            "--verify".to_owned(),
            "--deep".to_owned(),
            "--strict".to_owned(),
            app_bundle.display().to_string(),
        ],
    )?;
    drop(ent_guard);
    Ok(())
}

/// Packages `shell_binary` and `app_dylib` into a real signed Mach-O `<Executable>.app` bundle.
pub(crate) fn package_macos_app_bundle(
    out_dir: &Path,
    manifest: &NvManifest,
    info: &ManifestAppInfo,
    shell: HostShell,
    shell_binary: &Path,
    app_dylib: &Path,
) -> Result<MacosBundleOutput, String> {
    package_macos_app_bundle_inner(out_dir, manifest, info, shell, shell_binary, Some(app_dylib))
}

/// Computes a deterministic 16-hex cache stamp for a dev macOS `.app` bundle from `shell_binary`
/// size/mtime, `executable`, `bundle_id`, `Info.plist`, and optional entitlements plist.
pub(crate) fn compute_dev_bundle_stamp(
    executable: &str,
    bundle_id: &str,
    shell_binary: &Path,
    plist_xml: &str,
    ent_xml: Option<&str>,
) -> Result<String, String> {
    let meta = fs::metadata(shell_binary).map_err(|e| {
        format!("failed to stat shell binary '{}': {e}", shell_binary.display())
    })?;
    let mtime_nanos = meta
        .modified()
        .ok()
        .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
        .map_or(0u128, |d| d.as_nanos());
    let mut buf = Vec::with_capacity(
        64 + executable.len() + bundle_id.len() + plist_xml.len() + ent_xml.map_or(0, str::len),
    );
    buf.extend_from_slice(&meta.len().to_le_bytes());
    buf.extend_from_slice(&mtime_nanos.to_le_bytes());
    buf.extend_from_slice(&(executable.len() as u64).to_le_bytes());
    buf.extend_from_slice(executable.as_bytes());
    buf.extend_from_slice(&(bundle_id.len() as u64).to_le_bytes());
    buf.extend_from_slice(bundle_id.as_bytes());
    buf.extend_from_slice(&(plist_xml.len() as u64).to_le_bytes());
    buf.extend_from_slice(plist_xml.as_bytes());
    if let Some(ent) = ent_xml {
        buf.push(1);
        buf.extend_from_slice(&(ent.len() as u64).to_le_bytes());
        buf.extend_from_slice(ent.as_bytes());
    } else {
        buf.push(0);
    }
    Ok(format!("{:016x}", xxh64(&buf, DEV_BUNDLE_STAMP_SEED)))
}

/// Packages or reuses a cached dev-only macOS `.app` bundle (without copying `libnv_app.dylib`,
/// since `nv dev --skia` always passes `--dylib <live_target_dylib>`).
/// Returns `(executable_path, reused_from_cache)`.
pub(crate) fn package_or_reuse_macos_dev_bundle(
    out_dir: &Path,
    manifest: &NvManifest,
    info: &ManifestAppInfo,
    shell: HostShell,
    shell_binary: &Path,
) -> Result<(PathBuf, bool), String> {
    let executable = manifest.resolved_executable(info);
    let bundle_id = macos_bundle_id(manifest, info, shell);
    let plist_xml = manifest.emit_macos_info_plist(info, Some(&bundle_id));
    let ent_xml = manifest.emit_apple_entitlements_plist();
    let stamp = compute_dev_bundle_stamp(
        &executable,
        &bundle_id,
        shell_binary,
        &plist_xml,
        ent_xml.as_deref(),
    )?;

    let app_bundle = out_dir.join(format!("{executable}.app"));
    let executable_path = app_bundle.join("Contents").join("MacOS").join(&executable);
    let plist_path = app_bundle.join("Contents").join("Info.plist");
    let stamp_path = out_dir.join(".bundle-stamp");
    if executable_path.is_file()
        && plist_path.is_file()
        && fs::read_to_string(&stamp_path)
            .ok()
            .is_some_and(|cached| cached.trim() == stamp)
    {
        return Ok((executable_path, true));
    }

    let bundle = package_macos_app_bundle_inner(out_dir, manifest, info, shell, shell_binary, None)?;
    fs::write(&stamp_path, format!("{stamp}\n"))
        .map_err(|e| format!("failed to write '{}': {e}", stamp_path.display()))?;
    Ok((bundle.executable_path, false))
}

fn package_macos_app_bundle_inner(
    out_dir: &Path,
    manifest: &NvManifest,
    info: &ManifestAppInfo,
    shell: HostShell,
    shell_binary: &Path,
    app_dylib: Option<&Path>,
) -> Result<MacosBundleOutput, String> {
    let executable = manifest.resolved_executable(info);
    let bundle_id = macos_bundle_id(manifest, info, shell);
    let app_bundle = out_dir.join(format!("{executable}.app"));
    let contents_dir = app_bundle.join("Contents");
    let macos_dir = contents_dir.join("MacOS");
    let frameworks_dir = contents_dir.join("Frameworks");

    if app_bundle.exists() {
        fs::remove_dir_all(&app_bundle).map_err(|e| {
            format!("failed to clean previous bundle '{}': {e}", app_bundle.display())
        })?;
    }
    fs::create_dir_all(&macos_dir)
        .map_err(|e| format!("failed to create '{}': {e}", macos_dir.display()))?;
    if app_dylib.is_some() {
        fs::create_dir_all(&frameworks_dir)
            .map_err(|e| format!("failed to create '{}': {e}", frameworks_dir.display()))?;
    }

    // 1. Copy real Mach-O host binary to Contents/MacOS/<Executable>.
    let executable_path = macos_dir.join(&executable);
    fs::copy(shell_binary, &executable_path).map_err(|e| {
        format!(
            "failed to copy shell binary '{}' -> '{}': {e}",
            shell_binary.display(),
            executable_path.display()
        )
    })?;
    set_mode(&executable_path, 0o755)?;

    // 2. Optionally copy app cdylib to Contents/Frameworks/libnv_app.dylib (omitted for `nv dev`
    //    bundles because `--dylib <live_target_dylib>` overrides it at launch).
    let dylib_path = frameworks_dir.join("libnv_app.dylib");
    if let Some(src_dylib) = app_dylib {
        fs::copy(src_dylib, &dylib_path).map_err(|e| {
            format!(
                "failed to copy app dylib '{}' -> '{}': {e}",
                src_dylib.display(),
                dylib_path.display()
            )
        })?;
        set_mode(&dylib_path, 0o755)?;
        run_checked(
            "install_name_tool",
            &[
                "-id".to_owned(),
                "@rpath/libnv_app.dylib".to_owned(),
                dylib_path.display().to_string(),
            ],
        )?;
    }

    // 3. Emit and lint Contents/Info.plist.
    let plist_path = contents_dir.join("Info.plist");
    let plist_xml = manifest.emit_macos_info_plist(info, Some(&bundle_id));
    fs::write(&plist_path, plist_xml)
        .map_err(|e| format!("failed to write '{}': {e}", plist_path.display()))?;
    run_checked("plutil", &["-lint".to_owned(), plist_path.display().to_string()])?;

    // 4. Ad-hoc sign bottom-up (dylib first when present, then `.app` bundle) and verify strictly.
    let ent_xml = manifest.emit_apple_entitlements_plist();
    sign_apple_bundle(
        out_dir,
        &app_bundle,
        &executable,
        &bundle_id,
        app_dylib.map(|_| dylib_path.as_path()),
        ent_xml.as_deref(),
    )?;

    Ok(MacosBundleOutput { app_bundle, executable_path, dylib_path, plist_path, bundle_id })
}

/// Launches a packaged macOS `.app` bundle either directly (`Contents/MacOS/<Executable>`) or via
/// `open -W -n`.
pub(crate) fn launch_macos_app(
    app_bundle: &Path,
    executable: &Path,
    direct_exec: bool,
    shell_args: &[String],
) -> Result<(), String> {
    if direct_exec {
        println!("==> Running {} directly...", executable.display());
        let status = Command::new(executable)
            .args(shell_args)
            .status()
            .map_err(|e| format!("failed to spawn '{}': {e}", executable.display()))?;
        if !status.success() {
            return Err(format!("app exited with {status}"));
        }
    } else {
        let mut cmd = Command::new("open");
        cmd.args(["-W", "-n"]).arg(app_bundle);
        if !shell_args.is_empty() {
            cmd.arg("--args").args(shell_args);
        }
        println!("==> Launching {}...", app_bundle.display());
        let status = cmd.status().map_err(|e| format!("failed to spawn `open`: {e}"))?;
        if !status.success() {
            return Err(format!("app exited with {status}"));
        }
    }
    Ok(())
}