cascade-environment 0.1.0-alpha.2

Execution-environment detection and planning contracts for Cascade.
Documentation
//! Pure parsers for environment backend command output.

use std::path::PathBuf;

use crate::{ExecutableOrigin, ResolvedExecutable, classify_wsl_executable};

/// Captured output from one backend probe before domain parsing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProbeOutput {
    pub stdout: String,
    pub stderr: String,
    pub exit_code: Option<i32>,
}

impl ProbeOutput {
    pub fn succeeded(&self) -> bool {
        self.exit_code == Some(0)
    }
}

/// Parses `wsl --list --quiet` output without assuming PowerShell's encoding.
///
/// Embedded NUL characters are removed because some Windows command-capture
/// paths decode UTF-16 output as alternating characters and NULs.
pub fn parse_wsl_distributions(output: &str) -> Vec<String> {
    output
        .replace('\0', "")
        .lines()
        .map(|line| line.trim().trim_start_matches('*').trim())
        .filter(|line| !line.is_empty())
        .map(str::to_owned)
        .collect()
}

/// Returns the first non-empty line produced by `command -v` or an equivalent probe.
pub fn parse_executable_path(output: &str) -> Option<PathBuf> {
    output
        .replace('\0', "")
        .lines()
        .map(str::trim)
        .find(|line| !line.is_empty())
        .map(PathBuf::from)
}

/// Returns a compact first-line version without inventing provider semantics.
pub fn parse_version_output(output: &str) -> Option<String> {
    output
        .replace('\0', "")
        .lines()
        .map(str::trim)
        .find(|line| !line.is_empty())
        .map(str::to_owned)
}

/// Builds a resolved WSL executable from independently captured path and version probes.
pub fn parse_wsl_resolved_executable(
    command: impl Into<String>,
    path_output: &str,
    version_output: &str,
) -> Option<ResolvedExecutable> {
    let command = command.into();
    let path = parse_executable_path(path_output)?;
    let origin = classify_wsl_executable(&path);
    Some(ResolvedExecutable {
        command,
        path,
        origin,
        version: parse_version_output(version_output),
    })
}

/// Builds a host executable report. A host-resolved absolute path is native to
/// the host environment; unresolved relative output remains unknown.
pub fn parse_host_resolved_executable(
    command: impl Into<String>,
    path_output: &str,
    version_output: &str,
) -> Option<ResolvedExecutable> {
    let command = command.into();
    let path = parse_executable_path(path_output)?;
    let origin = if path.is_absolute() {
        ExecutableOrigin::Native
    } else {
        ExecutableOrigin::Unknown
    };
    Some(ResolvedExecutable {
        command,
        path,
        origin,
        version: parse_version_output(version_output),
    })
}

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

    #[test]
    fn parses_wsl_distribution_fixture_with_nuls_and_default_marker() {
        assert_eq!(
            parse_wsl_distributions("U\0b\0u\0n\0t\0u\0\r\0\n\0* Debian\r\n"),
            ["Ubuntu", "Debian"]
        );
    }

    #[test]
    fn parses_first_non_empty_executable_and_version_lines() {
        assert_eq!(
            parse_executable_path("\n/usr/bin/git\nignored"),
            Some(PathBuf::from("/usr/bin/git"))
        );
        assert_eq!(
            parse_version_output("\ngit version 2.45.1\n"),
            Some("git version 2.45.1".to_owned())
        );
    }

    #[test]
    fn parses_native_and_host_inherited_wsl_tools() {
        let native =
            parse_wsl_resolved_executable("git", "/usr/bin/git\n", "git version 2.45.1\n").unwrap();
        let inherited = parse_wsl_resolved_executable(
            "codex",
            "/mnt/d/Users/user/AppData/Roaming/npm/codex\n",
            "codex-cli 0.144.5\n",
        )
        .unwrap();

        assert_eq!(native.origin, ExecutableOrigin::Native);
        assert_eq!(inherited.origin, ExecutableOrigin::HostInherited);
    }

    #[test]
    fn missing_path_does_not_create_resolved_executable() {
        assert!(parse_wsl_resolved_executable("codex", "\n", "").is_none());
    }
}