Skip to main content

git_stk/
upgrade.rs

1use std::io::IsTerminal;
2use std::path::PathBuf;
3use std::process::Command;
4use std::time::{Duration, SystemTime, UNIX_EPOCH};
5use std::{env, fs, sync::mpsc, thread};
6
7use anyhow::{Context, Result, bail};
8use axoupdater::AxoUpdater;
9
10use crate::prompt::confirm;
11
12/// Source repository used for `--head` installs.
13const REPO_URL: &str = "https://github.com/lararosekelley/git-stk";
14
15/// Stamp file next to the install receipt; one release check per day.
16const UPDATE_CHECK_FILE: &str = "update-check";
17const CHECK_INTERVAL_SECS: u64 = 24 * 60 * 60;
18
19/// Once a day, after a common command: print one dim line when a newer
20/// release exists. Best effort with a hard time cap; anything unusual (no
21/// receipt, offline, piped stderr, opt-out) prints nothing.
22pub fn maybe_hint_update() {
23    if !std::io::stderr().is_terminal() {
24        return;
25    }
26    let Some(path) = update_check_path() else {
27        return;
28    };
29    let now = SystemTime::now()
30        .duration_since(UNIX_EPOCH)
31        .map(|elapsed| elapsed.as_secs())
32        .unwrap_or(0);
33    if !should_check(fs::read_to_string(&path).ok().as_deref(), now) {
34        return;
35    }
36    if crate::settings::bool_setting(crate::settings::NO_UPDATE_CHECK_KEY).unwrap_or(false) {
37        return;
38    }
39
40    // Stamp before checking so a failure does not retry until tomorrow.
41    if let Some(parent) = path.parent() {
42        let _ = fs::create_dir_all(parent);
43    }
44    let _ = fs::write(&path, format!("checked={now}\n"));
45
46    // The query runs on a thread the process is free to abandon: the
47    // command's work is already done, so cap the wait.
48    let (sender, receiver) = mpsc::channel();
49    thread::spawn(move || {
50        let mut updater = AxoUpdater::new_for("git-stk");
51        let behind =
52            updater.load_receipt().is_ok() && updater.is_update_needed_sync().unwrap_or(false);
53        let _ = sender.send(behind);
54    });
55    if let Ok(true) = receiver.recv_timeout(Duration::from_secs(2)) {
56        anstream::eprintln!(
57            "{}",
58            crate::style::paint(
59                crate::style::DIM,
60                "a newer git-stk release is available - run `git stk upgrade`"
61            )
62        );
63    }
64}
65
66fn update_check_path() -> Option<PathBuf> {
67    let base = env::var_os("XDG_CONFIG_HOME")
68        .map(PathBuf::from)
69        .or_else(|| env::var_os("HOME").map(|home| PathBuf::from(home).join(".config")))?;
70    Some(base.join("git-stk").join(UPDATE_CHECK_FILE))
71}
72
73/// Whether the daily window has passed (or the stamp is missing/garbled).
74fn should_check(cache: Option<&str>, now: u64) -> bool {
75    let Some(cache) = cache else {
76        return true;
77    };
78    cache
79        .lines()
80        .find_map(|line| line.strip_prefix("checked="))
81        .and_then(|value| value.trim().parse::<u64>().ok())
82        .is_none_or(|checked| now.saturating_sub(checked) >= CHECK_INTERVAL_SECS)
83}
84
85pub fn upgrade(head: bool, force: bool, yes: bool) -> Result<()> {
86    if head {
87        upgrade_to_head(yes)
88    } else {
89        upgrade_to_latest_release(force)
90    }
91}
92
93fn upgrade_to_head(yes: bool) -> Result<()> {
94    println!("--head builds and installs the latest unreleased commit from {REPO_URL}");
95    println!("HEAD is a pre-release snapshot: it may be broken or untested");
96
97    if !yes && !confirm("continue? [y/N] ")? {
98        println!("upgrade cancelled");
99        return Ok(());
100    }
101
102    let status = Command::new("cargo")
103        .args(["install", "--git", REPO_URL, "--locked", "git-stk"])
104        .status()
105        .context("failed to run cargo; --head requires a Rust toolchain")?;
106
107    if !status.success() {
108        bail!("cargo install exited with status {status}");
109    }
110
111    println!("installed git-stk from HEAD");
112    println!("to return to the latest release, run: git stk upgrade --force");
113    refresh_assets_with_new_binary();
114    Ok(())
115}
116
117/// Re-render generated assets (man page) after an upgrade, using the newly
118/// installed binary so the assets match its version rather than the running
119/// (pre-upgrade) one. Failure is a warning, not an error: the upgrade itself
120/// already succeeded.
121fn refresh_assets_with_new_binary() {
122    let refreshed = Command::new("git-stk")
123        .args(["setup", "--refresh"])
124        .status()
125        .map(|status| status.success())
126        .unwrap_or(false);
127
128    if !refreshed {
129        eprintln!("warning: failed to refresh generated assets; run `git stk setup` manually");
130    }
131}
132
133fn upgrade_to_latest_release(force: bool) -> Result<()> {
134    let mut updater = AxoUpdater::new_for("git-stk");
135    updater
136        .load_receipt()
137        .map_err(anyhow::Error::from)
138        .context(
139            "no usable install receipt found; if git-stk was installed with cargo, \
140             upgrade with `cargo install git-stk --locked` instead",
141        )?;
142    updater.always_update(force);
143
144    match updater
145        .run_sync()
146        .context("failed to upgrade to the latest release")?
147    {
148        Some(result) => {
149            let old = result
150                .old_version
151                .map(|version| version.to_string())
152                .unwrap_or_else(|| "unknown".to_owned());
153            anstream::println!(
154                "{}",
155                crate::style::success(&format!("upgraded git-stk {old} -> {}", result.new_version))
156            );
157            refresh_assets_with_new_binary();
158        }
159        None => println!(
160            "git-stk {} is already the latest release",
161            env!("CARGO_PKG_VERSION")
162        ),
163    }
164
165    Ok(())
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171
172    #[test]
173    fn should_check_when_stamp_is_missing_or_garbled() {
174        assert!(should_check(None, 1_000_000));
175        assert!(should_check(Some(""), 1_000_000));
176        assert!(should_check(Some("checked=not-a-number\n"), 1_000_000));
177    }
178
179    #[test]
180    fn should_check_once_per_day() {
181        let stamp = format!("checked={}\n", 1_000_000);
182        assert!(!should_check(Some(&stamp), 1_000_000 + 60));
183        assert!(!should_check(
184            Some(&stamp),
185            1_000_000 + CHECK_INTERVAL_SECS - 1
186        ));
187        assert!(should_check(Some(&stamp), 1_000_000 + CHECK_INTERVAL_SECS));
188    }
189}