Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/holger

holger-recipe/src/twins.rs

//! **Every product is its `cargo install` twin** (lane HOL-PRODUCTS, owner 2026-10-30).
//!
//! Holger is four products, one crate each: `holger` (the server), `holger-downstream`
//! (the airgapped downstream), `holger-ui` (the web console) and `holger-cli` (the
//! command-line tool). The Build Thing row of each builds exactly what one plain
//! `cargo install` line builds: the same package, bin, features, default-feature switch,
//! target and the release profile. The row adds the pinned toolchain container, the
//! remapped paths and the signature; it never adds a feature.
//!
//! [`PRODUCTS`] is the one table: each product, its crates.io line, the same line from a
//! clone, and what the row shows (its crate count, its binary size and what it is). The
//! README renders it ([`readme_table`]); `tests/rows_equal_cargo_install.rs` holds every
//! row to its line and `tests/every_shape_stays_slim.rs` every row to its tree guard.
//!
//! Pure: no filesystem, so it builds for the wasm32 shim too.

use std::collections::BTreeSet;

use nornir_build_thing::variant::{BuildVariant, Profile};

/// One product and its `cargo install` twin.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Product {
    /// The crate, which is also its Build Thing row and its program.
    pub name: &'static str,
    /// The `cargo install` line from a clone (run at holger's root; the console's from a
    /// holger-ui clone beside it).
    pub install: &'static str,
    /// Distinct crates in `cargo tree -e normal` of the row, measured.
    pub crates: usize,
    /// The release binary's size in bytes, measured (0: not measured yet).
    pub bytes: u64,
    /// What it is, in words.
    pub is: &'static str,
}

/// The four products, in the order the docs name them. Measured 2026-10-30 at holger
/// f57c4863 / holger-ui 3cd4143: `cargo tree -e normal` distinct lines, and the release
/// binary `cargo xtask products` built in the pinned toolchain container on dwarf (the
/// console with its bundle built in).
pub const PRODUCTS: &[Product] = &[
    Product {
        name: "holger",
        install: "cargo install --locked --path server/cli",
        crates: SERVER_CRATES,
        bytes: SERVER_BYTES,
        is: "the server: the twelve formats, the intake chain (scanners, approvals, audit), the offline bundle and intel verbs",
    },
    Product {
        name: "holger-downstream",
        install: "cargo install --locked --path holger-downstream",
        crates: DOWNSTREAM_CRATES,
        bytes: DOWNSTREAM_BYTES,
        is: "the airgapped downstream: takes packages from ONE upstream Holger (a carried bundle or a sync), verifies them, serves the twelve formats, runs no scanner and dials nothing else",
    },
    Product {
        name: "holger-ui",
        install: "cargo install --locked --path ../holger-ui/crates/holger-ui",
        crates: UI_CRATES,
        bytes: UI_BYTES,
        is: "the web console: the console bundle and a same-origin pass-through to the holger it points at",
    },
    Product {
        name: "holger-cli",
        install: "cargo install --locked --path holger-cli",
        crates: CLI_CRATES,
        bytes: CLI_BYTES,
        is: "the command-line tool: every console action as a command (it dials only --at), the airgap bundle, the offline verifier and the courier",
    },
];

const SERVER_CRATES: usize = 349;
const SERVER_BYTES: u64 = 58_020_224;
const DOWNSTREAM_CRATES: usize = 328;
const DOWNSTREAM_BYTES: u64 = 48_745_440;
const UI_CRATES: usize = 98;
const UI_BYTES: u64 = 6_813_968;
const CLI_CRATES: usize = 240;
const CLI_BYTES: u64 = 22_233_104;

/// The package directories a `--path` names, and the package each one is.
pub const PATHS: &[(&str, &str)] = &[
    ("server/cli", crate::variants::SERVER_CLI),
    ("holger-downstream", crate::variants::DOWNSTREAM),
    ("holger-cli", crate::variants::HOLGER_CLI),
    ("../holger-ui/crates/holger-ui", crate::variants::HOLGER_UI),
];

/// One cargo build point: what decides which binary comes out.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BuildPoint {
    pub package: Option<String>,
    /// `None`: no `--bin` (cargo builds every bin the features enable).
    pub bin: Option<String>,
    pub features: BTreeSet<String>,
    pub no_default_features: bool,
    pub target: Option<String>,
    pub profile: String,
    /// `--locked`: the committed lock decides every crate's version.
    pub locked: bool,
}

/// The build point a declared row builds: its own argv
/// ([`BuildVariant::cargo_args`]). The Build Thing's container road always adds
/// `--offline --locked`, so a row is locked.
pub fn point_of_row(v: &BuildVariant) -> BuildPoint {
    let mut p = parse_args(&v.cargo_args()).unwrap_or_default();
    p.locked = true;
    if p.profile.is_empty() {
        p.profile = match &v.profile {
            Profile::Dev => "dev".into(),
            Profile::Release => "release".into(),
            Profile::Custom(c) => c.clone(),
        };
    }
    p
}

