use std::io::IsTerminal;
use chrono::Utc;
use colored::Colorize;
use serde_json::{json, Value};
use crate::config::OutputFormat;
use crate::install_method;
use crate::safety::env_is_truthy;
use crate::version_cache::VersionCheckCache;
const BINARY_REPO: &str = "coralogix/cx-cli";
const BREW_FORMULA_URL: &str = "https://formulae.brew.sh/api/formula/cx.json";
pub async fn fetch_if_stale() {
if env_is_truthy("CX_NO_UPDATE_NOTIFIER") {
return;
}
let mut state = VersionCheckCache::load();
if !state.check_is_stale() {
return;
}
let Ok(client) = reqwest::Client::builder()
.user_agent(concat!("cx-cli/", env!("CARGO_PKG_VERSION")))
.timeout(std::time::Duration::from_secs(10))
.build()
else {
return;
};
if let Some(v) = fetch_latest_binary(&client).await {
state.latest_binary = Some(v);
}
state.last_checked_at = Some(Utc::now());
state.installation_id = VersionCheckCache::load()
.installation_id
.or(state.installation_id);
let _ = state.save();
}
async fn fetch_latest_binary(client: &reqwest::Client) -> Option<String> {
match install_method::detect() {
install_method::InstallMethod::Brew => {
let resp = get_json(client, BREW_FORMULA_URL).await?;
brew_stable_version(&resp)
}
_ => {
let url = format!("https://api.github.com/repos/{BINARY_REPO}/releases/latest");
let resp = get_json(client, &url).await?;
github_release_version(&resp)
}
}
}
async fn get_json(client: &reqwest::Client, url: &str) -> Option<Value> {
client.get(url).send().await.ok()?.json().await.ok()
}
fn github_release_version(resp: &Value) -> Option<String> {
resp["tag_name"]
.as_str()
.map(|s| s.trim_start_matches('v').to_string())
}
fn brew_stable_version(resp: &Value) -> Option<String> {
resp["versions"]["stable"].as_str().map(str::to_string)
}
pub fn maybe_print_notice(output: OutputFormat) {
if env_is_truthy("CX_NO_UPDATE_NOTIFIER") {
return;
}
let state = VersionCheckCache::load();
let current = env!("CARGO_PKG_VERSION");
if let Some(latest) = state.latest_binary.as_deref() {
if is_newer(latest, current) {
let upgrade = install_method::binary_upgrade_command(&install_method::detect());
if output == OutputFormat::Toon || !std::io::stderr().is_terminal() {
print_plain_notice(latest, current, &upgrade);
return;
}
let skills = install_method::skills_upgrade_command();
eprintln!();
eprintln!(
"{} {} {} {}{}.",
"cx".bold(),
latest.bold().green(),
"is available (you have".dimmed(),
current.dimmed(),
")".dimmed()
);
eprintln!(
"{} {} {} {} {}",
"upgrade:".dimmed(),
upgrade.bold(),
"|".dimmed(),
"skills:".dimmed(),
skills.bold()
);
eprintln!(
"{}",
"Set CX_NO_UPDATE_NOTIFIER=1 to silence this.".dimmed()
);
}
}
}
pub fn build_meta_block() -> Option<Value> {
if env_is_truthy("CX_NO_UPDATE_NOTIFIER") {
return None;
}
let state = VersionCheckCache::load();
let current = env!("CARGO_PKG_VERSION");
let binary_block = state.latest_binary.as_deref().and_then(|latest| {
if is_newer(latest, current) {
let command = install_method::binary_upgrade_command(&install_method::detect());
Some(json!({ "current": current, "latest": latest, "command": command }))
} else {
None
}
});
binary_block.map(|b| {
json!({
"update": {
"binary": b,
"skills": {
"command": install_method::skills_upgrade_command(),
"docs": install_method::install_docs_url()
}
}
})
})
}
pub fn maybe_print_toon_meta() {
if let Some(meta) = build_meta_block() {
if let Ok(s) = serde_json::to_string(&json!({ "_meta": meta })) {
println!("{s}");
}
}
}
fn print_plain_notice(latest: &str, current: &str, upgrade: &str) {
let skills = install_method::skills_upgrade_command();
eprintln!(
"[cx update] v{latest} available (you have {current}) | upgrade: {upgrade} | skills: {skills}"
);
}
fn is_newer(latest: &str, current: &str) -> bool {
match (parse_version(latest), parse_version(current)) {
(Some(l), Some(c)) => l > c,
_ => false,
}
}
fn parse_version(v: &str) -> Option<(u32, u32, u32)> {
let v = v.strip_prefix('v').unwrap_or(v);
let mut parts = v.splitn(3, '.');
let major: u32 = parts.next()?.parse().ok()?;
let minor: u32 = parts.next()?.parse().ok()?;
let patch_str = parts.next()?;
let patch_digits: &str = patch_str
.split(|c: char| !c.is_ascii_digit())
.next()
.unwrap_or("");
let patch: u32 = patch_digits.parse().ok()?;
Some((major, minor, patch))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn is_newer_latest_greater_than_current() {
assert!(is_newer("1.3.0", "1.2.0"));
assert!(is_newer("2.0.0", "1.9.9"));
assert!(is_newer("0.2.0", "0.1.5"));
}
#[test]
fn is_newer_same_version() {
assert!(!is_newer("1.2.0", "1.2.0"));
}
#[test]
fn is_newer_latest_older_than_current_no_downgrade() {
assert!(!is_newer("0.1.4", "0.1.5"));
assert!(!is_newer("1.2.0", "1.3.0"));
}
#[test]
fn is_newer_unparseable_returns_false() {
assert!(!is_newer("", "1.2.0"));
assert!(!is_newer("1.3.0", ""));
assert!(!is_newer("not-a-version", "1.2.0"));
}
#[test]
fn is_newer_pre_release_suffix_handled() {
assert!(is_newer("0.2.0", "0.1.15-dev"));
assert!(!is_newer("0.1.15", "0.1.15-dev"));
assert!(!is_newer("0.1.14", "0.1.15-dev"));
assert!(is_newer("0.2.0-rc1", "0.1.5"));
}
#[test]
fn is_newer_v_prefix_handled() {
assert!(is_newer("v1.3.0", "1.2.0"));
assert!(is_newer("1.3.0", "v1.2.0"));
assert!(is_newer("v1.3.0", "v1.2.0"));
}
#[test]
fn github_release_version_strips_v_prefix() {
let resp = json!({ "tag_name": "v0.1.29" });
assert_eq!(github_release_version(&resp).as_deref(), Some("0.1.29"));
assert_eq!(github_release_version(&json!({})), None);
}
#[test]
fn brew_stable_version_reads_formula_api() {
let resp = json!({
"name": "cx",
"versions": { "stable": "0.1.28", "head": null, "bottle": true }
});
assert_eq!(brew_stable_version(&resp).as_deref(), Some("0.1.28"));
assert_eq!(brew_stable_version(&json!({})), None);
}
#[test]
fn build_meta_block_suppressed_by_env_var() {
std::env::set_var("CX_NO_UPDATE_NOTIFIER", "1");
let result = build_meta_block();
std::env::remove_var("CX_NO_UPDATE_NOTIFIER");
assert!(result.is_none());
}
}