silcrow 0.2.1

Deterministic CLI for a citable, checkable graph of laws in a git tree.
use std::io::IsTerminal;
use std::path::{Path, PathBuf};
use std::thread::JoinHandle;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use anyhow::Result;
use semver::Version;
use serde_json::{json, Value};

use crate::upgrade::{REPO_NAME, REPO_OWNER};

const FETCH_EVERY: u64 = 24 * 3600;
const NOTICE_EVERY: u64 = 3600;
// The command waits for this fetch before it exits, once a day at most.
const FETCH_TIMEOUT: Duration = Duration::from_secs(2);
const CURRENT: &str = env!("CARGO_PKG_VERSION");

#[derive(Debug, Default, Clone, PartialEq, Eq)]
struct Ledger {
    tried_at: Option<u64>,
    latest: Option<String>,
    noticed_at: Option<u64>,
}

/// A release check started with the command and finished after it.
pub struct Notice {
    path: PathBuf,
    ledger: Ledger,
    fetch: Option<JoinHandle<Result<String>>>,
}

/// `None` when nothing may be printed. The fetch, if due, runs while the command does.
pub fn begin_release_check(allowed: bool) -> Option<Notice> {
    // § nfzrg1qsg@9vd23
    let ci = std::env::var("CI").ok();
    // § one nfzrg1qsg.b@wmyaf
    if !(allowed && eligible(std::io::stderr().is_terminal(), ci.as_deref())) {
        return None;
    }
    let path = ledger_path(
        std::env::var_os("XDG_CACHE_HOME").map(PathBuf::from),
        std::env::var_os("HOME").map(PathBuf::from),
    )?;
    Notice::open_ledger(path, unix_now()?, || fetch_latest(FETCH_TIMEOUT))
}

/// Prints the line when one is due.
pub fn print_release_notice(notice: Option<Notice>) {
    let Some((notice, now)) = notice.zip(unix_now()) else {
        return;
    };
    if let Some(line) = notice.close_ledger(now) {
        eprintln!("{line}");
    }
}

impl Notice {
    fn open_ledger(
        path: PathBuf,
        now: u64,
        fetch: impl FnOnce() -> Result<String> + Send + 'static,
    ) -> Option<Self> {
        // § nfzrg1qsg.b@4cgpz
        let mut ledger = read_ledger(&path);
        let mut handle = None;
        if fetch_due(&ledger, now) {
            // Stamped before the fetch, so a failure or a concurrent command waits a day too.
            // A stamp that cannot be written would fetch on every command, so it fetches none.
            ledger.tried_at = Some(now);
            write_ledger(&path, &ledger).ok()?;
            handle = Some(std::thread::spawn(fetch));
        }
        Some(Self {
            path,
            ledger,
            fetch: handle,
        })
    }

    fn close_ledger(mut self, now: u64) -> Option<String> {
        // § nfzrg1qsg.a@89qbn
        let before = self.ledger.clone();
        if let Some(Ok(Ok(latest))) = self.fetch.take().map(JoinHandle::join) {
            self.ledger.latest = Some(latest);
        }
        let line = notice_line(&self.ledger, CURRENT, now);
        if line.is_some() {
            self.ledger.noticed_at = Some(now);
        }
        if self.ledger != before {
            let _ = write_ledger(&self.path, &self.ledger);
        }
        line
    }
}

fn eligible(stderr_tty: bool, ci: Option<&str>) -> bool {
    // § nfzrg1qsg.b@wkxw2
    stderr_tty && !ci_job(ci)
}

/// Whether `CI`, read as `ci`, names a CI job: set to a value other than empty, `0` or `false`.
pub fn ci_job(ci: Option<&str>) -> bool {
    ci.is_some_and(|value| {
        let value = value.trim();
        !value.is_empty() && value != "0" && !value.eq_ignore_ascii_case("false")
    })
}

fn ledger_path(xdg_cache: Option<PathBuf>, home: Option<PathBuf>) -> Option<PathBuf> {
    let cache = match xdg_cache.filter(|dir| dir.is_absolute()) {
        Some(dir) => dir,
        None => home.filter(|dir| dir.is_absolute())?.join(".cache"),
    };
    Some(cache.join("silcrow").join("release.json"))
}

fn fetch_due(ledger: &Ledger, now: u64) -> bool {
    ledger
        .tried_at
        .is_none_or(|tried| now.saturating_sub(tried) >= FETCH_EVERY)
}

fn notice_line(ledger: &Ledger, current: &str, now: u64) -> Option<String> {
    // § nfzrg1qsg@y122k
    let latest = ledger.latest.as_deref()?;
    let newer = matches!(
        (Version::parse(latest), Version::parse(current)),
        (Ok(latest), Ok(current)) if latest > current
    );
    let quiet = ledger
        .noticed_at
        .is_some_and(|at| now.saturating_sub(at) < NOTICE_EVERY);
    (newer && !quiet).then(|| {
        format!("silcrow: release {latest} is out, this is {current}. Run `silcrow upgrade` to install it.")
    })
}

fn fetch_latest(timeout: Duration) -> Result<String> {
    // Not self_update's `get_latest_release()`: its client has no timeout, and a
    // command stuck on GitHub would never exit. `upgrade` keeps self_update.
    let client = reqwest::blocking::Client::builder()
        .timeout(timeout)
        .user_agent(format!("silcrow/{CURRENT}"))
        .build()?;
    let body = client
        .get(format!(
            "https://api.github.com/repos/{REPO_OWNER}/{REPO_NAME}/releases/latest"
        ))
        .send()?
        .error_for_status()?
        .text()?;
    let release: Value = serde_json::from_str(&body)?;
    let Some(tag) = release["tag_name"].as_str() else {
        anyhow::bail!("the latest release has no tag_name");
    };
    Ok(tag.trim_start_matches('v').to_string())
}

