mecha10-cli 0.8.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.

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

impl ProcessService {
    /// Find globally installed binary for a node. Searches `~/.cargo/bin/{node_name}` then
    /// `~/.mecha10/bin/{node_name}`.
    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: global installation at
    /// `~/.cargo/bin/mecha10-node-runner`, else falls back to relying on PATH.
    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 `mecha10.json`, defaulting to `true` when absent or unparseable.
    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`).
    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: (1) global installation at ~/.cargo/bin or ~/.mecha10/bin, (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::*;

    /// Falls back to the "current executable" tier when no global/local/cargo-bin binary exists.
    #[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());
    }
}