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
//! `nv xcframework` subcommand — Apple Tier-3 staticlib & `.xcframework` build recipes.

use std::collections::HashSet;
use std::env;
use std::ffi::OsStr;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use super::tier3::{
    parse_targets, plan_tier3_build, AppleTier3BuildPlan, Tier3BuildRequest, Tier3Error,
    DEFAULT_HEADERS_REL_PATH,
};
use crate::build::probe::{check_prerequisites, EnvironmentProbe, PrerequisiteIssue, SystemProbe};
use crate::cargo_env;

pub(crate) struct XcframeworkOptions {
    pub targets: Vec<String>,
    pub package: String,
    pub lib_name: Option<String>,
    pub release: bool,
    pub toolchain: String,
    pub xcframework: Option<PathBuf>,
    pub headers: Option<PathBuf>,
    pub target_dir: Option<PathBuf>,
    pub dry_run: bool,
}

fn resolve_headers_dir(repo_root: &Path, override_dir: Option<PathBuf>) -> PathBuf {
    if let Some(dir) = override_dir {
        return if dir.is_absolute() { dir } else { repo_root.join(dir) };
    }
    repo_root.join(DEFAULT_HEADERS_REL_PATH)
}

pub(crate) fn format_xcframework_plan(
    plan: &AppleTier3BuildPlan,
    issues: &[PrerequisiteIssue],
) -> String {
    let mut out = String::new();
    let profile = if plan.release { "release" } else { "debug" };
    out.push_str(&format!(
        "Native View Engine — Apple Tier-3 Build Plan ({}, profile={profile}, toolchain={})\n",
        plan.package, plan.toolchain
    ));
    out.push_str(
        "Linkage: staticlib (zero dlopen) -> register nv_get_interface via NvStaticInterfaceTable (NvInterfaceResolver.swift)\n\n",
    );

    for (idx, step) in plan.cargo_steps.iter().enumerate() {
        let spec = step.target.spec();
        out.push_str(&format!(
            "[step {}/{}] {} ({}, sdk={}, min_os={})\n",
            idx + 1,
            plan.cargo_steps.len(),
            spec.cli_name,
            spec.rust_triple,
            spec.sdk_name,
            spec.min_os_version
        ));
        for (k, v) in &step.env {
            out.push_str(&format!("  env  {k}={v}\n"));
        }
        out.push_str(&format!("  cmd  {} {}\n", step.program, step.args.join(" ")));
        out.push_str(&format!("  out  {}\n", step.output_staticlib.display()));
        out.push_str(&format!("  link {}\n\n", step.linkage.swift_registration));
    }

    if let Some(xcf) = &plan.xcframework {
        out.push_str(&format!(
            "[xcframework] {} ({} slice(s), headers={})\n",
            xcf.output_path.display(),
            xcf.slices.len(),
            xcf.headers_dir.display()
        ));
        out.push_str(&format!("  cmd  {} {}\n", xcf.program, xcf.args.join(" ")));
        let present: HashSet<_> = xcf.slices.iter().map(|s| s.target).collect();
        for slice in &xcf.slices {
            if !present.contains(&slice.target.counterpart()) {
                let [dev, sim] = slice.target.spec().family.pair();
                out.push_str(&format!(
                    "  tip  pair device + simulator slices with '--target {},{}'\n",
                    dev.spec().cli_name,
                    sim.spec().cli_name
                ));
            }
        }
        out.push('\n');
    }

    if !issues.is_empty() {
        out.push_str("Prerequisite warnings:\n");
        for issue in issues {
            out.push_str(&format!(
                "  [WARN] {}\n         fix: {}\n",
                issue.summary, issue.remediation
            ));
        }
    }
    out
}

pub(crate) fn build_request_from_options_with_roots(
    opts: &XcframeworkOptions,
    app_workspace_root: &Path,
    sdk_root: &Path,
    cwd: &Path,
    env_target_dir: Option<&OsStr>,
) -> Result<Tier3BuildRequest, Tier3Error> {
    let targets = parse_targets(&opts.targets)?;
    let lib_name = opts
        .lib_name
        .clone()
        .filter(|s| !s.trim().is_empty())
        .unwrap_or_else(|| opts.package.replace('-', "_"));
    let target_dir = cargo_env::resolve_target_dir_with_env(
        app_workspace_root,
        cwd,
        opts.target_dir.clone(),
        env_target_dir,
    );
    let headers_dir = resolve_headers_dir(sdk_root, opts.headers.clone());
    let xcframework_out = opts.xcframework.as_ref().map(|p| {
        if p.as_os_str().is_empty() || p == Path::new("auto") {
            target_dir.join("xcframework").join(format!("{lib_name}.xcframework"))
        } else if p.is_absolute() {
            p.clone()
        } else {
            app_workspace_root.join(p)
        }
    });

    Ok(Tier3BuildRequest {
        targets,
        package: opts.package.clone(),
        lib_name,
        release: opts.release,
        toolchain: opts.toolchain.clone(),
        target_dir,
        headers_dir,
        xcframework_out,
    })
}

