use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use super::cli::{Cli, clis};
use super::{executable::resolve, status::run};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "camelCase")]
#[non_exhaustive]
pub enum Auth {
SignedIn { account: Option<String> },
SignedOut,
Unknown,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Report {
pub cli: Cli,
pub path: Option<PathBuf>,
pub version: Option<String>,
pub auth: Auth,
pub detail: Option<String>,
}
impl Report {
pub fn new(cli: Cli) -> Self {
Self {
cli,
path: None,
version: None,
auth: Auth::Unknown,
detail: None,
}
}
pub fn installed(&self) -> bool {
self.path.is_some()
}
}
pub async fn probe(cli: Cli, executable: Option<&Path>) -> Report {
let program = executable
.map(Path::to_path_buf)
.unwrap_or_else(|| PathBuf::from(cli.program()));
let Some(path) = resolve(&program).await else {
return Report {
detail: Some(format!("`{}` was not found", program.display())),
..Report::new(cli)
};
};
let mut detail = None;
let version = match run(&path, &["--version"]).await {
Ok(out) => parse_version(&out.stdout),
Err(error) => {
detail = Some(error);
None
}
};
let (auth, auth_detail) = (cli.auth)(&path).await;
Report {
cli,
path: Some(path),
version,
auth,
detail: detail.or(auth_detail),
}
}
pub async fn probe_all() -> Vec<Report> {
futures::future::join_all(clis().iter().map(|&cli| probe(cli, None))).await
}
fn parse_version(stdout: &str) -> Option<String> {
stdout
.split_whitespace()
.map(|word| word.trim_start_matches('v'))
.find(|word| {
let mut parts = word.split('.');
parts
.next()
.is_some_and(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()))
&& parts
.next()
.is_some_and(|p| p.chars().next().is_some_and(|c| c.is_ascii_digit()))
})
.map(str::to_owned)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn versions_are_read_from_each_harness() {
assert_eq!(
parse_version("2.1.322 (Claude Code)\n").as_deref(),
Some("2.1.322")
);
assert_eq!(
parse_version("codex-cli 0.167.1\n").as_deref(),
Some("0.167.1")
);
assert_eq!(parse_version("1.0.2\n").as_deref(), Some("1.0.2"));
assert_eq!(parse_version("v3.4.0").as_deref(), Some("3.4.0"));
assert_eq!(parse_version("no version here"), None);
}
}