fn unix_now() -> Option<u64> {
    let elapsed = SystemTime::now().duration_since(UNIX_EPOCH).ok()?;
    Some(elapsed.as_secs())
}

/// A missing or unreadable ledger is an empty one: the next check rebuilds it.
fn read_ledger(path: &Path) -> Ledger {
    let Some(value) = std::fs::read_to_string(path)
        .ok()
        .and_then(|text| serde_json::from_str::<Value>(&text).ok())
    else {
        return Ledger::default();
    };
    Ledger {
        tried_at: value["tried_at"].as_u64(),
        latest: value["latest"].as_str().map(str::to_string),
        noticed_at: value["noticed_at"].as_u64(),
    }
}

fn write_ledger(path: &Path, ledger: &Ledger) -> std::io::Result<()> {
    let text = json!({
        "tried_at": ledger.tried_at,
        "latest": ledger.latest,
        "noticed_at": ledger.noticed_at,
    })
    .to_string();
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir)?;
    }
    std::fs::write(path, text)
}

#[cfg(test)]
mod tests {
    use super::*;

    const DAY: u64 = 24 * 3600;
    const T0: u64 = 1_800_000_000;

    fn ledger(latest: &str, noticed_at: Option<u64>) -> Ledger {
        Ledger {
            tried_at: Some(T0),
            latest: Some(latest.into()),
            noticed_at,
        }
    }

    #[test]
    fn only_a_terminal_outside_ci_is_eligible() {
        assert!(eligible(true, None));
        assert!(eligible(true, Some("")));
        assert!(eligible(true, Some("0")));
        assert!(eligible(true, Some("false")));
        assert!(!eligible(true, Some("true")));
        assert!(!eligible(true, Some("1")));
        assert!(!eligible(false, None));
    }

    #[test]
    fn the_ledger_lives_in_the_user_cache() {
        let xdg = Some(PathBuf::from("/xdg"));
        let home = Some(PathBuf::from("/home/me"));
        assert_eq!(
            ledger_path(xdg, home.clone()),
            Some(PathBuf::from("/xdg/silcrow/release.json"))
        );
        assert_eq!(
            ledger_path(Some(PathBuf::from("rel")), home.clone()),
            Some(PathBuf::from("/home/me/.cache/silcrow/release.json"))
        );
        assert_eq!(ledger_path(None, None), None);
        assert_eq!(ledger_path(None, Some(PathBuf::from("rel"))), None);
    }

    #[test]
    fn fetches_at_most_daily() {
        assert!(fetch_due(&Ledger::default(), T0));
        let tried = ledger("0.1.0", None);
        assert!(!fetch_due(&tried, T0 + DAY - 1));
        assert!(fetch_due(&tried, T0 + DAY));
    }

    #[test]
    fn only_a_newer_semver_release_makes_a_line() {
        let line_for = |latest: &str| notice_line(&ledger(latest, None), "0.1.0", T0);
        assert_eq!(
            line_for("0.2.0").as_deref(),
            Some("silcrow: release 0.2.0 is out, this is 0.1.0. Run `silcrow upgrade` to install it.")
        );
        assert_eq!(line_for("0.1.0"), None);
        assert_eq!(line_for("0.0.9"), None);
        assert_eq!(line_for("nightly"), None);
        assert_eq!(notice_line(&Ledger::default(), "0.1.0", T0), None);
    }

    #[test]
    fn the_line_is_printed_at_most_hourly() {
        assert_eq!(
            notice_line(&ledger("0.2.0", Some(T0)), "0.1.0", T0 + NOTICE_EVERY - 1),
            None
        );
        assert!(notice_line(&ledger("0.2.0", Some(T0)), "0.1.0", T0 + NOTICE_EVERY).is_some());
    }

    #[test]
    fn a_fetch_records_the_release_and_the_notice() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("silcrow/release.json");
        let line = Notice::open_ledger(path.clone(), T0, || Ok("99.0.0".into()))
            .unwrap()
            .close_ledger(T0);
        assert!(line.unwrap().contains("release 99.0.0 is out"));
        assert_eq!(
            read_ledger(&path),
            Ledger {
                tried_at: Some(T0),
                latest: Some("99.0.0".into()),
                noticed_at: Some(T0),
            }
        );
        let again = Notice::open_ledger(path.clone(), T0 + 60, || panic!("fetched twice in a day"));
        assert_eq!(again.unwrap().close_ledger(T0 + 60), None);
    }

    #[test]
    fn a_failed_fetch_keeps_the_last_release_and_waits_a_day() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("release.json");
        write_ledger(&path, &ledger("99.0.0", Some(T0))).unwrap();
        let notice = Notice::open_ledger(path.clone(), T0 + DAY, || anyhow::bail!("offline"));
        assert!(notice.unwrap().close_ledger(T0 + DAY).is_some());
        let after = read_ledger(&path);
        assert_eq!(after.tried_at, Some(T0 + DAY));
        assert_eq!(after.latest.as_deref(), Some("99.0.0"));
    }

    #[test]
    fn an_unwritable_ledger_fetches_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let blocker = dir.path().join("file");
        std::fs::write(&blocker, "").unwrap();
        let path = blocker.join("release.json");
        assert!(Notice::open_ledger(path, T0, || panic!("fetched without a stamp")).is_none());
    }

    #[test]
    fn a_garbled_ledger_reads_as_empty() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("release.json");
        std::fs::write(&path, "{not json").unwrap();
        assert_eq!(read_ledger(&path), Ledger::default());
    }
}