forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

build.rs57 lines, 2.5 KiBHistoryRawDownload
1//! Build script of the `im` binary. It compiles `style/main.scss` into `OUT_DIR/main.css`, and it
2//! emits the build identity and the content hashes that the page links use as cache-busting
3//! queries: `IM_MAIN_CSS_V`, `IM_NAV_JS_V`, `IM_PAGES_JS_V` and `IM_BUILD_SHA`.
4//!
5//! It does not decide what is served: `src/assets.rs` embeds the files. It does not decide what a
6//! page links to either: `src/assets.rs` builds the `?v=` URLs from these values. It only compiles
7//! and hashes, so a changed file gets a new hash and an unchanged file keeps its URL.
8
9use std::{env, fs, path::PathBuf};
10
11use hex::encode;
12use sha2::{Digest, Sha256};
13
14/// Number of hex characters of the SHA-256 that make a content version. Twelve characters are 48
15/// bits, which is plenty to tell two builds of one file apart.
16const VERSION_HEX_LEN: usize = 12;
17
18fn main() {
19 println!("cargo:rerun-if-env-changed=IM_BUILD_SHA");
20 println!("cargo:rerun-if-changed=../../style");
21 println!("cargo:rerun-if-changed=assets");
22 println!("cargo:rerun-if-changed=build.rs");
23
24 // The commit identity shown by `/healthz`. The release script sets it; a local build says `dev`.
25 let sha = env::var("IM_BUILD_SHA").unwrap_or_else(|_| "dev".to_owned());
26 println!("cargo:rustc-env=IM_BUILD_SHA={sha}");
27
28 let manifest =
29 PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("cargo sets the manifest dir"));
30 let out = PathBuf::from(env::var("OUT_DIR").expect("cargo sets OUT_DIR"));
31
32 // The stylesheet is compiled from the repository-level `style/` directory. Its partials are
33 // `@use`d relative to `main.scss`, so no load path is needed.
34 let css = grass::from_path(
35 manifest.join("../../style/main.scss"),
36 &grass::Options::default(),
37 )
38 .unwrap_or_else(|e| panic!("compiling style/main.scss: {e}"));
39 fs::write(out.join("main.css"), &css).expect("writing the compiled stylesheet to OUT_DIR");
40 println!(
41 "cargo:rustc-env=IM_MAIN_CSS_V={}",
42 content_version(css.as_bytes())
43 );
44
45 for (var, file) in [
46 ("IM_NAV_JS_V", "assets/nav.js"),
47 ("IM_PAGES_JS_V", "assets/pages.js"),
48 ] {
49 let bytes = fs::read(manifest.join(file)).unwrap_or_else(|e| panic!("reading {file}: {e}"));
50 println!("cargo:rustc-env={var}={}", content_version(&bytes));
51 }
52}
53
54/// The first `VERSION_HEX_LEN` hex characters of the SHA-256 of `bytes`.
55fn content_version(bytes: &[u8]) -> String {
56 encode(Sha256::digest(bytes))[..VERSION_HEX_LEN].to_owned()
57}