1use self::UpdateSelfError as E;
3use crate::cmd;
4use crate::opts::UpdateSelfOptions;
5use crate::tasks::ResolveEnv;
6use crate::tasks::task::TaskStatus;
7use camino::Utf8PathBuf;
8use chrono::Utc;
9use color_eyre::eyre::Context;
10use color_eyre::eyre::Result;
11use displaydoc::Display;
12use serde_derive::Deserialize;
13use std::env;
14use std::fs;
15use std::fs::File;
16use std::fs::Permissions;
17use std::io;
18use std::os::unix::fs::PermissionsExt;
19use thiserror::Error;
20use tracing::debug;
21use tracing::info;
22use tracing::trace;
23
24#[derive(Debug, Deserialize)]
27struct GitHubReleaseJsonResponse {
28 tag_name: String,
30}
31
32const APP_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),);
34const CURRENT_VERSION: &str = env!("CARGO_PKG_VERSION");
36
37impl ResolveEnv for UpdateSelfOptions {}
38
39pub(crate) fn run(opts: &UpdateSelfOptions) -> Result<TaskStatus> {
42 let up_path = Utf8PathBuf::try_from(env::current_exe()?)?.canonicalize_utf8()?;
43
44 if !opts.always_update && up_path.starts_with(env!("CARGO_MANIFEST_DIR")) {
47 debug!("Skipping up update, current version '{up_path}' is a dev build.",);
48 return Ok(TaskStatus::Skipped);
49 }
50
51 let client = reqwest::blocking::Client::builder()
52 .user_agent(APP_USER_AGENT)
53 .build()?;
54
55 trace!("Self update opts: {opts:?}");
56 if opts.url == crate::opts::SELF_UPDATE_URL {
57 let latest_github_release = client
58 .get(crate::opts::LATEST_RELEASE_URL)
59 .send()?
60 .error_for_status()?
61 .json::<GitHubReleaseJsonResponse>()?;
62 trace!("latest_github_release: {latest_github_release:?}");
63 let latest_github_release = latest_github_release.tag_name;
64 if semver::Version::parse(&latest_github_release)?
65 <= semver::Version::parse(CURRENT_VERSION)?
66 {
67 debug!(
68 "Skipping up update, current version '{CURRENT_VERSION}' is not older than latest \
69 GitHub version '{latest_github_release}'",
70 );
71 return Ok(TaskStatus::Skipped);
72 }
73 trace!("Updating up from '{CURRENT_VERSION}' to '{latest_github_release}'",);
74 }
75
76 let temp_dir = Utf8PathBuf::try_from(env::temp_dir())?;
77 let temp_path = &temp_dir.join(format!("up-{}", Utc::now().to_rfc3339()));
78
79 trace!("Downloading url {url} to path {up_path}", url = &opts.url,);
80
81 trace!("Using temporary path: {temp_path}");
82 let mut response = reqwest::blocking::get(&opts.url)?.error_for_status()?;
83
84 fs::create_dir_all(&temp_dir).wrap_err_with(|| E::CreateDir { path: temp_dir })?;
85 let mut dest = File::create(temp_path).wrap_err_with(|| E::CreateFile {
86 path: temp_path.clone(),
87 })?;
88 io::copy(&mut response, &mut dest).wrap_err(E::Copy {})?;
89
90 let permissions = Permissions::from_mode(0o755);
91 fs::set_permissions(temp_path, permissions).wrap_err_with(|| E::SetPermissions {
92 path: temp_path.clone(),
93 })?;
94
95 let new_version = cmd!(temp_path.as_str(), "--version").read()?;
96 let new_version = new_version.trim_start_matches(concat!(env!("CARGO_PKG_NAME"), " "));
97 if semver::Version::parse(new_version)? > semver::Version::parse(CURRENT_VERSION)? {
98 info!("Updating up from '{CURRENT_VERSION}' to '{new_version}'",);
99 fs::rename(temp_path, &up_path).wrap_err_with(|| E::Rename {
100 from: temp_path.clone(),
101 to: up_path.clone(),
102 })?;
103 Ok(TaskStatus::Passed)
104 } else {
105 debug!(
106 "Skipping up update, current version '{CURRENT_VERSION}' and new version \
107 '{new_version}'",
108 );
109 Ok(TaskStatus::Skipped)
110 }
111}
112
113#[derive(Error, Debug, Display)]
114pub enum UpdateSelfError {
116 CreateDir {
118 path: Utf8PathBuf,
120 },
121 CreateFile {
123 path: Utf8PathBuf,
125 },
126 Copy,
128 SetPermissions {
130 path: Utf8PathBuf,
132 },
133 Rename {
135 from: Utf8PathBuf,
137 to: Utf8PathBuf,
139 },
140}