twitcher 0.8.1

Find template switch mutations in genomic data
#![allow(
    clippy::exit,
    reason = "a build script may abort the build on an invalid lockfile"
)]

//! Extracts the version of the tsalign family of crates (`lib_tsalign`, `lib_tsshow` and
//! `generic_a_star`) from the lockfile and exposes it to the crate as `TSALIGN_VERSION`.
//!
//! The three crates are released in lockstep, so a mismatch is a build error.

use std::{env, fs, path::PathBuf, process::exit};

use serde::Deserialize;

/// The crates whose versions must match, and whose common version is reported to the user.
const TSALIGN_CRATES: [&str; 3] = ["lib_tsalign", "lib_tsshow", "generic_a_star"];

/// The parts of `Cargo.lock` we care about.
#[derive(Deserialize)]
struct Lockfile {
    #[serde(default, rename = "package")]
    packages: Vec<Package>,
}

/// A single entry of the lockfile's package list.
#[derive(Deserialize)]
struct Package {
    name: String,
    version: String,
}

fn main() {
    let Some(manifest_dir) = env::var_os("CARGO_MANIFEST_DIR") else {
        fail("CARGO_MANIFEST_DIR is not set");
    };
    let lockfile_path = PathBuf::from(manifest_dir).join("Cargo.lock");
    println!("cargo::rerun-if-changed={}", lockfile_path.display());

    let lockfile = match fs::read_to_string(&lockfile_path) {
        Ok(lockfile) => lockfile,
        Err(error) => fail(&format!("cannot read {}: {error}", lockfile_path.display())),
    };
    let lockfile: Lockfile = match toml::from_str(&lockfile) {
        Ok(lockfile) => lockfile,
        Err(error) => fail(&format!(
            "cannot parse {}: {error}",
            lockfile_path.display()
        )),
    };

    let mut common: Option<&Package> = None;
    for crate_name in TSALIGN_CRATES {
        let mut found = lockfile
            .packages
            .iter()
            .filter(|package| package.name == crate_name);
        let (Some(package), None) = (found.next(), found.next()) else {
            fail(&format!(
                "expected exactly one version of `{crate_name}` in {}",
                lockfile_path.display()
            ));
        };

        match common {
            None => common = Some(package),
            Some(common) if common.version == package.version => {}
            Some(common) => fail(&format!(
                "the tsalign crates must be in lockstep, but `{}` is at {} while `{}` is at {}",
                package.name, package.version, common.name, common.version
            )),
        }
    }

    let Some(common) = common else {
        fail("no tsalign crates are configured");
    };
    println!("cargo::rustc-env=TSALIGN_VERSION={}", common.version);
}

/// Aborts the build with an error message.
fn fail(message: &str) -> ! {
    println!("cargo::error={message}");
    exit(1);
}