#[cfg(test)]
pub(crate) fn build_request_from_options_with_env(
    opts: &XcframeworkOptions,
    repo_root: &Path,
    cwd: &Path,
    env_target_dir: Option<&OsStr>,
) -> Result<Tier3BuildRequest, Tier3Error> {
    build_request_from_options_with_roots(opts, repo_root, repo_root, cwd, env_target_dir)
}

#[cfg(test)]
pub(crate) fn run_xcframework_with_probe(
    opts: XcframeworkOptions,
    repo_root: &Path,
    probe: &dyn EnvironmentProbe,
) -> Result<String, String> {
    let cwd = env::current_dir().unwrap_or_else(|_| repo_root.to_path_buf());
    run_xcframework_with_roots(opts, repo_root, repo_root, &cwd, probe)
}

pub(crate) fn run_xcframework_with_roots(
    opts: XcframeworkOptions,
    app_workspace_root: &Path,
    sdk_root: &Path,
    cwd: &Path,
    probe: &dyn EnvironmentProbe,
) -> Result<String, String> {
    let env_target_dir = env::var_os("CARGO_TARGET_DIR");
    let req = build_request_from_options_with_roots(
        &opts,
        app_workspace_root,
        sdk_root,
        cwd,
        env_target_dir.as_deref(),
    )
    .map_err(|e| e.to_string())?;
    let issues = check_prerequisites(
        &req.targets,
        &req.toolchain,
        req.xcframework_out.is_some(),
        &req.headers_dir,
        probe,
    );
    let plan = plan_tier3_build(&req, probe).map_err(|e| e.to_string())?;

    if opts.dry_run {
        return Ok(format_xcframework_plan(&plan, &issues));
    }
    if !issues.is_empty() {
        return Err(Tier3Error::MissingPrerequisites(issues).to_string());
    }

    for step in &plan.cargo_steps {
        println!(
            "==> Building '{}' for {} ({})...",
            plan.package,
            step.target.spec().cli_name,
            step.target.spec().rust_triple
        );
        let status = Command::new(&step.program)
            .current_dir(app_workspace_root)
            .args(&step.args)
            .envs(&step.env)
            .status()
            .map_err(|e| format!("failed to spawn {}: {e}", step.program))?;
        if !status.success() {
            return Err(format!(
                "cargo build failed for target '{}' with exit status {status}",
                step.target.spec().cli_name
            ));
        }
    }

    if let Some(xcf) = &plan.xcframework {
        if xcf.output_path.exists() {
            fs::remove_dir_all(&xcf.output_path).map_err(|e| {
                format!("failed to remove stale xcframework '{}': {e}", xcf.output_path.display())
            })?;
        }
        if let Some(parent) = xcf.output_path.parent() {
            fs::create_dir_all(parent).map_err(|e| {
                format!("failed to create xcframework parent '{}': {e}", parent.display())
            })?;
        }
        println!("==> Bundling XCFramework '{}'...", xcf.output_path.display());
        let status = Command::new(&xcf.program)
            .current_dir(app_workspace_root)
            .args(&xcf.args)
            .status()
            .map_err(|e| format!("failed to spawn {}: {e}", xcf.program))?;
        if !status.success() {
            return Err(format!(
                "xcodebuild -create-xcframework failed with exit status {status}"
            ));
        }
    }

    Ok(format_xcframework_plan(&plan, &[]))
}

pub(crate) fn cmd_xcframework(opts: XcframeworkOptions) {
    let cwd = env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let env_sdk = env::var("NV_SDK_ROOT").ok();
    let meta = cargo_env::load_cargo_metadata(None).ok();
    let app_workspace_root = meta
        .as_ref()
        .map(|m| m.workspace_root.clone())
        .unwrap_or_else(cargo_env::find_workspace_root);
    let sdk_root = meta
        .as_ref()
        .and_then(|m| cargo_env::resolve_sdk_root(None, env_sdk.as_deref(), m, &cwd, &cwd).ok())
        .map(|sdk| sdk.0)
        .unwrap_or_else(|| app_workspace_root.clone());
    match run_xcframework_with_roots(opts, &app_workspace_root, &sdk_root, &cwd, &SystemProbe) {
        Ok(report) => print!("{report}"),
        Err(err) => {
            eprintln!("error: {err}");
            std::process::exit(1);
        }
    }
}