1use 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};
14
15const REPO: &str = "kintsugi-tools/paperscope";
16const API_LATEST: &str = "https://api.github.com/repos/kintsugi-tools/paperscope/releases/latest";
17
18#[derive(Args)]
19pub struct UpdateArgs {
20 #[arg(long)]
22 pub check: bool,
23}
24
25pub async fn run(args: UpdateArgs) -> Result<i32> {
26 let current = env!("CARGO_PKG_VERSION");
27 println!("paper {current}");
28
29 let latest = match latest_release().await {
30 Ok(tag) => tag,
31 Err(error) => {
32 println!("could not check for updates: {error:#}");
33 println!("check your connection, or reinstall from https://kintsugi.tools/paper.sh");
34 return Ok(EXIT_NOT_FOUND);
35 }
36 };
37
38 if !is_newer(&latest, current) {
39 println!("up to date (latest release is {latest})");
40 warn_if_shadowed();
41 return Ok(EXIT_FOUND);
42 }
43
44 println!("newer release available: {latest}");
45 if args.check {
46 println!("run `paper update` to install it");
47 return Ok(EXIT_FOUND);
48 }
49
50 install_latest().await?;
51 println!("updated to {latest}");
52 warn_if_shadowed();
53 Ok(EXIT_FOUND)
54}
55
56async fn latest_release() -> Result<String> {
58 let client = reqwest::Client::builder()
59 .user_agent(concat!("paper/", env!("CARGO_PKG_VERSION")))
60 .timeout(std::time::Duration::from_secs(20))
61 .build()?;
62 let response = client
63 .get(API_LATEST)
64 .send()
65 .await
66 .context("query GitHub releases")?
67 .error_for_status()
68 .context("query GitHub releases")?;
69 let body: serde_json::Value = response.json().await.context("read release metadata")?;
70 let tag = body
71 .get("tag_name")
72 .and_then(|value| value.as_str())
73 .context("release metadata has no tag_name")?;
74 Ok(tag.trim_start_matches('v').to_string())
75}
76
77fn is_newer(candidate: &str, current: &str) -> bool {
79 let parse = |value: &str| -> (u64, u64, u64, bool) {
80 let (core, pre) = match value.split_once('-') {
81 Some((core, _)) => (core, true),
82 None => (value, false),
83 };
84 let mut parts = core.split('.').map(|part| part.parse::<u64>().unwrap_or(0));
85 (
86 parts.next().unwrap_or(0),
87 parts.next().unwrap_or(0),
88 parts.next().unwrap_or(0),
89 pre,
90 )
91 };
92 let (a, b) = (parse(candidate), parse(current));
93 (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)
94}
95
96async fn install_latest() -> Result<()> {
98 #[cfg(windows)]
99 let (url, program, flag) = (
100 format!("https://github.com/{REPO}/releases/latest/download/paperscope-installer.ps1"),
101 "powershell",
102 "-File",
103 );
104 #[cfg(not(windows))]
105 let (url, program, flag) = (
106 format!("https://github.com/{REPO}/releases/latest/download/paperscope-installer.sh"),
107 "sh",
108 "",
109 );
110
111 let client = reqwest::Client::builder()
112 .user_agent(concat!("paper/", env!("CARGO_PKG_VERSION")))
113 .build()?;
114 let script = client
115 .get(&url)
116 .send()
117 .await
118 .context("download installer")?
119 .error_for_status()
120 .context("download installer")?
121 .text()
122 .await
123 .context("read installer")?;
124
125 let (_dir, path) = temp_script_path(&std::env::temp_dir())?;
127 std::fs::OpenOptions::new()
128 .write(true)
129 .create_new(true)
130 .open(&path)
131 .and_then(|mut file| file.write_all(script.as_bytes()))
132 .with_context(|| format!("write installer to {}", path.display()))?;
133 let mut command = std::process::Command::new(program);
134 if !flag.is_empty() {
135 command.arg(flag);
136 }
137 command.arg(&path);
138 let status = command.status().context("run installer")?;
139 if !status.success() {
140 bail!("installer exited with {status}; nothing was changed");
141 }
142 Ok(())
143}
144
145fn temp_script_path(base: &Path) -> Result<(tempfile::TempDir, PathBuf)> {
148 let name = if cfg!(windows) {
149 "paperscope-installer.ps1"
150 } else {
151 "paperscope-installer.sh"
152 };
153 std::fs::create_dir_all(base)
154 .with_context(|| format!("creating temporary directory {}", base.display()))?;
155 let mut builder = tempfile::Builder::new();
156 builder.prefix("paper-update-");
157 #[cfg(unix)]
158 builder.permissions(std::os::unix::fs::PermissionsExt::from_mode(0o700));
159 let dir = builder
160 .tempdir_in(base)
161 .with_context(|| format!("creating temporary directory in {}", base.display()))?;
162 let path = dir.path().join(name);
163 Ok((dir, path))
164}
165
166pub fn warn_if_shadowed() {
171 let Ok(current) = std::env::current_exe() else {
172 return;
173 };
174 let current = canonical(¤t);
175 let Some(path) = std::env::var_os("PATH") else {
176 return;
177 };
178 for dir in absolute_dirs(&path) {
179 let candidate = dir.join(if cfg!(windows) { "paper.exe" } else { "paper" });
180 if !candidate.is_file() {
181 continue;
182 }
183 let candidate = canonical(&candidate);
184 if candidate != current {
185 println!(
186 "note: `paper` in {} is a different copy ({}) and comes first in PATH;",
187 dir.display(),
188 version_of(&candidate).unwrap_or_else(|| "version unknown".to_string())
189 );
190 println!(
191 " remove it or put {} earlier in PATH to run this one.",
192 current.display()
193 );
194 return;
195 }
196 }
197}
198
199fn absolute_dirs(path: &std::ffi::OsStr) -> impl Iterator<Item = PathBuf> + '_ {
203 std::env::split_paths(path).filter(|dir| dir.is_absolute())
204}
205
206fn canonical(path: &Path) -> PathBuf {
207 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
208}
209
210fn version_of(binary: &Path) -> Option<String> {
211 let output = std::process::Command::new(binary)
212 .arg("--version")
213 .output()
214 .ok()?;
215 let text = String::from_utf8_lossy(&output.stdout);
216 text.split_whitespace().last().map(str::to_string)
217}
218
219#[cfg(test)]
220mod tests {
221 use super::is_newer;
222
223 #[test]
224 fn temp_script_directory_is_fresh_and_private() {
225 let root = tempfile::tempdir().expect("tempdir");
226 let base = root.path().join("missing");
228 let (first, path) = super::temp_script_path(&base).expect("temp path");
229 let (second, _) = super::temp_script_path(&base).expect("temp path");
230 assert_eq!(path.parent(), Some(first.path()));
231 assert_ne!(first.path(), second.path());
232 assert!(!path.exists());
233 #[cfg(unix)]
234 {
235 use std::os::unix::fs::PermissionsExt;
236 let mode = std::fs::metadata(first.path())
237 .expect("metadata")
238 .permissions()
239 .mode();
240 assert_eq!(mode & 0o777, 0o700);
241 }
242 let dir = first.path().to_path_buf();
243 drop(first);
244 assert!(!dir.exists());
245 }
246
247 #[test]
248 fn relative_path_entries_are_ignored() {
249 let abs = std::env::current_dir().expect("current dir");
250 let path = std::env::join_paths(["", ".", "bin", abs.to_str().expect("utf-8"), ""])
251 .expect("join PATH");
252 assert_eq!(super::absolute_dirs(&path).collect::<Vec<_>>(), [abs]);
253 }
254
255 #[test]
256 fn compares_versions_numerically() {
257 assert!(is_newer("0.2.10", "0.2.9"));
258 assert!(is_newer("0.3.0", "0.2.99"));
259 assert!(!is_newer("0.2.7", "0.2.7"));
260 assert!(!is_newer("0.2.6", "0.2.7"));
261 assert!(is_newer("0.2.7", "0.2.7-beta.1"));
262 }
263}