//! Build script of the `im` binary. It compiles `style/main.scss` into `OUT_DIR/main.css`, and it //! emits the build identity and the content hashes that the page links use as cache-busting //! queries: `IM_MAIN_CSS_V`, `IM_NAV_JS_V`, `IM_PAGES_JS_V` and `IM_BUILD_SHA`. //! //! It does not decide what is served: `src/assets.rs` embeds the files. It does not decide what a //! page links to either: `src/assets.rs` builds the `?v=` URLs from these values. It only compiles //! and hashes, so a changed file gets a new hash and an unchanged file keeps its URL. use std::{env, fs, path::PathBuf}; use hex::encode; use sha2::{Digest, Sha256}; /// Number of hex characters of the SHA-256 that make a content version. Twelve characters are 48 /// bits, which is plenty to tell two builds of one file apart. const VERSION_HEX_LEN: usize = 12; fn main() { println!("cargo:rerun-if-env-changed=IM_BUILD_SHA"); println!("cargo:rerun-if-changed=../../style"); println!("cargo:rerun-if-changed=assets"); println!("cargo:rerun-if-changed=build.rs"); // The commit identity shown by `/healthz`. The release script sets it; a local build says `dev`. let sha = env::var("IM_BUILD_SHA").unwrap_or_else(|_| "dev".to_owned()); println!("cargo:rustc-env=IM_BUILD_SHA={sha}"); let manifest = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("cargo sets the manifest dir")); let out = PathBuf::from(env::var("OUT_DIR").expect("cargo sets OUT_DIR")); // The stylesheet is compiled from the repository-level `style/` directory. Its partials are // `@use`d relative to `main.scss`, so no load path is needed. let css = grass::from_path( manifest.join("../../style/main.scss"), &grass::Options::default(), ) .unwrap_or_else(|e| panic!("compiling style/main.scss: {e}")); fs::write(out.join("main.css"), &css).expect("writing the compiled stylesheet to OUT_DIR"); println!( "cargo:rustc-env=IM_MAIN_CSS_V={}", content_version(css.as_bytes()) ); for (var, file) in [ ("IM_NAV_JS_V", "assets/nav.js"), ("IM_PAGES_JS_V", "assets/pages.js"), ] { let bytes = fs::read(manifest.join(file)).unwrap_or_else(|e| panic!("reading {file}: {e}")); println!("cargo:rustc-env={var}={}", content_version(&bytes)); } } /// The first `VERSION_HEX_LEN` hex characters of the SHA-256 of `bytes`. fn content_version(bytes: &[u8]) -> String { encode(Sha256::digest(bytes))[..VERSION_HEX_LEN].to_owned() }