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
//! `adb` device selection, APK install, and hardened `am start -W` launch verification for
//! `nv run -t android`.

use std::path::Path;
use std::process::Command;

use nativeview_cli::manifest::AndroidShell;

use super::bundle::run_checked;
use super::tools::{detect_adb, detect_android_sdk_root};

/// Android `am start -n` component name for `view` vs `compose`.
pub(crate) fn android_launch_component(app_id: &str, shell: AndroidShell) -> String {
    match shell {
        AndroidShell::Compose => format!("{app_id}/.MainActivity"),
        AndroidShell::View => format!("{app_id}/io.github.nativeview.android.NvMainActivity"),
    }
}

/// Parses `adb devices` output when `--device` is omitted:
/// - 1 online (`device`) device -> returns its serial
/// - >1 online devices -> errors listing all attached online serials
/// - 0 online devices -> errors mentioning any `unauthorized`/`offline` devices
pub(crate) fn parse_adb_devices_output(stdout: &str) -> Result<String, String> {
    let mut online: Vec<&str> = Vec::new();
    let mut other: Vec<(&str, &str)> = Vec::new();
    for line in stdout.lines().skip(1) {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('*') {
            continue;
        }
        let mut cols = trimmed.split_whitespace();
        let (Some(serial), Some(state)) = (cols.next(), cols.next()) else {
            continue;
        };
        if state == "device" {
            online.push(serial);
        } else {
            other.push((serial, state));
        }
    }
    match online.len() {
        1 => Ok(online[0].to_owned()),
        n if n > 1 => Err(format!(
            "multiple online Android devices detected ({}); pass --device <SERIAL> to choose one",
            online.join(", ")
        )),
        _ => {
            if other.is_empty() {
                Err(
                    "no online Android device/emulator found via `adb devices`; start an emulator or pass --device <SERIAL>"
                        .to_owned(),
                )
            } else {
                let details: Vec<String> =
                    other.into_iter().map(|(s, st)| format!("{s} ({st})")).collect();
                Err(format!(
                    "no online Android device ready (found non-ready devices: {}); authorize/boot a device or pass --device <SERIAL>",
                    details.join(", ")
                ))
            }
        }
    }
}

/// Validates `adb shell am start -W` output (Android `am start` exits 0 even on launch errors).
pub(crate) fn validate_am_start_output(stdout: &str, stderr: &str) -> Result<(), String> {
    let combined = format!("{stdout}\n{stderr}");
    for line in combined.lines() {
        let trimmed = line.trim();
        if trimmed.contains("Error:") || trimmed.contains("Exception") {
            return Err(format!("`adb shell am start -W` reported an error: {trimmed}"));
        }
    }
    let has_ok = combined.lines().any(|l| {
        let t = l.trim();
        t.eq_ignore_ascii_case("status: ok") || t.eq_ignore_ascii_case("complete")
    });
    if !has_ok {
        let snippet = combined.trim();
        return Err(if snippet.is_empty() {
            "`adb shell am start -W` produced no launch confirmation (expected 'Status: ok' or 'Complete')".to_owned()
        } else {
            format!(
                "`adb shell am start -W` did not confirm launch ('Status: ok'/'Complete'): {snippet}"
            )
        });
    }
    Ok(())
}

fn select_online_adb_device(adb: &Path) -> Result<String, String> {
    let out = Command::new(adb)
        .arg("devices")
        .output()
        .map_err(|e| format!("failed to run `{} devices`: {e}", adb.display()))?;
    if !out.status.success() {
        return Err(format!("`{} devices` failed with {}", adb.display(), out.status));
    }
    parse_adb_devices_output(&String::from_utf8_lossy(&out.stdout))
}

/// Installs and launches a built Android APK via `adb`.
pub(crate) fn run_android_apk(
    apk_path: &Path,
    app_id: &str,
    shell: AndroidShell,
    device_serial: Option<&str>,
) -> Result<(), String> {
    let sdk_root = detect_android_sdk_root().ok();
    let adb = detect_adb(sdk_root.as_deref())?;
    let serial = match device_serial.map(str::trim).filter(|s| !s.is_empty()) {
        Some(s) => s.to_owned(),
        None => select_online_adb_device(&adb)?,
    };
    let component = android_launch_component(app_id, shell);

    println!("==> Installing {} onto {serial}...", apk_path.display());
    run_checked(
        Command::new(&adb).args(["-s", &serial, "install", "-r"]).arg(apk_path),
        "adb install -r",
    )?;
    println!("==> Launching {component} on {serial}...");
    let out = Command::new(&adb)
        .args(["-s", &serial, "shell", "am", "start", "-W", "-n", &component])
        .output()
        .map_err(|e| format!("failed to run `adb shell am start`: {e}"))?;
    let stdout = String::from_utf8_lossy(&out.stdout);
    let stderr = String::from_utf8_lossy(&out.stderr);
    if !stdout.is_empty() {
        print!("{stdout}");
    }
    if !stderr.is_empty() {
        eprint!("{stderr}");
    }
    if !out.status.success() {
        return Err(format!("`adb shell am start` failed with {}", out.status));
    }
    validate_am_start_output(&stdout, &stderr)
}