Skip to main content

cascade_environment/
probe.rs

1//! Pure parsers for environment backend command output.
2
3use std::path::PathBuf;
4
5use crate::{ExecutableOrigin, ResolvedExecutable, classify_wsl_executable};
6
7/// Captured output from one backend probe before domain parsing.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct ProbeOutput {
10    pub stdout: String,
11    pub stderr: String,
12    pub exit_code: Option<i32>,
13}
14
15impl ProbeOutput {
16    pub fn succeeded(&self) -> bool {
17        self.exit_code == Some(0)
18    }
19}
20
21/// Parses `wsl --list --quiet` output without assuming PowerShell's encoding.
22///
23/// Embedded NUL characters are removed because some Windows command-capture
24/// paths decode UTF-16 output as alternating characters and NULs.
25pub fn parse_wsl_distributions(output: &str) -> Vec<String> {
26    output
27        .replace('\0', "")
28        .lines()
29        .map(|line| line.trim().trim_start_matches('*').trim())
30        .filter(|line| !line.is_empty())
31        .map(str::to_owned)
32        .collect()
33}
34
35/// Returns the first non-empty line produced by `command -v` or an equivalent probe.
36pub fn parse_executable_path(output: &str) -> Option<PathBuf> {
37    output
38        .replace('\0', "")
39        .lines()
40        .map(str::trim)
41        .find(|line| !line.is_empty())
42        .map(PathBuf::from)
43}
44
45/// Returns a compact first-line version without inventing provider semantics.
46pub fn parse_version_output(output: &str) -> Option<String> {
47    output
48        .replace('\0', "")
49        .lines()
50        .map(str::trim)
51        .find(|line| !line.is_empty())
52        .map(str::to_owned)
53}
54
55/// Builds a resolved WSL executable from independently captured path and version probes.
56pub fn parse_wsl_resolved_executable(
57    command: impl Into<String>,
58    path_output: &str,
59    version_output: &str,
60) -> Option<ResolvedExecutable> {
61    let command = command.into();
62    let path = parse_executable_path(path_output)?;
63    let origin = classify_wsl_executable(&path);
64    Some(ResolvedExecutable {
65        command,
66        path,
67        origin,
68        version: parse_version_output(version_output),
69    })
70}
71
72/// Builds a host executable report. A host-resolved absolute path is native to
73/// the host environment; unresolved relative output remains unknown.
74pub fn parse_host_resolved_executable(
75    command: impl Into<String>,
76    path_output: &str,
77    version_output: &str,
78) -> Option<ResolvedExecutable> {
79    let command = command.into();
80    let path = parse_executable_path(path_output)?;
81    let origin = if path.is_absolute() {
82        ExecutableOrigin::Native
83    } else {
84        ExecutableOrigin::Unknown
85    };
86    Some(ResolvedExecutable {
87        command,
88        path,
89        origin,
90        version: parse_version_output(version_output),
91    })
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97
98    #[test]
99    fn parses_wsl_distribution_fixture_with_nuls_and_default_marker() {
100        assert_eq!(
101            parse_wsl_distributions("U\0b\0u\0n\0t\0u\0\r\0\n\0* Debian\r\n"),
102            ["Ubuntu", "Debian"]
103        );
104    }
105
106    #[test]
107    fn parses_first_non_empty_executable_and_version_lines() {
108        assert_eq!(
109            parse_executable_path("\n/usr/bin/git\nignored"),
110            Some(PathBuf::from("/usr/bin/git"))
111        );
112        assert_eq!(
113            parse_version_output("\ngit version 2.45.1\n"),
114            Some("git version 2.45.1".to_owned())
115        );
116    }
117
118    #[test]
119    fn parses_native_and_host_inherited_wsl_tools() {
120        let native =
121            parse_wsl_resolved_executable("git", "/usr/bin/git\n", "git version 2.45.1\n").unwrap();
122        let inherited = parse_wsl_resolved_executable(
123            "codex",
124            "/mnt/d/Users/user/AppData/Roaming/npm/codex\n",
125            "codex-cli 0.144.5\n",
126        )
127        .unwrap();
128
129        assert_eq!(native.origin, ExecutableOrigin::Native);
130        assert_eq!(inherited.origin, ExecutableOrigin::HostInherited);
131    }
132
133    #[test]
134    fn missing_path_does_not_create_resolved_executable() {
135        assert!(parse_wsl_resolved_executable("codex", "\n", "").is_none());
136    }
137}