Skip to main content

paper/cli/
update.rs

1//! `paper update` — move an installed binary to the latest release.
2//!
3//! Updating goes through the same installer a fresh install uses, so there is
4//! exactly one code path that knows where files belong, how to verify the
5//! download and how to touch `PATH`. `--check` is offline-safe reporting only.
6
7use std::path::{Path, PathBuf};
8
9use anyhow::{bail, Context, Result};
10use clap::Args;
11
12use super::{EXIT_FOUND, EXIT_NOT_FOUND};
13
14const REPO: &str = "arrowassassin/paperscope";
15const API_LATEST: &str = "https://api.github.com/repos/arrowassassin/paperscope/releases/latest";
16
17#[derive(Args)]
18pub struct UpdateArgs {
19    /// Only report whether a newer release exists; change nothing.
20    #[arg(long)]
21    pub check: bool,
22}
23
24pub async fn run(args: UpdateArgs) -> Result<i32> {
25    let current = env!("CARGO_PKG_VERSION");
26    println!("paper {current}");
27
28    let latest = match latest_release().await {
29        Ok(tag) => tag,
30        Err(error) => {
31            println!("could not check for updates: {error:#}");
32            println!("check your connection, or reinstall from https://kintsugi.tools/paper.sh");
33            return Ok(EXIT_NOT_FOUND);
34        }
35    };
36
37    if !is_newer(&latest, current) {
38        println!("up to date (latest release is {latest})");
39        warn_if_shadowed();
40        return Ok(EXIT_FOUND);
41    }
42
43    println!("newer release available: {latest}");
44    if args.check {
45        println!("run `paper update` to install it");
46        return Ok(EXIT_FOUND);
47    }
48
49    install_latest().await?;
50    println!("updated to {latest}");
51    warn_if_shadowed();
52    Ok(EXIT_FOUND)
53}
54
55/// Ask GitHub for the newest published release tag, without a token.
56async fn latest_release() -> Result<String> {
57    let client = reqwest::Client::builder()
58        .user_agent(concat!("paper/", env!("CARGO_PKG_VERSION")))
59        .timeout(std::time::Duration::from_secs(20))
60        .build()?;
61    let response = client
62        .get(API_LATEST)
63        .send()
64        .await
65        .context("query GitHub releases")?
66        .error_for_status()
67        .context("query GitHub releases")?;
68    let body: serde_json::Value = response.json().await.context("read release metadata")?;
69    let tag = body
70        .get("tag_name")
71        .and_then(|value| value.as_str())
72        .context("release metadata has no tag_name")?;
73    Ok(tag.trim_start_matches('v').to_string())
74}
75
76/// Numeric comparison of `major.minor.patch`; a pre-release suffix sorts low.
77fn is_newer(candidate: &str, current: &str) -> bool {
78    let parse = |value: &str| -> (u64, u64, u64, bool) {
79        let (core, pre) = match value.split_once('-') {
80            Some((core, _)) => (core, true),
81            None => (value, false),
82        };
83        let mut parts = core.split('.').map(|part| part.parse::<u64>().unwrap_or(0));
84        (
85            parts.next().unwrap_or(0),
86            parts.next().unwrap_or(0),
87            parts.next().unwrap_or(0),
88            pre,
89        )
90    };
91    let (a, b) = (parse(candidate), parse(current));
92    (a.0, a.1, a.2) > (b.0, b.1, b.2) || ((a.0, a.1, a.2) == (b.0, b.1, b.2) && b.3 && !a.3)
93}
94
95/// Run the platform installer from the latest release.
96async fn install_latest() -> Result<()> {
97    #[cfg(windows)]
98    let (url, program, flag) = (
99        format!("https://github.com/{REPO}/releases/latest/download/paperscope-installer.ps1"),
100        "powershell",
101        "-File",
102    );
103    #[cfg(not(windows))]
104    let (url, program, flag) = (
105        format!("https://github.com/{REPO}/releases/latest/download/paperscope-installer.sh"),
106        "sh",
107        "",
108    );
109
110    let client = reqwest::Client::builder()
111        .user_agent(concat!("paper/", env!("CARGO_PKG_VERSION")))
112        .build()?;
113    let script = client
114        .get(&url)
115        .send()
116        .await
117        .context("download installer")?
118        .error_for_status()
119        .context("download installer")?
120        .text()
121        .await
122        .context("read installer")?;
123
124    let path = temp_script_path()?;
125    std::fs::write(&path, script).context("write installer")?;
126    let mut command = std::process::Command::new(program);
127    if !flag.is_empty() {
128        command.arg(flag);
129    }
130    command.arg(&path);
131    let status = command.status().context("run installer")?;
132    let _ = std::fs::remove_file(&path);
133    if !status.success() {
134        bail!("installer exited with {status}; nothing was changed");
135    }
136    Ok(())
137}
138
139fn temp_script_path() -> Result<PathBuf> {
140    let name = if cfg!(windows) {
141        "paperscope-installer.ps1"
142    } else {
143        "paperscope-installer.sh"
144    };
145    Ok(std::env::temp_dir()
146        .join(format!("paper-update-{}", std::process::id()))
147        .join(name))
148}
149
150/// Tell the user when `paper` on `PATH` resolves to a different binary.
151///
152/// This is the single most confusing update symptom: Homebrew and the shell
153/// installer both install a `paper`, and whichever directory comes first wins.
154pub fn warn_if_shadowed() {
155    let Ok(current) = std::env::current_exe() else {
156        return;
157    };
158    let current = canonical(&current);
159    let Some(path) = std::env::var_os("PATH") else {
160        return;
161    };
162    for dir in std::env::split_paths(&path) {
163        let candidate = dir.join(if cfg!(windows) { "paper.exe" } else { "paper" });
164        if !candidate.is_file() {
165            continue;
166        }
167        let candidate = canonical(&candidate);
168        if candidate != current {
169            println!(
170                "note: `paper` in {} is a different copy ({}) and comes first in PATH;",
171                dir.display(),
172                version_of(&candidate).unwrap_or_else(|| "version unknown".to_string())
173            );
174            println!(
175                "      remove it or put {} earlier in PATH to run this one.",
176                current.display()
177            );
178            return;
179        }
180    }
181}
182
183fn canonical(path: &Path) -> PathBuf {
184    std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
185}
186
187fn version_of(binary: &Path) -> Option<String> {
188    let output = std::process::Command::new(binary)
189        .arg("--version")
190        .output()
191        .ok()?;
192    let text = String::from_utf8_lossy(&output.stdout);
193    text.split_whitespace().last().map(str::to_string)
194}
195
196#[cfg(test)]
197mod tests {
198    use super::is_newer;
199
200    #[test]
201    fn compares_versions_numerically() {
202        assert!(is_newer("0.2.10", "0.2.9"));
203        assert!(is_newer("0.3.0", "0.2.99"));
204        assert!(!is_newer("0.2.7", "0.2.7"));
205        assert!(!is_newer("0.2.6", "0.2.7"));
206        assert!(is_newer("0.2.7", "0.2.7-beta.1"));
207    }
208}