Skip to main content

torii_lib/util/
updater.rs

1use std::io::IsTerminal;
2use std::time::Duration;
3use update_informer::{registry, Check};
4
5use crate::config::ToriiConfig;
6
7const PKG_NAME: &str = env!("CARGO_PKG_NAME");
8const PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
9
10/// Check crates.io for a newer version. Returns `Some(version_string)` if one exists.
11/// Silent on errors, opt-out, or timeouts. Result is cached locally for `interval_hours`.
12pub fn check() -> Option<String> {
13    let cfg = ToriiConfig::load_global().unwrap_or_default();
14    if !cfg.update.check {
15        return None;
16    }
17    let interval = Duration::from_secs(cfg.update.interval_hours.saturating_mul(3600));
18    let informer = update_informer::new(registry::Crates, PKG_NAME, PKG_VERSION)
19        .interval(interval)
20        .timeout(Duration::from_secs(2));
21    informer.check_version().ok().flatten().map(|v| v.to_string())
22}
23
24/// CLI banner โ€” printed on stderr after command execution if an update is available.
25/// Silent if stderr is not a tty.
26pub fn maybe_notify() {
27    if !std::io::stderr().is_terminal() {
28        return;
29    }
30    if let Some(new_version) = check() {
31        let cmd = update_command();
32        eprintln!();
33        eprintln!("๐Ÿ’ก New version of torii available: {} โ†’ {}", PKG_VERSION, new_version);
34        eprintln!("   Update: {}", cmd);
35        eprintln!("   Disable: torii config set update.check false");
36    }
37}
38
39/// Suggested update command based on install method.
40pub fn update_command() -> &'static str {
41    let exe = std::env::current_exe().ok();
42    let path = exe.as_ref().map(|p| p.to_string_lossy().to_string()).unwrap_or_default();
43
44    if path.contains("/.cargo/bin/") {
45        "cargo install gitorii  (or: cargo binstall gitorii)"
46    } else if path.starts_with("/usr/local/bin")
47        || path.starts_with("/usr/bin")
48        || path.starts_with("/opt/")
49    {
50        "curl -LsSf https://github.com/paskidev/gitorii/releases/latest/download/gitorii-installer.sh | sh"
51    } else {
52        "cargo binstall gitorii  (or re-run your installer)"
53    }
54}