thirdshift 0.23.0

Turn a GitHub issue into a ready-for-review pull request, unattended
//! `thirdshift update`: replace this copy of thirdshift with the latest stable
//! GitHub Release, through the install receipt the shell installer wrote.
//!
//! The CLI and Console's requested Update action call this; a Run never checks for updates. The
//! release's installer moves the new binary into place with a rename, so a Run
//! or a Spec run still using the old binary keeps running it. So do the child
//! Runs it starts afterwards, which the child Run module starts from the
//! running binary rather than from its install path.

use std::fmt::Display;

use anyhow::{Context, Error, Result, anyhow};
use axoupdater::{AxoUpdater, AxoupdateError};

const VERSION: &str = env!("CARGO_PKG_VERSION");

#[derive(serde::Serialize)]
pub struct Versions {
    pub current: String,
    pub latest: String,
}

/// Ask the same release source as the installer without changing this copy.
pub fn check() -> Result<Versions> {
    let mut updater = AxoUpdater::new_for("thirdshift");
    updater.set_release_source(axoupdater::ReleaseSource {
        release_type: axoupdater::ReleaseSourceType::GitHub,
        owner: "JacobStephens2".into(),
        name: "thirdshift".into(),
        app_name: "thirdshift".into(),
    });
    updater.set_client(
        reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(15))
            .build()?,
    );
    // axoupdater exposes a blocking installer, but only an async version query.
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()?;
    let latest = runtime
        .block_on(updater.query_new_version())?
        .context("no stable thirdshift release is available")?
        .to_string();
    Ok(Versions {
        current: VERSION.into(),
        latest,
    })
}

pub fn command(check_only: bool, json: bool) -> Result<String> {
    if check_only {
        let versions = check()?;
        Ok(if json {
            serde_json::to_string(&versions)?
        } else {
            format!(
                "thirdshift {}; latest release {}",
                versions.current, versions.latest
            )
        })
    } else {
        Ok(serde_json::to_string(&update()?)?)
    }
}

/// How to update the kinds of install that `update` won't touch.
const OTHER_INSTALLS: &str = concat!(
    "  built from source:  git pull && cargo install --path .\n",
    "  from crates.io:     cargo install thirdshift\n",
    "  copied by hand:     reinstall with curl -LsSf ",
    "https://github.com/JacobStephens2/thirdshift/releases/latest/download/thirdshift-installer.sh | sh",
);

/// Update to the latest stable release, or confirm this is it. Returns the
/// line that says which.
pub fn update() -> Result<String> {
    let mut updater = AxoUpdater::new_for("thirdshift");
    match updater.load_receipt() {
        Ok(_) => {}
        Err(AxoupdateError::NoReceipt { .. }) => {
            return Err(refusal("this thirdshift has no install receipt"));
        }
        Err(error) => return Err(anyhow!(error).context("can't read the install receipt")),
    }
    // Without this check, a copy from elsewhere would be reported as up to
    // date whenever the installer's copy is.
    if !updater.check_receipt_is_for_this_executable()? {
        return Err(refusal(format!(
            "the install receipt is for the copy in {}, not this one",
            updater.install_prefix_root()?
        )));
    }
    // The running binary knows its version better than the receipt does.
    updater.set_current_version(VERSION.parse()?)?;
    // stdout carries nothing for `update`; the installer's stdout comes back
    // in the error if it fails.
    updater.disable_installer_stdout();
    let updated = updater
        .run_sync()
        .context("can't update from GitHub Releases")?;
    Ok(match updated {
        Some(result) => format!("updated thirdshift {VERSION} to {}", result.new_version),
        None => format!("thirdshift {VERSION} is the latest release"),
    })
}

/// Refuse to replace a copy the installer didn't put in place, for `reason`,
/// and say how to update it instead.
fn refusal(reason: impl Display) -> Error {
    anyhow!(
        "{reason}; update only replaces the copy the thirdshift installer put in place. \
         To update this one instead:\n{OTHER_INSTALLS}"
    )
}