/// The build point of a `cargo install …` line. `cargo install` builds the release
/// profile unless `--profile` or `--debug` says otherwise.
pub fn point_of_install(line: &str) -> Result<BuildPoint, String> {
    let words: Vec<String> = line.split_whitespace().map(String::from).collect();
    if words.len() < 2 || words[0] != "cargo" || words[1] != "install" {
        return Err(format!("not a `cargo install` line: {line:?}"));
    }
    let mut p = parse_args(&words[2..])?;
    if p.profile.is_empty() {
        p.profile = "release".into();
    }
    Ok(p)
}

/// Pure: the build point of a cargo argv (after `cargo`; `build`/`install` is skipped).
fn parse_args(args: &[String]) -> Result<BuildPoint, String> {
    let mut p = BuildPoint::default();
    let mut it = args.iter().peekable();
    let value = |flag: &str, v: Option<&String>| {
        v.cloned()
            .ok_or_else(|| format!("`{flag}` without a value"))
    };
    while let Some(a) = it.next() {
        let (flag, inline) = match a.split_once('=') {
            Some((f, v)) if f.starts_with("--") => (f.to_string(), Some(v.to_string())),
            _ => (a.clone(), None),
        };
        let take = |it: &mut std::iter::Peekable<std::slice::Iter<'_, String>>| match &inline {
            Some(v) => Ok(v.clone()),
            None => value(&flag, it.next()),
        };
        match flag.as_str() {
            "build" | "install" => {}
            "-p" | "--package" => p.package = Some(take(&mut it)?),
            "--path" => {
                let dir = take(&mut it)?;
                let dir = dir.trim_end_matches('/');
                let pkg = PATHS
                    .iter()
                    .find(|(d, _)| *d == dir)
                    .map(|(_, n)| n.to_string());
                p.package = Some(
                    pkg.ok_or_else(|| format!("`--path {dir}` is no package this table knows"))?,
                );
            }
            // A row built from a sibling checkout (`manifest_dir`): the manifest names the package.
            "--manifest-path" => {
                let m = take(&mut it)?;
                let dir = m.trim_end_matches("Cargo.toml").trim_end_matches('/');
                if let Some((_, n)) = PATHS.iter().find(|(d, _)| *d == dir) {
                    p.package.get_or_insert_with(|| n.to_string());
                }
            }
            "--bin" => p.bin = Some(take(&mut it)?),
            "--features" | "-F" => {
                p.features.extend(
                    take(&mut it)?
                        .split([',', ' '])
                        .filter(|f| !f.is_empty())
                        .map(String::from),
                );
            }
            "--no-default-features" => p.no_default_features = true,
            "--target" => p.target = Some(take(&mut it)?),
            "--profile" => p.profile = take(&mut it)?,
            "--release" => p.profile = "release".into(),
            "--debug" => p.profile = "dev".into(),
            "--locked" => p.locked = true,
            // Where cargo writes or installs, never what it builds.
            "--root" | "--target-dir" | "--message-format" | "--config" => {
                take(&mut it)?;
            }
            "--offline" | "--frozen" | "--force" | "-q" | "--quiet" => {}
            // `cargo install holger`: the crates.io form names the package itself.
            krate
                if !krate.starts_with('-')
                    && p.package.is_none()
                    && PATHS.iter().any(|(_, n)| *n == krate) =>
            {
                p.package = Some(krate.to_string())
            }
            other => {
                return Err(format!(
                    "`{other}`: this table does not know what it changes in the build"
                ))
            }
        }
    }
    Ok(p)
}

/// Pure: every way a row's build point differs from its `cargo install` twin, in words.
/// `default_bin` is the one bin the package builds with no required feature (`holger`):
/// a line without `--bin` and with the default features builds that one alone.
pub fn twin_differences(
    row: &BuildPoint,
    install: &BuildPoint,
    default_bin: Option<&str>,
) -> Vec<String> {
    let mut d = Vec::new();
    if row.package != install.package {
        d.push(format!(
            "package: the row builds {:?}, the install {:?}",
            row.package, install.package
        ));
    }
    let install_bin = install.bin.clone().or_else(|| {
        (install.features.is_empty() && !install.no_default_features)
            .then(|| default_bin.map(String::from))
            .flatten()
    });
    if row.bin != install_bin {
        d.push(format!(
            "bin: the row builds {:?}, the install {:?}",
            row.bin, install_bin
        ));
    }
    if row.features != install.features {
        let only_row: Vec<&String> = row.features.difference(&install.features).collect();
        let only_install: Vec<&String> = install.features.difference(&row.features).collect();
        d.push(format!(
            "features: only the row names {only_row:?}, only the install names {only_install:?}"
        ));
    }
    if row.no_default_features != install.no_default_features {
        d.push(format!(
            "default features: the row {}, the install {}",
            if row.no_default_features {
                "turns them off"
            } else {
                "keeps them"
            },
            if install.no_default_features {
                "turns them off"
            } else {
                "keeps them"
            }
        ));
    }
    if row.target != install.target {
        d.push(format!(
            "target: the row builds {:?}, the install {:?}",
            row.target, install.target
        ));
    }
    if row.profile != install.profile {
        d.push(format!(
            "profile: the row builds {}, the install {}",
            row.profile, install.profile
        ));
    }
    if row.locked && !install.locked {
        d.push("lock: the row builds --locked, the install re-resolves (add --locked)".into());
    }
    d
}

