mecha10-cli 0.7.0

Mecha10 CLI tool
Documentation
//! Binary path resolution for `ProcessService`
//!
//! Handles finding globally installed binaries and resolving paths to the
//! `mecha10-node-runner` binary and the `mecha10` CLI binary itself. Node
//! binary resolution for framework nodes is handled by `BinaryManager`
//! (see `spawn_node.rs`), which errors immediately on an unresolvable binary
//! rather than falling back through further tiers.

use super::ProcessService;
use crate::paths;
use anyhow::Result;

impl ProcessService {
    /// Find globally installed binary for a node
    ///
    /// Searches in:
    /// 1. ~/.cargo/bin/{node_name}
    /// 2. ~/.mecha10/bin/{node_name}
    ///
    /// # Arguments
    ///
    /// * `node_name` - Name of the node (e.g., "camera")
    ///
    /// # Returns
    ///
    /// Path to the binary if found, None otherwise
    pub fn find_global_binary(node_name: &str) -> Option<std::path::PathBuf> {
        let cargo_bin = paths::user::cargo_bin(node_name);
        if cargo_bin.exists() && cargo_bin.is_file() {
            return Some(cargo_bin);
        }

        let mecha10_bin = paths::user::bin(node_name);
        if mecha10_bin.exists() && mecha10_bin.is_file() {
            return Some(mecha10_bin);
        }

        None
    }

    /// Resolve path to mecha10-node-runner binary
    ///
    /// Resolution strategy:
    /// 1. Global installation: ~/.cargo/bin/mecha10-node-runner
    /// 2. Fallback: "mecha10-node-runner" (rely on PATH)
    ///
    /// # Returns
    ///
    /// Path to the mecha10-node-runner binary
    pub fn resolve_node_runner_path() -> String {
        if let Some(global_path) = Self::find_global_binary("mecha10-node-runner") {
            return global_path.to_string_lossy().to_string();
        }

        "mecha10-node-runner".to_string()
    }

    /// Get the version for a node from the project config
    pub(super) fn get_node_version_from_config(&self, node_identifier: &str) -> Option<String> {
        use crate::types::ProjectConfig;

        let config_path = std::path::Path::new(paths::PROJECT_CONFIG);
        if !config_path.exists() {
            return None;
        }

        let config_content = std::fs::read_to_string(config_path).ok()?;
        let config: ProjectConfig = serde_json::from_str(&config_content).ok()?;

        config.nodes.get_version(node_identifier).map(|s| s.to_string())
    }

    /// Check whether disk-based logging is enabled for the current project's *current*
    /// environment (LAB-2041).
    ///
    /// Reads `environments.<current_env>.logging.disk_logging_enabled` from the
    /// project's `mecha10.json`, where `<current_env>` is whatever
    /// `EnvironmentsConfig::current_env_name` resolves to (`MECHA10_ENV`, defaulting to
    /// "dev"). Defaults to `true` (existing behavior) when no project config is
    /// present, it can't be parsed, or the current environment has no `logging`
    /// section, so projects without an explicit override are unaffected.
    ///
    /// Edge/robot deployments that already ship logs to a remote server can set this to
    /// `false` on their `prod`/`staging` environment to avoid unbounded local disk
    /// growth and repeated writes wearing out SD/USB storage, without disabling disk
    /// logging in `dev` too. This has no effect on remote/network log shipping.
    pub(super) fn disk_logging_enabled(&self) -> bool {
        use crate::types::ProjectConfig;

        let config_path = std::path::Path::new(paths::PROJECT_CONFIG);
        if !config_path.exists() {
            return true;
        }

        let config_content = match std::fs::read_to_string(config_path) {
            Ok(c) => c,
            Err(_) => return true,
        };

        let config: ProjectConfig = match serde_json::from_str(&config_content) {
            Ok(c) => c,
            Err(_) => return true,
        };

        config.environments.disk_logging_enabled()
    }

    /// Check if a node is a local project node (declared with `NodeSource::Project` in
    /// `mecha10.json`) - delegates to `mecha10_cli_core::types::is_local_project_node`, the
    /// same check `mecha10-node-runner`'s `resolve_node_execution` uses, so the two can't
    /// drift onto different classification rules for the same node.
    pub(super) fn is_local_project_node(&self, node_name: &str) -> bool {
        mecha10_cli_core::types::is_local_project_node(std::path::Path::new(paths::PROJECT_CONFIG), node_name)
    }

    /// Resolve path to mecha10 CLI binary
    ///
    /// Tiers below (`LAB-4558`: sequenced via `mecha10_binary_naming::try_resolution_tiers!`,
    /// the same ordered-fallback-chain helper shared with `BinaryManager::resolve_with_version`
    /// and `NodeResolver::resolve_with_version` - only the concrete tiers here are CLI-specific):
    /// 1. Global installation: ~/.cargo/bin/mecha10 or ~/.mecha10/bin/mecha10
    /// 2. Local/cargo bin fallback locations
    /// 3. The currently running executable
    pub(super) fn resolve_cli_binary() -> Result<String> {
        mecha10_binary_naming::try_resolution_tiers!("mecha10 CLI binary", {
            "global binary" => Self::find_global_binary("mecha10")
                .map(|path| path.to_string_lossy().to_string())
                .ok_or_else(|| "not found at ~/.cargo/bin or ~/.mecha10/bin".to_string()),

            "local/cargo bin fallback locations" => {
                let locations = [paths::user::local_bin("mecha10"), paths::user::cargo_bin("mecha10")];
                locations
                    .iter()
                    .find(|path| path.exists())
                    .map(|path| path.to_string_lossy().to_string())
                    .ok_or_else(|| "not found at local_bin/cargo_bin fallback locations".to_string())
            },

            "current executable" => std::env::current_exe()
                .map(|exe| exe.to_string_lossy().to_string())
                .map_err(|e| format!("current_exe() failed: {e}")),
        })
        .map_err(|e| anyhow::anyhow!("{}. Ensure it's installed and in your PATH.", e))
    }

    /// Check if mecha10-node-runner is available
    pub fn is_node_runner_available() -> bool {
        Self::find_global_binary("mecha10-node-runner").is_some()
    }
}

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

    /// `resolve_cli_binary` falls all the way through to the "current executable" tier when
    /// none of the global/local/cargo-bin locations exist (the common case for `cargo test`,
    /// where none of those directories contain a `mecha10` binary) - this must still resolve
    /// successfully via `std::env::current_exe()` rather than erroring, preserving the
    /// pre-`LAB-4558` three-tier fallback behavior.
    #[test]
    fn resolve_cli_binary_falls_back_to_current_exe_when_no_global_or_local_binary_exists() {
        let resolved = ProcessService::resolve_cli_binary().expect("current_exe() tier must succeed");
        assert!(!resolved.is_empty());
    }
}