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,
}
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()?,
);
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()?)?)
}
}
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",
);
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")),
}
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()?
)));
}
updater.set_current_version(VERSION.parse()?)?;
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"),
})
}
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}"
)
}