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("LOCALAPPDATA").map(PathBuf::from))
71 .or_else(|| env::var_os("HOME").map(|home| PathBuf::from(home).join(".config")))?;
72 Some(base.join("git-stk").join(UPDATE_CHECK_FILE))
73}
74
75fn should_check(cache: Option<&str>, now: u64) -> bool {
77 let Some(cache) = cache else {
78 return true;
79 };
80 cache
81 .lines()
82 .find_map(|line| line.strip_prefix("checked="))
83 .and_then(|value| value.trim().parse::<u64>().ok())
84 .is_none_or(|checked| now.saturating_sub(checked) >= CHECK_INTERVAL_SECS)
85}
86
87pub fn upgrade(head: bool, force: bool, yes: bool) -> Result<()> {
88 if head {
89 upgrade_to_head(yes)
90 } else {
91 upgrade_to_latest_release(force)
92 }
93}
94
95fn upgrade_to_head(yes: bool) -> Result<()> {
96 println!("--head builds and installs the latest unreleased commit from {REPO_URL}");
97 println!("HEAD is a pre-release snapshot: it may be broken or untested");
98
99 if !yes && !confirm("continue? [y/N] ")? {
100 println!("upgrade cancelled");
101 return Ok(());
102 }
103
104 let status = Command::new("cargo")
105 .args(["install", "--git", REPO_URL, "--locked", "git-stk"])
106 .status()
107 .context("failed to run cargo; --head requires a Rust toolchain")?;
108
109 if !status.success() {
110 bail!("cargo install exited with status {status}");
111 }
112
113 println!("installed git-stk from HEAD");
114 println!("to return to the latest release, run: git stk upgrade --force");
115 refresh_assets_with_new_binary();
116 Ok(())
117}
118
119fn refresh_assets_with_new_binary() {
124 let refreshed = Command::new("git-stk")
125 .args(["setup", "--refresh"])
126 .status()
127 .map(|status| status.success())
128 .unwrap_or(false);
129
130 if !refreshed {
131 eprintln!("warning: failed to refresh generated assets; run `git stk setup` manually");
132 }
133}
134
135fn upgrade_to_latest_release(force: bool) -> Result<()> {
136 let mut updater = AxoUpdater::new_for("git-stk");
137 updater
138 .load_receipt()
139 .map_err(anyhow::Error::from)
140 .context(
141 "no usable install receipt found; if git-stk was installed with cargo, \
142 upgrade with `cargo install git-stk --locked` instead",
143 )?;
144 updater.always_update(force);
145
146 match updater
147 .run_sync()
148 .context("failed to upgrade to the latest release")?
149 {
150 Some(result) => {
151 let old = result
152 .old_version
153 .map(|version| version.to_string())
154 .unwrap_or_else(|| "unknown".to_owned());
155 anstream::println!(
156 "{}",
157 crate::style::success(&format!("upgraded git-stk {old} -> {}", result.new_version))
158 );
159 refresh_assets_with_new_binary();
160 }
161 None => println!(
162 "git-stk {} is already the latest release",
163 env!("CARGO_PKG_VERSION")
164 ),
165 }
166
167 Ok(())
168}
169
170#[cfg(test)]
171mod tests {
172 use super::*;
173
174 #[test]
175 fn should_check_when_stamp_is_missing_or_garbled() {
176 assert!(should_check(None, 1_000_000));
177 assert!(should_check(Some(""), 1_000_000));
178 assert!(should_check(Some("checked=not-a-number\n"), 1_000_000));
179 }
180
181 #[test]
182 fn should_check_once_per_day() {
183 let stamp = format!("checked={}\n", 1_000_000);
184 assert!(!should_check(Some(&stamp), 1_000_000 + 60));
185 assert!(!should_check(
186 Some(&stamp),
187 1_000_000 + CHECK_INTERVAL_SECS - 1
188 ));
189 assert!(should_check(Some(&stamp), 1_000_000 + CHECK_INTERVAL_SECS));
190 }
191}