use anyhow::{Context, Result};
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
static CLI_VERSION_DETECTION: AtomicBool = AtomicBool::new(false);
pub fn enable_cli_version_detection() {
CLI_VERSION_DETECTION.store(true, Ordering::Relaxed);
}
fn cli_version_detection_enabled() -> bool {
CLI_VERSION_DETECTION.load(Ordering::Relaxed)
}
pub fn detect_cli_version(bin: &str, cache_file: &str, fallback: &str) -> String {
if !cli_version_detection_enabled() {
return fallback.to_string();
}
if let Some(v) = read_cached_version(cache_file) {
return v;
}
if let Some(v) = run_cli_version(bin) {
let _ = write_cached_version(cache_file, &v);
return v;
}
fallback.to_string()
}
pub fn parse_version(raw: &str) -> Option<String> {
raw.split_whitespace()
.find(|t| t.starts_with(|c: char| c.is_ascii_digit()) && t.contains('.'))
.map(str::to_string)
}
fn read_cached_version(cache_file: &str) -> Option<String> {
read_cached_version_in(&crate::utils::get_cache_dir().ok()?, cache_file)
}
fn read_cached_version_in(dir: &Path, cache_file: &str) -> Option<String> {
let text = std::fs::read_to_string(dir.join(cache_file)).ok()?;
let v: serde_json::Value = serde_json::from_str(&text).ok()?;
if !is_today_utc(v.get("last_checked_at")?.as_str()?) {
return None;
}
v.get("version")?.as_str().map(str::to_string)
}
fn write_cached_version(cache_file: &str, version: &str) -> Result<()> {
write_cached_version_in(&crate::utils::get_cache_dir()?, cache_file, version)
}
fn write_cached_version_in(dir: &Path, cache_file: &str, version: &str) -> Result<()> {
crate::utils::write_json_atomic(
dir.join(cache_file),
&serde_json::json!({
"version": version,
"last_checked_at": crate::utils::now_rfc3339_utc_nanos(),
}),
)
}
fn run_cli_version(bin: &str) -> Option<String> {
let output = std::process::Command::new(bin)
.arg("--version")
.output()
.ok()?;
output.status.success().then_some(())?;
parse_version(&String::from_utf8_lossy(&output.stdout))
}
fn is_today_utc(ts: &str) -> bool {
chrono::DateTime::parse_from_rfc3339(ts)
.map(|dt| dt.with_timezone(&chrono::Utc).date_naive() == chrono::Utc::now().date_naive())
.unwrap_or(false)
}
pub fn build_client() -> Result<reqwest::blocking::Client> {
reqwest::blocking::Client::builder()
.timeout(std::time::Duration::from_secs(8))
.build()
.context("Failed to build HTTP client")
}
pub fn iso_to_unix_secs(s: &str) -> Option<i64> {
let ms = crate::utils::parse_iso_timestamp(s);
(ms > 0).then_some(ms / 1000)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn iso_to_unix_secs_handles_bad_input() {
assert_eq!(iso_to_unix_secs("not-a-date"), None);
assert!(iso_to_unix_secs("2026-07-03T17:09:59.651608+00:00").unwrap() > 0);
}
#[test]
fn is_today_utc_matches_now_but_not_a_past_day() {
let now = crate::utils::now_rfc3339_utc_nanos();
assert!(is_today_utc(&now));
assert!(!is_today_utc("2000-01-01T00:00:00Z"));
assert!(!is_today_utc("not-a-timestamp"));
}
#[test]
fn cli_version_detection_stays_off_outside_the_binary() {
assert!(!cli_version_detection_enabled());
assert_eq!(
detect_cli_version("cargo", "cargo_version.json", "1.2.3"),
"1.2.3"
);
}
#[test]
fn cached_version_round_trips_and_goes_stale_the_next_utc_day() {
let dir = tempfile::tempdir().unwrap();
assert_eq!(
read_cached_version_in(dir.path(), "grok_version.json"),
None
);
write_cached_version_in(dir.path(), "grok_version.json", "0.2.112").unwrap();
assert_eq!(
read_cached_version_in(dir.path(), "grok_version.json").as_deref(),
Some("0.2.112")
);
std::fs::write(
dir.path().join("grok_version.json"),
serde_json::json!({ "version": "0.1.0", "last_checked_at": "2000-01-01T00:00:00Z" })
.to_string(),
)
.unwrap();
assert_eq!(
read_cached_version_in(dir.path(), "grok_version.json"),
None
);
}
#[test]
fn parse_version_handles_leading_or_trailing_labels() {
assert_eq!(
parse_version("2.1.201 (Claude Code)").as_deref(),
Some("2.1.201")
);
assert_eq!(
parse_version("codex-cli 0.142.5").as_deref(),
Some("0.142.5")
);
assert_eq!(parse_version(" 2.0.14\n").as_deref(), Some("2.0.14"));
assert_eq!(parse_version(""), None);
assert_eq!(parse_version("Claude Code"), None);
}
}