use anyhow::Context;
use serde::Serialize;
use super::{detect_install_method, install_script_ref, latest_release, InstallMethod, UpdateInfo};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum CheckFormat {
Text,
Json,
}
#[derive(Debug, Serialize)]
struct UpdateCheck {
current: String,
latest: String,
update_available: bool,
method: InstallMethod,
command: Option<String>,
needs_terminal: bool,
}
impl UpdateCheck {
fn new(update: UpdateInfo, method: InstallMethod) -> anyhow::Result<Self> {
let update_available = update.is_available();
let UpdateInfo {
latest_tag,
latest_version,
current_version,
} = update;
Ok(Self {
current: current_version,
latest: latest_version,
update_available,
method,
command: update_available
.then(|| method.update_command(&install_script_ref(latest_tag)))
.transpose()?,
needs_terminal: method.needs_terminal(),
})
}
}
pub(crate) async fn run_check(current_version: &str, format: CheckFormat) -> anyhow::Result<()> {
let update = latest_release(current_version)
.await
.context("could not check the latest rho release")?;
let check = UpdateCheck::new(update, detect_install_method())?;
match format {
CheckFormat::Json => println!("{}", serde_json::to_string(&check)?),
CheckFormat::Text => print_summary(&check),
}
Ok(())
}
fn print_summary(check: &UpdateCheck) {
println!("install method: {}", check.method.label());
let Some(command) = &check.command else {
println!(
"rho is up to date (v{}, latest release v{}).",
check.current, check.latest
);
return;
};
println!(
"rho v{} is available (current v{}).",
check.latest, check.current
);
println!("update command: {command}");
if cfg!(windows) {
println!("run the update command to install it.");
} else if check.needs_terminal {
println!("run `rho update` in a terminal to install it.");
} else {
println!("run `rho update` to install it.");
}
}
#[cfg(test)]
#[path = "update_check_tests.rs"]
mod tests;