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 anstream::eprintln!(
132 "{} failed to refresh generated assets; run `git stk setup` manually",
133 crate::style::paint(crate::style::WARN, "warning:")
134 );
135 }
136}
137
138fn upgrade_to_latest_release(force: bool) -> Result<()> {
139 let mut updater = AxoUpdater::new_for("git-stk");
140 updater
141 .load_receipt()
142 .map_err(anyhow::Error::from)
143 .context(
144 "no usable install receipt found; if git-stk was installed with cargo, \
145 upgrade with `cargo install git-stk --locked` instead",
146 )?;
147 updater.always_update(force);
148
149 match updater
150 .run_sync()
151 .context("failed to upgrade to the latest release")?
152 {
153 Some(result) => {
154 let old = result
155 .old_version
156 .map(|version| version.to_string())
157 .unwrap_or_else(|| "unknown".to_owned());
158 anstream::println!(
159 "{}",
160 crate::style::success(&format!("upgraded git-stk {old} -> {}", result.new_version))
161 );
162 refresh_assets_with_new_binary();
163 }
164 None => println!(
165 "git-stk {} is already the latest release",
166 env!("CARGO_PKG_VERSION")
167 ),
168 }
169
170 Ok(())
171}
172
173#[cfg(test)]
174mod tests {
175 use super::*;
176
177 #[test]
178 fn should_check_when_stamp_is_missing_or_garbled() {
179 assert!(should_check(None, 1_000_000));
180 assert!(should_check(Some(""), 1_000_000));
181 assert!(should_check(Some("checked=not-a-number\n"), 1_000_000));
182 }
183
184 #[test]
185 fn should_check_once_per_day() {
186 let stamp = format!("checked={}\n", 1_000_000);
187 assert!(!should_check(Some(&stamp), 1_000_000 + 60));
188 assert!(!should_check(
189 Some(&stamp),
190 1_000_000 + CHECK_INTERVAL_SECS - 1
191 ));
192 assert!(should_check(Some(&stamp), 1_000_000 + CHECK_INTERVAL_SECS));
193 }
194}