sapphire_framework_update/
install.rs1use std::io::{BufRead, Write as _};
4use std::path::{Path, PathBuf};
5use std::time::Duration;
6
7use crate::release::{Release, ReleaseSource, latest_release};
8use crate::{Error, Result};
9
10const MAX_DOWNLOAD: u64 = 512 * 1024 * 1024;
13
14const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(15 * 60);
16
17#[derive(Clone, Debug, Default, clap::Args)]
19pub struct UpdateArgs {
20 #[arg(long)]
22 pub check: bool,
23 #[arg(long, short = 'y')]
25 pub yes: bool,
26}
27
28#[derive(Clone, Debug, PartialEq, Eq)]
31pub enum InstallMethod {
32 Release,
34 Cargo,
37 PackageManager,
40}
41
42pub fn install_method(exe: &Path, cargo_home: Option<&Path>) -> InstallMethod {
45 if let Some(home) = cargo_home
46 && exe.starts_with(home.join("bin"))
47 {
48 return InstallMethod::Cargo;
49 }
50 if exe.starts_with("/usr/local") {
53 return InstallMethod::Release;
54 }
55 const MANAGED: [&str; 7] = [
56 "/usr",
57 "/bin",
58 "/sbin",
59 "/nix",
60 "/opt/homebrew",
61 "/home/linuxbrew",
62 "/snap",
63 ];
64 if MANAGED.iter().any(|dir| exe.starts_with(dir)) {
65 return InstallMethod::PackageManager;
66 }
67 InstallMethod::Release
68}
69
70pub fn platform() -> String {
73 format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH)
74}
75
76pub fn asset_name(base: &str) -> String {
79 format!("{base}-{}{}", platform(), std::env::consts::EXE_SUFFIX)
80}
81
82pub fn install(
88 bytes: &[u8],
89 exe: &Path,
90 replace: impl FnOnce(&Path) -> std::io::Result<()>,
91) -> Result<()> {
92 let dir = exe.parent().ok_or_else(|| {
93 Error::Io(std::io::Error::other(format!(
94 "{} has no directory",
95 exe.display()
96 )))
97 })?;
98 let mut staged = tempfile::Builder::new()
99 .prefix(".update-")
100 .tempfile_in(dir)?;
101 staged.write_all(bytes)?;
102 staged.as_file().sync_all()?;
103 #[cfg(unix)]
104 {
105 use std::os::unix::fs::PermissionsExt;
106 std::fs::set_permissions(staged.path(), std::fs::Permissions::from_mode(0o755))?;
107 }
108 replace(staged.path())?;
109 Ok(())
110}
111
112async fn download(client: &reqwest::Client, url: &str) -> Result<Vec<u8>> {
114 let response = client
115 .get(url)
116 .timeout(DOWNLOAD_TIMEOUT)
117 .send()
118 .await
119 .and_then(reqwest::Response::error_for_status)
120 .map_err(|e| Error::Http(format!("downloading {url}: {e}")))?;
121 if response.content_length().is_some_and(|n| n > MAX_DOWNLOAD) {
122 return Err(Error::Http(format!(
123 "{url} is larger than {MAX_DOWNLOAD} bytes"
124 )));
125 }
126 let bytes = response
127 .bytes()
128 .await
129 .map_err(|e| Error::Http(format!("downloading {url}: {e}")))?;
130 if bytes.len() as u64 > MAX_DOWNLOAD {
131 return Err(Error::Http(format!(
132 "{url} is larger than {MAX_DOWNLOAD} bytes"
133 )));
134 }
135 Ok(bytes.to_vec())
136}
137
138async fn fetch(
140 client: &reqwest::Client,
141 source: &ReleaseSource,
142 release: &Release,
143 base: &str,
144) -> Result<Vec<u8>> {
145 let name = asset_name(base);
146 let binary = release
147 .assets
148 .iter()
149 .find(|a| a.name == name)
150 .ok_or_else(|| {
151 Error::NoAsset(format!(
152 "{} {} has no {name}",
153 source.repository(),
154 release.version
155 ))
156 })?;
157 let bytes = download(client, &binary.download_url).await?;
158 if bytes.is_empty() {
159 return Err(Error::Http(format!("{name} downloaded empty")));
160 }
161 Ok(bytes)
162}
163
164fn manual_advice(source: &ReleaseSource, release: &Release, method: &InstallMethod) -> String {
166 match (method, source.crate_name()) {
167 (InstallMethod::Cargo, Some(name)) => {
168 format!("installed with cargo; run: cargo install {name} --locked")
169 }
170 (InstallMethod::Cargo, None) => {
171 "installed with cargo; update it with cargo install".to_owned()
172 }
173 (InstallMethod::PackageManager, _) => {
174 "installed by a package manager; update it with that".to_owned()
175 }
176 (InstallMethod::Release, _) => format!("download it from {}", release.url),
177 }
178}
179
180fn cargo_home() -> Option<PathBuf> {
182 std::env::var_os("CARGO_HOME")
183 .map(PathBuf::from)
184 .or_else(|| std::env::home_dir().map(|home| home.join(".cargo")))
185}
186
187pub async fn run(
193 args: &UpdateArgs,
194 source: &ReleaseSource,
195 name: &str,
196 current: &str,
197) -> Result<i32> {
198 let current_v = semver::Version::parse(current).map_err(|e| {
199 Error::NotConfigured(format!(
200 "this binary's version {current:?} is not semver: {e}"
201 ))
202 })?;
203 let client = crate::client(&format!("{name}/{current}"))?;
204 let release = latest_release(&client, source).await?;
205 if release.version <= current_v {
206 println!(
207 "{name} {current} is up to date (latest release {})",
208 release.version
209 );
210 return Ok(0);
211 }
212 println!(
213 "{name} {} is available (installed: {current}): {}",
214 release.version, release.url
215 );
216 if args.check {
217 return Ok(0);
218 }
219
220 let Some(base) = source.asset_base() else {
221 println!(
222 "{name} does not update itself; {}",
223 manual_advice(source, &release, &InstallMethod::Release)
224 );
225 return Ok(1);
226 };
227 let exe = std::env::current_exe()?;
228 let exe = exe.canonicalize().unwrap_or(exe);
229 let method = install_method(&exe, cargo_home().as_deref());
230 if method != InstallMethod::Release {
231 println!(
232 "{} is {}",
233 exe.display(),
234 manual_advice(source, &release, &method)
235 );
236 return Ok(1);
237 }
238
239 if !args.yes
240 && !confirm(&format!(
241 "replace {} with {}?",
242 exe.display(),
243 release.version
244 ))?
245 {
246 println!("not updated");
247 return Ok(1);
248 }
249 let bytes = fetch(&client, source, &release, base).await?;
250 install(&bytes, &exe, |staged| self_replace::self_replace(staged))?;
251 println!(
252 "installed {name} {}; restart the {name} service to run it",
253 release.version
254 );
255 Ok(0)
256}
257
258fn confirm(question: &str) -> Result<bool> {
260 print!("{question} [y/N] ");
261 std::io::stdout().flush()?;
262 let mut answer = String::new();
263 std::io::stdin().lock().read_line(&mut answer)?;
264 Ok(matches!(
265 answer.trim().to_ascii_lowercase().as_str(),
266 "y" | "yes"
267 ))
268}
269
270#[cfg(test)]
271mod tests {
272 use super::*;
273
274 fn v(s: &str) -> semver::Version {
275 semver::Version::parse(s).unwrap()
276 }
277
278 #[test]
279 fn a_binary_is_replaced_only_where_it_was_placed_by_hand() {
280 let home = Path::new("/home/u/.cargo");
281 let method = |p: &str| install_method(Path::new(p), Some(home));
282 assert_eq!(method("/home/u/.cargo/bin/app"), InstallMethod::Cargo);
283 assert_eq!(method("/usr/bin/app"), InstallMethod::PackageManager);
284 assert_eq!(
285 method("/nix/store/abc-app/bin/app"),
286 InstallMethod::PackageManager
287 );
288 assert_eq!(
289 method("/opt/homebrew/bin/app"),
290 InstallMethod::PackageManager
291 );
292 assert_eq!(method("/usr/local/bin/app"), InstallMethod::Release);
293 assert_eq!(method("/home/u/.local/bin/app"), InstallMethod::Release);
294 }
295
296 #[test]
297 fn the_asset_names_this_machine() {
298 let name = asset_name("sapphire-bridge");
299 assert!(name.starts_with("sapphire-bridge-"));
300 assert!(name.contains(std::env::consts::OS));
301 assert!(name.contains(std::env::consts::ARCH));
302 }
303
304 #[test]
305 fn install_puts_the_bytes_in_place_and_leaves_no_staging_file() {
306 let tmp = tempfile::tempdir().unwrap();
307 let exe = tmp.path().join("app");
308 std::fs::write(&exe, b"old").unwrap();
309 install(b"new", &exe, |staged| {
310 std::fs::copy(staged, &exe).map(|_| ())
311 })
312 .unwrap();
313 assert_eq!(std::fs::read(&exe).unwrap(), b"new");
314 let left: Vec<_> = std::fs::read_dir(tmp.path()).unwrap().collect();
315 assert_eq!(left.len(), 1, "the staging file is gone");
316 #[cfg(unix)]
317 {
318 use std::os::unix::fs::PermissionsExt;
319 let staged_mode = std::fs::metadata(&exe).unwrap().permissions().mode();
320 assert_eq!(
321 staged_mode & 0o111,
322 0o111,
323 "the copy keeps the executable bit"
324 );
325 }
326 }
327
328 async fn serve(routes: impl FnOnce(&str) -> Vec<(String, Vec<u8>)>) -> String {
331 use tokio::io::{AsyncReadExt, AsyncWriteExt};
332 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
333 let root = format!("http://{}", listener.local_addr().unwrap());
334 let routes = routes(&root);
335 tokio::spawn(async move {
336 loop {
337 let (mut socket, _) = listener.accept().await.unwrap();
338 let mut buf = vec![0u8; 8192];
339 let n = socket.read(&mut buf).await.unwrap();
340 let request = String::from_utf8_lossy(&buf[..n]);
341 let path = request.split_whitespace().nth(1).unwrap_or("").to_owned();
342 let (status, body) = match routes.iter().find(|(p, _)| *p == path) {
343 Some((_, body)) => ("200 OK", body.clone()),
344 None => ("404 Not Found", Vec::new()),
345 };
346 let head = format!(
347 "HTTP/1.1 {status}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
348 body.len()
349 );
350 socket.write_all(head.as_bytes()).await.unwrap();
351 socket.write_all(&body).await.unwrap();
352 }
353 });
354 root
355 }
356
357 const RELEASES: &str = "/repos/o/r/releases?per_page=100";
358
359 async fn repository(binary: &[u8]) -> String {
361 let name = asset_name("app");
362 let binary = binary.to_vec();
363 serve(move |root| {
364 let releases = format!(
365 r#"[{{"tag_name":"v0.20.0","html_url":"{root}/r/v0.20.0","assets":[
366 {{"name":"{name}","browser_download_url":"{root}/dl/{name}"}}]}}]"#
367 );
368 vec![
369 (RELEASES.to_owned(), releases.into_bytes()),
370 (format!("/dl/{name}"), binary),
371 ]
372 })
373 .await
374 }
375
376 #[tokio::test]
377 async fn a_release_is_fetched_end_to_end() {
378 let root = repository(b"new binary").await;
379 let source = ReleaseSource::github("o", "r").api_base(&root).asset("app");
380 let client = crate::client("test/0.0.0").unwrap();
381 let release = latest_release(&client, &source).await.unwrap();
382 assert_eq!(release.version, v("0.20.0"));
383 let bytes = fetch(&client, &source, &release, "app").await.unwrap();
384 assert_eq!(bytes, b"new binary");
385 }
386
387 #[tokio::test]
388 async fn an_empty_download_is_refused() {
389 let root = repository(b"").await;
390 let source = ReleaseSource::github("o", "r").api_base(&root).asset("app");
391 let client = crate::client("test/0.0.0").unwrap();
392 let release = latest_release(&client, &source).await.unwrap();
393 let err = fetch(&client, &source, &release, "app").await.unwrap_err();
394 assert!(matches!(err, Error::Http(_)), "{err}");
395 }
396
397 #[tokio::test]
398 async fn a_release_without_this_platforms_file_is_refused() {
399 let root = serve(|_| {
400 vec![(
401 RELEASES.to_owned(),
402 br#"[{"tag_name":"v0.20.0","html_url":"https://example.invalid","assets":[]}]"#
403 .to_vec(),
404 )]
405 })
406 .await;
407 let source = ReleaseSource::github("o", "r").api_base(&root).asset("app");
408 let client = crate::client("test/0.0.0").unwrap();
409 let release = latest_release(&client, &source).await.unwrap();
410 let err = fetch(&client, &source, &release, "app").await.unwrap_err();
411 assert!(matches!(err, Error::NoAsset(_)), "{err}");
412 }
413}