silcrow 0.2.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@t468w
    let asset = asset_name(release.version(), self_update::get_target());
    // Read before the swap: on Linux the running path names the deleted file after it.
    let exe = std::env::current_exe()?;
    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()
            );
            // The binary is already swapped: a tree that cannot be read costs the steps, never
            // the upgrade's success.
            match scheme_steps_after(&exe) {
                Ok(Some(steps)) => print!("\n{steps}"),
                Ok(None) => {}
                Err(e) => eprintln!(
                    "silcrow: the hashing scheme of the project here could not be read ({e:#}). Run `silcrow check` in it to see the steps of a scheme change."
                ),
            }
        }
        _ => println!("Already up to date."),
    }
    Ok(())
}

/// The steps of a scheme change for the workspace around the working directory, when the binary
/// installed at `exe` hashes with another scheme than its history records.
fn scheme_steps_after(exe: &std::path::Path) -> Result<Option<String>> {
    // § dfkjbzska.c@z25ke
    let cwd = std::env::current_dir()?;
    scheme_steps_in(&cwd, exe)
}

fn scheme_steps_in(cwd: &std::path::Path, exe: &std::path::Path) -> Result<Option<String>> {
    // Outside git no history records a scheme, and the walk would read every directory below.
    let inside = crate::workspace::git(cwd)
        .args(["rev-parse", "--is-inside-work-tree"])
        .output()
        .is_ok_and(|out| out.status.success());
    if !inside {
        return Ok(None);
    }
    let ws = crate::workspace::Workspace::discover(cwd)?;
    if ws.local().is_empty() {
        return Ok(None);
    }
    let out = std::process::Command::new(exe).arg("--version").output()?;
    let Some(binary) = installed_scheme(&String::from_utf8_lossy(&out.stdout)) else {
        return Ok(None);
    };
    let recorded = crate::hook::recorded_scheme_at(&ws.root, "HEAD")?;
    Ok(crate::check::scheme_steps(
        recorded,
        binary,
        ws.local().len() > 1,
    ))
}

/// The hashing scheme a `--version` line names, `None` for a release that names none.
fn installed_scheme(version: &str) -> Option<u32> {
    // § dfkjbzska.d@7b6c9
    version
        .trim()
        .rsplit_once("hashing scheme ")?
        .1
        .trim()
        .parse()
        .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::*;

    /// Outside git no history records a scheme, so the steps read no tree there.
    #[test]
    fn the_scheme_steps_read_no_tree_outside_git() {
        let exe = std::env::current_exe().expect("exe");
        let outside = tempfile::tempdir().expect("tempdir");
        assert!(scheme_steps_in(outside.path(), &exe)
            .expect("steps")
            .is_none());
    }

    #[test]
    fn the_installed_scheme_is_read_from_its_version_line() {
        assert_eq!(
            installed_scheme("silcrow 0.3.0, hashing scheme 26\n"),
            Some(26)
        );
        assert_eq!(installed_scheme("silcrow 0.1.0\n"), None);
    }

    #[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}");
    }
}