/// Human size, as the README shows it: `48.5 MB` (10^6 bytes), or `not measured`.
pub fn size(bytes: u64) -> String {
    if bytes == 0 {
        return "not measured".into();
    }
    format!("{:.1} MB", bytes as f64 / 1e6)
}

/// The README's one table of the four products, rendered from [`PRODUCTS`].
pub fn readme_table() -> String {
    let mut s = String::from("| product | install | from a clone | crates | binary | what it is |\n|---|---|---|---|---|---|\n");
    for r in PRODUCTS {
        s.push_str(&format!(
            "| `{}` | `cargo install {}` | `{}` | {} | {} | {} |\n",
            r.name,
            r.name,
            r.install,
            if r.crates == 0 {
                "not measured".to_string()
            } else {
                r.crates.to_string()
            },
            size(r.bytes),
            r.is
        ));
    }
    s.push_str("\nThe extras are features of the same crates: `--features all-formats` (NuGet, gems, conda, Composer), `online` (the pull-through clients), `federation` (Artifactory, Nexus, AWS and Azure through Skidbladnir), and `full` (all three).\n");
    s
}

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

    fn pt(line: &str) -> BuildPoint {
        point_of_install(line).unwrap()
    }

    #[test]
    fn an_install_line_parses_to_its_build_point() {
        let p = pt("cargo install --locked --path server/cli --no-default-features --features a,b --bin holger-mvp");
        assert_eq!(p.package.as_deref(), Some("holger"));
        assert_eq!(p.bin.as_deref(), Some("holger-mvp"));
        assert_eq!(
            p.features,
            BTreeSet::from(["a".to_string(), "b".to_string()])
        );
        assert!(p.no_default_features && p.locked);
        assert_eq!(p.profile, "release", "cargo install builds release");
        assert_eq!(p.target, None);
        assert_eq!(
            pt("cargo install --path=server/cli/ --features=x").features,
            BTreeSet::from(["x".to_string()])
        );
        assert_eq!(
            pt("cargo install holger-downstream").package.as_deref(),
            Some("holger-downstream"),
            "the crates.io form"
        );
    }

    #[test]
    fn a_line_that_is_not_an_install_or_names_an_unknown_flag_is_refused() {
        assert!(point_of_install("cargo build -p holger").is_err());
        assert!(point_of_install("cargo install --path server/cli --all-features").is_err());
        assert!(point_of_install("cargo install --path elsewhere").is_err());
    }

    #[test]
    fn a_differing_feature_set_is_named() {
        let row = BuildPoint {
            features: BTreeSet::from(["downstream".into(), "sync".into()]),
            ..pt("cargo install --locked --path server/cli --bin holger-downstream")
        };
        let install = pt("cargo install --locked --path server/cli --features downstream --bin holger-downstream");
        let d = twin_differences(&row, &install, Some("holger"));
        assert_eq!(d.len(), 1, "{d:?}");
        assert!(d[0].contains("only the row names [\"sync\"]"), "{d:?}");
    }

    #[test]
    fn every_other_difference_is_named_too() {
        let install =
            pt("cargo install --path server/cli --features downstream --bin holger-downstream");
        let row = BuildPoint {
            package: Some("holger".into()),
            bin: Some("holger-downstream".into()),
            features: BTreeSet::from(["downstream".into()]),
            no_default_features: true,
            target: Some("x86_64-unknown-linux-musl".into()),
            profile: "dev".into(),
            locked: true,
        };
        let d = twin_differences(&row, &install, Some("holger")).join("\n");
        for want in ["default features", "target", "profile", "lock"] {
            assert!(d.contains(want), "{want} not named:\n{d}");
        }
    }

    #[test]
    fn a_line_without_bin_builds_the_default_bin_only_with_the_default_features() {
        let row = BuildPoint {
            bin: Some("holger".into()),
            locked: true,
            ..pt("cargo install --locked --path server/cli")
        };
        assert!(twin_differences(
            &row,
            &pt("cargo install --locked --path server/cli"),
            Some("holger")
        )
        .is_empty());
        let row = BuildPoint {
            features: BTreeSet::from(["downstream".into()]),
            ..row
        };
        let d = twin_differences(
            &row,
            &pt("cargo install --locked --path server/cli --features downstream"),
            Some("holger"),
        );
        assert!(
            d.iter().any(|l| l.starts_with("bin:")),
            "with features and no --bin cargo installs every bin they enable: {d:?}"
        );
    }

    #[test]
    fn the_table_renders_every_row_once() {
        let t = readme_table();
        for r in PRODUCTS {
            assert_eq!(t.matches(&format!("`{}`", r.install)).count(), 1, "{t}");
        }
        assert_eq!(size(48_472_272), "48.5 MB");
        assert_eq!(size(0), "not measured");
    }
}