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::io::Write;
8use std::path::{Path, PathBuf};
9
10use anyhow::{bail, Context, Result};
11use clap::Args;
12
13use super::{EXIT_FOUND, EXIT_NOT_FOUND};
14use crate::core::update_state::version_newer;
15
16const REPO: &str = "kintsugi-tools/paperscope";
17const API_LATEST: &str = "https://api.github.com/repos/kintsugi-tools/paperscope/releases/latest";
18
19#[derive(Args)]
20pub struct UpdateArgs {
21    /// Only report whether a newer release exists; change nothing.
22    #[arg(long)]
23    pub check: bool,
24}
25
26pub async fn run(args: UpdateArgs) -> Result<i32> {
27    let current = env!("CARGO_PKG_VERSION");
28    println!("paper {current}");
29
30    let latest = match latest_release().await {
31        Ok(tag) => tag,
32        Err(error) => {
33            println!("could not check for updates: {error:#}");
34            println!("check your connection, or reinstall from https://kintsugi.tools/paper.sh");
35            return Ok(EXIT_NOT_FOUND);
36        }
37    };
38
39    if !version_newer(&latest, current) {
40        println!("up to date (latest release is {latest})");
41        warn_if_shadowed();
42        return Ok(EXIT_FOUND);
43    }
44
45    println!("newer release available: {latest}");
46    if args.check {
47        println!("run `paper update` to install it");
48        return Ok(EXIT_FOUND);
49    }
50
51    install_latest().await?;
52    println!("updated to {latest}");
53    warn_if_shadowed();
54    Ok(EXIT_FOUND)
55}
56
57/// Ask GitHub for the newest published release tag, without a token.
58async fn latest_release() -> Result<String> {
59    let client = reqwest::Client::builder()
60        .user_agent(concat!("paper/", env!("CARGO_PKG_VERSION")))
61        .timeout(std::time::Duration::from_secs(20))
62        .build()?;
63    let response = client
64        .get(API_LATEST)
65        .send()
66        .await
67        .context("query GitHub releases")?
68        .error_for_status()
69        .context("query GitHub releases")?;
70    let body: serde_json::Value = response.json().await.context("read release metadata")?;
71    let tag = body
72        .get("tag_name")
73        .and_then(|value| value.as_str())
74        .context("release metadata has no tag_name")?;
75    Ok(tag.trim_start_matches('v').to_string())
76}
77
78/// Run the platform installer from the latest release.
79async fn install_latest() -> Result<()> {
80    #[cfg(windows)]
81    let (url, program, flag) = (
82        format!("https://github.com/{REPO}/releases/latest/download/paperscope-installer.ps1"),
83        "powershell",
84        "-File",
85    );
86    #[cfg(not(windows))]
87    let (url, program, flag) = (
88        format!("https://github.com/{REPO}/releases/latest/download/paperscope-installer.sh"),
89        "sh",
90        "",
91    );
92
93    let client = reqwest::Client::builder()
94        .user_agent(concat!("paper/", env!("CARGO_PKG_VERSION")))
95        .build()?;
96    let script = client
97        .get(&url)
98        .send()
99        .await
100        .context("download installer")?
101        .error_for_status()
102        .context("download installer")?
103        .text()
104        .await
105        .context("read installer")?;
106
107    // The guard removes the directory and script when it drops, after the installer exits.
108    let (_dir, path) = temp_script_path(&std::env::temp_dir())?;
109    std::fs::OpenOptions::new()
110        .write(true)
111        .create_new(true)
112        .open(&path)
113        .and_then(|mut file| file.write_all(script.as_bytes()))
114        .with_context(|| format!("write installer to {}", path.display()))?;
115    let mut command = std::process::Command::new(program);
116    if !flag.is_empty() {
117        command.arg(flag);
118    }
119    command.arg(&path);
120    let status = command.status().context("run installer")?;
121    if !status.success() {
122        bail!("installer exited with {status}; nothing was changed");
123    }
124    Ok(())
125}
126
127/// Installer path inside a fresh, randomly named directory under `base`, created
128/// exclusively (0700 on Unix) so no other local user can pre-create or plant it.
129fn temp_script_path(base: &Path) -> Result<(tempfile::TempDir, PathBuf)> {
130    let name = if cfg!(windows) {
131        "paperscope-installer.ps1"
132    } else {
133        "paperscope-installer.sh"
134    };
135    std::fs::create_dir_all(base)
136        .with_context(|| format!("creating temporary directory {}", base.display()))?;
137    let mut builder = tempfile::Builder::new();
138    builder.prefix("paper-update-");
139    #[cfg(unix)]
140    builder.permissions(std::os::unix::fs::PermissionsExt::from_mode(0o700));
141    let dir = builder
142        .tempdir_in(base)
143        .with_context(|| format!("creating temporary directory in {}", base.display()))?;
144    let path = dir.path().join(name);
145    Ok((dir, path))
146}
147
148/// Tell the user when `paper` on `PATH` resolves to a different binary.
149///
150/// This is the single most confusing update symptom: Homebrew and the shell
151/// installer both install a `paper`, and whichever directory comes first wins.
152pub fn warn_if_shadowed() {
153    let Ok(current) = std::env::current_exe() else {
154        return;
155    };
156    let current = canonical(&current);
157    let Some(path) = std::env::var_os("PATH") else {
158        return;
159    };
160    for dir in absolute_dirs(&path) {
161        let candidate = dir.join(if cfg!(windows) { "paper.exe" } else { "paper" });
162        if !candidate.is_file() {
163            continue;
164        }
165        let candidate = canonical(&candidate);
166        if candidate != current {
167            println!(
168                "note: `paper` in {} is a different copy ({}) and comes first in PATH;",
169                dir.display(),
170                version_of(&candidate).unwrap_or_else(|| "version unknown".to_string())
171            );
172            println!(
173                "      remove it or put {} earlier in PATH to run this one.",
174                current.display()
175            );
176            return;
177        }
178    }
179}
180
181/// PATH entries that name a fixed directory. Empty, `.` and relative entries
182/// resolve against the current directory (shells do resolve them), so a
183/// `paper` there is not run by this shadow check.
184fn absolute_dirs(path: &std::ffi::OsStr) -> impl Iterator<Item = PathBuf> + '_ {
185    std::env::split_paths(path).filter(|dir| dir.is_absolute())
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    #[test]
204    fn temp_script_directory_is_fresh_and_private() {
205        let root = tempfile::tempdir().expect("tempdir");
206        // A missing temp root is still created, as before.
207        let base = root.path().join("missing");
208        let (first, path) = super::temp_script_path(&base).expect("temp path");
209        let (second, _) = super::temp_script_path(&base).expect("temp path");
210        assert_eq!(path.parent(), Some(first.path()));
211        assert_ne!(first.path(), second.path());
212        assert!(!path.exists());
213        #[cfg(unix)]
214        {
215            use std::os::unix::fs::PermissionsExt;
216            let mode = std::fs::metadata(first.path())
217                .expect("metadata")
218                .permissions()
219                .mode();
220            assert_eq!(mode & 0o777, 0o700);
221        }
222        let dir = first.path().to_path_buf();
223        drop(first);
224        assert!(!dir.exists());
225    }
226
227    #[test]
228    fn relative_path_entries_are_ignored() {
229        let abs = std::env::current_dir().expect("current dir");
230        let path = std::env::join_paths(["", ".", "bin", abs.to_str().expect("utf-8"), ""])
231            .expect("join PATH");
232        assert_eq!(super::absolute_dirs(&path).collect::<Vec<_>>(), [abs]);
233    }
234}