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 = "kintsugi-tools/paperscope";
15const API_LATEST: &str = "https://api.github.com/repos/kintsugi-tools/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)
126        .with_context(|| format!("write installer to {}", path.display()))?;
127    let mut command = std::process::Command::new(program);
128    if !flag.is_empty() {
129        command.arg(flag);
130    }
131    command.arg(&path);
132    let status = command.status().context("run installer")?;
133    let _ = std::fs::remove_file(&path);
134    if let Some(dir) = path.parent() {
135        let _ = std::fs::remove_dir(dir);
136    }
137    if !status.success() {
138        bail!("installer exited with {status}; nothing was changed");
139    }
140    Ok(())
141}
142
143fn temp_script_path() -> Result<PathBuf> {
144    let name = if cfg!(windows) {
145        "paperscope-installer.ps1"
146    } else {
147        "paperscope-installer.sh"
148    };
149    let dir = std::env::temp_dir().join(format!("paper-update-{}", std::process::id()));
150    std::fs::create_dir_all(&dir)
151        .with_context(|| format!("creating temporary directory {}", dir.display()))?;
152    Ok(dir.join(name))
153}
154
155/// Tell the user when `paper` on `PATH` resolves to a different binary.
156///
157/// This is the single most confusing update symptom: Homebrew and the shell
158/// installer both install a `paper`, and whichever directory comes first wins.
159pub fn warn_if_shadowed() {
160    let Ok(current) = std::env::current_exe() else {
161        return;
162    };
163    let current = canonical(&current);
164    let Some(path) = std::env::var_os("PATH") else {
165        return;
166    };
167    for dir in std::env::split_paths(&path) {
168        let candidate = dir.join(if cfg!(windows) { "paper.exe" } else { "paper" });
169        if !candidate.is_file() {
170            continue;
171        }
172        let candidate = canonical(&candidate);
173        if candidate != current {
174            println!(
175                "note: `paper` in {} is a different copy ({}) and comes first in PATH;",
176                dir.display(),
177                version_of(&candidate).unwrap_or_else(|| "version unknown".to_string())
178            );
179            println!(
180                "      remove it or put {} earlier in PATH to run this one.",
181                current.display()
182            );
183            return;
184        }
185    }
186}
187
188fn canonical(path: &Path) -> PathBuf {
189    std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
190}
191
192fn version_of(binary: &Path) -> Option<String> {
193    let output = std::process::Command::new(binary)
194        .arg("--version")
195        .output()
196        .ok()?;
197    let text = String::from_utf8_lossy(&output.stdout);
198    text.split_whitespace().last().map(str::to_string)
199}
200
201#[cfg(test)]
202mod tests {
203    use super::is_newer;
204
205    #[test]
206    fn temp_script_directory_exists() {
207        let path = super::temp_script_path().expect("temp path");
208        assert!(path.parent().expect("parent").is_dir());
209        if let Some(dir) = path.parent() {
210            let _ = std::fs::remove_dir(dir);
211        }
212    }
213
214    #[test]
215    fn compares_versions_numerically() {
216        assert!(is_newer("0.2.10", "0.2.9"));
217        assert!(is_newer("0.3.0", "0.2.99"));
218        assert!(!is_newer("0.2.7", "0.2.7"));
219        assert!(!is_newer("0.2.6", "0.2.7"));
220        assert!(is_newer("0.2.7", "0.2.7-beta.1"));
221    }
222}