silcrow 0.2.1

Deterministic CLI for a citable, checkable graph of laws in a git tree.
//! Fixes the build of this binary when it is compiled, the key of its cache entries.

use std::path::{Path, PathBuf};

fn main() {
    // ยง faq86xmas.i@mw7sy
    let mut hasher = blake3::Hasher::new();
    let mut files = vec![
        PathBuf::from("build.rs"),
        PathBuf::from("Cargo.toml"),
        PathBuf::from("Cargo.lock"),
    ];
    rust_files(Path::new("src"), &mut files);
    files.sort();
    for file in &files {
        let bytes = std::fs::read(file)
            .unwrap_or_else(|e| panic!("build.rs reads {}: {e}", file.display()));
        let name = file.to_string_lossy();
        hasher.update(&(name.len() as u64).to_le_bytes());
        hasher.update(name.as_bytes());
        hasher.update(&(bytes.len() as u64).to_le_bytes());
        hasher.update(&bytes);
    }
    let rustc = std::env::var("RUSTC").expect("cargo sets RUSTC");
    let compiler = std::process::Command::new(rustc)
        .arg("-vV")
        .output()
        .expect("build.rs runs rustc -vV");
    assert!(compiler.status.success(), "rustc -vV failed");
    hasher.update(&(compiler.stdout.len() as u64).to_le_bytes());
    hasher.update(&compiler.stdout);
    let mut settings: Vec<(String, String)> = std::env::vars_os()
        .map(|(name, value)| {
            (
                name.to_string_lossy().into_owned(),
                value.to_string_lossy().into_owned(),
            )
        })
        .filter(|(name, _)| {
            [
                "TARGET",
                "PROFILE",
                "OPT_LEVEL",
                "DEBUG",
                "CARGO_ENCODED_RUSTFLAGS",
            ]
            .contains(&name.as_str())
                || name.starts_with("CARGO_FEATURE_")
                || name.starts_with("CARGO_CFG_")
        })
        .collect();
    settings.sort();
    for (name, value) in &settings {
        for part in [name, value] {
            hasher.update(&(part.len() as u64).to_le_bytes());
            hasher.update(part.as_bytes());
        }
    }
    println!(
        "cargo:rustc-env=SILCROW_BUILD={}",
        hasher.finalize().to_hex()
    );
    println!("cargo:rerun-if-changed=build.rs");
    println!("cargo:rerun-if-changed=Cargo.toml");
    println!("cargo:rerun-if-changed=Cargo.lock");
    println!("cargo:rerun-if-changed=src");
}

/// Each `.rs` file under `dir`, at any depth.
fn rust_files(dir: &Path, out: &mut Vec<PathBuf>) {
    let entries =
        std::fs::read_dir(dir).unwrap_or_else(|e| panic!("build.rs reads {}: {e}", dir.display()));
    for entry in entries {
        let path = entry.expect("build.rs reads a directory entry").path();
        if path.is_dir() {
            rust_files(&path, out);
        } else if path.extension().is_some_and(|ext| ext == "rs") {
            out.push(path);
        }
    }
}