use std::path::PathBuf;
use crate::{ExecutableOrigin, ResolvedExecutable, classify_wsl_executable};
#[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)
}
}
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()
}
pub fn parse_executable_path(output: &str) -> Option<PathBuf> {
output
.replace('\0', "")
.lines()
.map(str::trim)
.find(|line| !line.is_empty())
.map(PathBuf::from)
}
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)
}
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),
})
}
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());
}
}