Skip to main content

up/tasks/
update_self.rs

1//! The `up self` library, for updating the CLI itself.
2use 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/// GitHub latest release API endpoint JSON response.
25/// <https://docs.github.com/en/rest/releases/releases?apiVersion=2022-11-28#get-the-latest-release>
26#[derive(Debug, Deserialize)]
27struct GitHubReleaseJsonResponse {
28    /// Name of the git tag the release is for.
29    tag_name: String,
30}
31
32/// Name user agent after the app, e.g. up/1.2.3.
33const APP_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),);
34/// Current version of up we're building.
35const CURRENT_VERSION: &str = env!("CARGO_PKG_VERSION");
36
37impl ResolveEnv for UpdateSelfOptions {}
38
39/// Downloads the latest version of the binary from the specified URL and
40/// replaces the current executable path with it.
41pub(crate) fn run(opts: &UpdateSelfOptions) -> Result<TaskStatus> {
42    let up_path = Utf8PathBuf::try_from(env::current_exe()?)?.canonicalize_utf8()?;
43
44    // If the current binary's location is where it was originally compiled, assume it is a dev
45    // build, and thus skip the update.
46    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)]
114/// Errors thrown by this file.
115pub enum UpdateSelfError {
116    /// Failed to create directory `{path}`
117    CreateDir {
118        /// Dir path we failed to create.
119        path: Utf8PathBuf,
120    },
121    /// Failed to create file `{path}`
122    CreateFile {
123        /// File path we failed to create.
124        path: Utf8PathBuf,
125    },
126    /// Failed to copy to destination file.
127    Copy,
128    /// Failed to set permissions for `{path}`.
129    SetPermissions {
130        /// Path we failed to set permissions for.
131        path: Utf8PathBuf,
132    },
133    /// Failed to rename `{from}` to `{to}`.
134    Rename {
135        /// Old name (path).
136        from: Utf8PathBuf,
137        /// Attempted new name (path).
138        to: Utf8PathBuf,
139    },
140}