silcrow 0.1.0

Deterministic CLI for a citable, checkable graph of laws in a git tree.
use anyhow::{anyhow, bail, Result};
use self_update::{
    backends::github::{Update, UpdateBuilder},
    cargo_crate_version,
    update::{Release, ReleaseAsset, ReleaseStatus},
};

pub const REPO_OWNER: &str = "zifeo";
pub const REPO_NAME: &str = "silcrow";

pub fn self_upgrade(version: Option<&str>, yes: bool, dev_build: bool) -> Result<()> {
    refuse_upgrade(dev_build)?;
    let release = release_of(version, yes)?;
    if version.is_none() && release.version() == cargo_crate_version!() {
        println!("Already up to date.");
        return Ok(());
    }
    // § g24nqa18j.a@fc08x
    let asset = asset_name(release.version(), self_update::get_target());
    match release_source(release.version(), &asset, yes)?.update_extended()? {
        ReleaseStatus::Updated(release) => {
            println!("Updated to {}.", release.version());
            println!(
                "Release notes: https://github.com/{REPO_OWNER}/{REPO_NAME}/releases/tag/v{}",
                release.version()
            );
        }
        _ => println!("Already up to date."),
    }
    Ok(())
}

fn refuse_upgrade(dev_build: bool) -> Result<()> {
    // § g24nqa18j.a@qfecc
    if dev_build {
        bail!("a development build is not upgraded. Rebuild it from source with `cargo build`.");
    }
    Ok(())
}

fn configure(yes: bool) -> UpdateBuilder {
    let mut update = Update::configure();
    update
        .repo_owner(REPO_OWNER)
        .repo_name(REPO_NAME)
        .bin_name("silcrow")
        .show_download_progress(true)
        .current_version(cargo_crate_version!())
        .no_confirm(yes);
    update
}

/// The release `version` names, else the latest one, failing with what is missing when GitHub
/// holds no such release.
fn release_of(version: Option<&str>, yes: bool) -> Result<Release> {
    // § g24nqa18j@22z5j
    let lookup = configure(yes).build()?;
    let found = match version {
        Some(version) => lookup.get_release_version(&format!("v{version}")),
        None => lookup.get_latest_release().and_then(|releases| {
            releases
                .all()
                .first()
                .cloned()
                .ok_or_else(self_update::errors::Error::no_release_found)
        }),
    };
    found.map_err(|e| missing(e, version))
}

/// `e`, or what GitHub lacks when it holds no release by that name.
fn missing(e: self_update::errors::Error, version: Option<&str>) -> anyhow::Error {
    // § g24nqa18j.d@9jdbn
    let gone = e.http_status() == Some(404)
        || matches!(e, self_update::errors::Error::NoReleaseFound { .. });
    match (gone, version) {
        (false, _) => e.into(),
        (true, Some(version)) => anyhow!(
            "{REPO_OWNER}/{REPO_NAME} has no release v{version}: https://github.com/{REPO_OWNER}/{REPO_NAME}/releases lists those it has."
        ),
        (true, None) => anyhow!(
            "{REPO_OWNER}/{REPO_NAME} has published no release yet, so there is none to upgrade to."
        ),
    }
}

/// The archive the release workflow publishes for `target`, which the installer reads too.
fn asset_name(version: &str, target: &str) -> String {
    format!("{REPO_NAME}-v{version}-{target}.tar.gz")
}

/// The asset named `name` exactly, never its `.sha256` beside it.
fn binary_asset(assets: &[ReleaseAsset], name: &str) -> Option<ReleaseAsset> {
    assets.iter().find(|asset| asset.name() == name).cloned()
}

/// The update to the release `version`, which installs only the archive `asset` and fails
/// unless the `.sha256` published beside it matches, as the installer does.
fn release_source(version: &str, asset: &str, yes: bool) -> Result<Update> {
    // § g24nqa18j.c@mse50
    let name = asset.to_string();
    Ok(configure(yes)
        .release_tag(format!("v{version}"))
        .asset_matcher(move |assets| binary_asset(assets, &name))
        .checksum_from_asset(format!("{asset}.sha256"))
        .build()?)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_development_build_is_never_upgraded() {
        let err = refuse_upgrade(true).unwrap_err().to_string();
        assert!(err.contains("`cargo build`"), "{err}");
        assert!(refuse_upgrade(false).is_ok());
    }

    #[test]
    fn the_release_source_builds_offline() {
        let asset = asset_name("0.2.0", "aarch64-apple-darwin");
        assert_eq!(asset, "silcrow-v0.2.0-aarch64-apple-darwin.tar.gz");
        assert!(release_source("0.2.0", &asset, true).is_ok());
    }

    #[test]
    fn the_binary_asset_is_picked_by_its_exact_name_never_its_checksum() {
        let name = asset_name("0.2.0", "x86_64-unknown-linux-gnu");
        let at = |name: &str| ReleaseAsset::new(name, format!("https://example.com/{name}"));
        let assets = [
            at(&format!("{name}.sha256")),
            at("silcrow-v0.2.0-x86_64-unknown-linux-musl.tar.gz"),
            at(&name),
        ];
        assert_eq!(
            binary_asset(&assets, &name).map(|a| a.name().to_string()),
            Some(name.clone())
        );
        assert!(binary_asset(&assets[..2], &name).is_none());
    }

    #[test]
    fn a_release_github_lacks_is_named_and_another_error_passes_through() {
        use self_update::errors::Error;
        let latest = missing(
            Error::http_status_error(404, "https://api.github.com/x"),
            None,
        );
        assert!(
            latest.to_string().contains("has published no release yet"),
            "{latest}"
        );
        let pinned = missing(Error::no_release_found(), Some("0.2.0")).to_string();
        assert!(pinned.contains("has no release v0.2.0"), "{pinned}");
        let other = missing(Error::checksum_mismatch("a", "b"), None).to_string();
        assert!(!other.contains("no release"), "{other}");
    }
}