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
12const REPO_URL: &str = "https://github.com/lararosekelley/git-stk";
14
15const UPDATE_CHECK_FILE: &str = "update-check";
17const CHECK_INTERVAL_SECS: u64 = 24 * 60 * 60;
18
19pub 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 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 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
73fn 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
117fn 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 println!("upgraded git-stk {old} -> {}", result.new_version);
154 refresh_assets_with_new_binary();
155 }
156 None => println!(
157 "git-stk {} is already the latest release",
158 env!("CARGO_PKG_VERSION")
159 ),
160 }
161
162 Ok(())
163}
164
165#[cfg(test)]
166mod tests {
167 use super::*;
168
169 #[test]
170 fn should_check_when_stamp_is_missing_or_garbled() {
171 assert!(should_check(None, 1_000_000));
172 assert!(should_check(Some(""), 1_000_000));
173 assert!(should_check(Some("checked=not-a-number\n"), 1_000_000));
174 }
175
176 #[test]
177 fn should_check_once_per_day() {
178 let stamp = format!("checked={}\n", 1_000_000);
179 assert!(!should_check(Some(&stamp), 1_000_000 + 60));
180 assert!(!should_check(
181 Some(&stamp),
182 1_000_000 + CHECK_INTERVAL_SECS - 1
183 ));
184 assert!(should_check(Some(&stamp), 1_000_000 + CHECK_INTERVAL_SECS));
185 }
186}