use std::{
fs,
path::Path,
process::{Command, Stdio},
time::{SystemTime, UNIX_EPOCH},
};
use serde::{Deserialize, Serialize};
use crate::{
action::{resolve_action_dev_tag, resolve_dev_tag},
env_file, ui,
};
const ENV_PATH: &str = ".codezero/.env";
const CACHE_PATH: &str = ".codezero/update-check.json";
const CHECK_INTERVAL_SECS: u64 = 60 * 60 * 24;
pub const CHECK_SUBCOMMAND: &str = "__check-updates";
#[derive(Debug, Serialize, Deserialize)]
struct UpdateCheck {
checked_at: u64,
latest_tag: String,
#[serde(default)]
latest_action_tag: String,
}
fn now_secs() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|duration| duration.as_secs())
.unwrap_or(0)
}
fn load_cache() -> Option<UpdateCheck> {
let data = fs::read_to_string(CACHE_PATH).ok()?;
serde_json::from_str(&data).ok()
}
fn write_cache(check: &UpdateCheck) -> anyhow::Result<()> {
let json = serde_json::to_string_pretty(check)?;
fs::write(CACHE_PATH, json)?;
Ok(())
}
fn is_stale(cache: &Option<UpdateCheck>) -> bool {
match cache {
None => true,
Some(check) => now_secs().saturating_sub(check.checked_at) >= CHECK_INTERVAL_SECS,
}
}
fn pipeline_id(tag: &str) -> Option<u64> {
let rest = tag.strip_prefix("0.0.0-experimental-")?;
let (id, _sha) = rest.split_once('-')?;
id.parse().ok()
}
fn is_newer(current: &str, latest: &str) -> bool {
match (pipeline_id(current), pipeline_id(latest)) {
(Some(current_id), Some(latest_id)) => latest_id > current_id,
_ => false,
}
}
pub fn run_background_check() -> anyhow::Result<()> {
let latest_tag = resolve_dev_tag()?;
let latest_action_tag = resolve_action_dev_tag()?;
write_cache(&UpdateCheck {
checked_at: now_secs(),
latest_tag,
latest_action_tag,
})
}
pub fn maybe_spawn_background_check() {
if !Path::new(ENV_PATH).exists() || !is_stale(&load_cache()) {
return;
}
let Ok(exe) = std::env::current_exe() else {
return;
};
let _ = Command::new(exe)
.arg(CHECK_SUBCOMMAND)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn();
}
pub fn show_reminder() {
let Some(cache) = load_cache() else {
return;
};
let current_core = env_file::read_value(ENV_PATH, "IMAGE_TAG")
.ok()
.flatten()
.unwrap_or_default();
let current_actions = env_file::read_value(ENV_PATH, "ACTION_IMAGE_TAG")
.ok()
.flatten()
.unwrap_or_default();
let core_behind = is_newer(¤t_core, &cache.latest_tag);
let actions_behind = is_newer(¤t_actions, &cache.latest_action_tag);
if core_behind || actions_behind {
let latest = if core_behind {
&cache.latest_tag
} else {
&cache.latest_action_tag
};
println!();
ui::muted_line(&format!(
"A newer CodeZero build is available ({latest})."
));
ui::muted_line(
"You can update now with `codezero --upgrade --dev` (experimental — a dedicated `upgrade` command is coming).",
);
}
}
pub fn record_current_tag(core_tag: &str, action_tag: &str) {
let _ = write_cache(&UpdateCheck {
checked_at: now_secs(),
latest_tag: core_tag.to_string(),
latest_action_tag: action_tag.to_string(),
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pipeline_id_parses_experimental_tags() {
assert_eq!(
pipeline_id("0.0.0-experimental-12345-abcdef0"),
Some(12345)
);
}
#[test]
fn pipeline_id_rejects_non_experimental_tags() {
assert_eq!(pipeline_id("latest"), None);
assert_eq!(pipeline_id("1.2.3"), None);
assert_eq!(pipeline_id("0.0.0-experimental-notanumber-sha"), None);
}
#[test]
fn is_newer_compares_pipeline_ids() {
let older = "0.0.0-experimental-100-aaa";
let newer = "0.0.0-experimental-200-bbb";
assert!(is_newer(older, newer));
assert!(!is_newer(newer, older));
assert!(!is_newer(newer, newer));
}
#[test]
fn is_newer_is_false_for_floating_or_unparseable_current() {
let latest = "0.0.0-experimental-200-bbb";
assert!(!is_newer("latest", latest));
assert!(!is_newer("1.2.3", latest));
assert!(!is_newer("0.0.0-experimental-100-aaa", "latest"));
}
#[test]
fn is_stale_when_missing_or_past_the_interval() {
assert!(is_stale(&None));
assert!(is_stale(&Some(UpdateCheck {
checked_at: now_secs().saturating_sub(CHECK_INTERVAL_SECS + 1),
latest_tag: "x".into(),
latest_action_tag: "x".into(),
})));
}
#[test]
fn is_fresh_within_the_interval() {
assert!(!is_stale(&Some(UpdateCheck {
checked_at: now_secs(),
latest_tag: "x".into(),
latest_action_tag: "x".into(),
})));
}
#[test]
fn update_check_round_trips_through_json() {
let check = UpdateCheck {
checked_at: 1_700_000_000,
latest_tag: "0.0.0-experimental-42-deadbee".into(),
latest_action_tag: "0.0.0-experimental-7-c0ffee0".into(),
};
let json = serde_json::to_string(&check).unwrap();
let parsed: UpdateCheck = serde_json::from_str(&json).unwrap();
assert_eq!(parsed.checked_at, check.checked_at);
assert_eq!(parsed.latest_tag, check.latest_tag);
assert_eq!(parsed.latest_action_tag, check.latest_action_tag);
}
#[test]
fn old_cache_without_action_tag_deserializes_to_empty() {
let json = r#"{"checked_at":1700000000,"latest_tag":"0.0.0-experimental-42-deadbee"}"#;
let parsed: UpdateCheck = serde_json::from_str(json).unwrap();
assert_eq!(parsed.latest_action_tag, "");
assert!(!is_newer("0.0.0-experimental-1-aaa", &parsed.latest_action_tag));
}
}