Skip to main content

max / makenotwork

2.3 KB · 64 lines History Blame Raw
1 use std::collections::hash_map::DefaultHasher;
2 use std::hash::{Hash, Hasher};
3 use std::process::Command;
4 use std::{fs, path::Path};
5
6 fn main() {
7 // Set GIT_HASH env var for compile-time inclusion via option_env!()
8 let hash = Command::new("git")
9 .args(["rev-parse", "--short", "HEAD"])
10 .output()
11 .ok()
12 .filter(|o| o.status.success())
13 .and_then(|o| String::from_utf8(o.stdout).ok())
14 .map(|s| s.trim().to_string())
15 .unwrap_or_default();
16
17 println!("cargo::rustc-env=GIT_HASH={}", hash);
18 // Only re-run when HEAD changes
19 println!("cargo::rerun-if-changed=.git/HEAD");
20
21 // --- Static asset fingerprinting ---
22 // Hash the content of key static files to produce a version suffix.
23 // When any watched file changes, URLs in templates get a new ?v= param,
24 // busting browser caches automatically.
25 let static_files = [
26 "static/style.css",
27 "static/htmx.min.js",
28 "static/upload.js",
29 "static/passkey.js",
30 "static/insertions.js",
31 ];
32
33 let mut hasher = DefaultHasher::new();
34 for path in &static_files {
35 println!("cargo::rerun-if-changed={}", path);
36 if let Ok(content) = fs::read(path) {
37 content.hash(&mut hasher);
38 }
39 }
40 let static_hash = format!("{:016x}", hasher.finish());
41 let version = &static_hash[..8];
42
43 // Generate a template partial with versioned asset URLs.
44 // base.html includes this via {% include "_head_assets.html" %}
45 let partial = format!(
46 r#" <link rel="preload" href="/static/fonts/Lato-Regular.woff2" as="font" type="font/woff2" crossorigin>
47 <link rel="preload" href="/static/fonts/ysrf.woff2" as="font" type="font/woff2" crossorigin>
48 <link rel="stylesheet" href="/static/style.css?v={v}">
49 <link rel="icon" href="/static/images/favicon.ico" type="image/x-icon">
50 <script src="/static/htmx.min.js"></script>
51 <script src="/static/upload.js?v={v}"></script>"#,
52 v = version,
53 );
54
55 let out_path = Path::new("templates/_head_assets.html");
56 // Only write if content changed (avoids unnecessary recompilation)
57 let needs_write = fs::read_to_string(out_path)
58 .map(|existing| existing != partial)
59 .unwrap_or(true);
60 if needs_write {
61 fs::write(out_path, &partial).expect("failed to write _head_assets.html");
62 }
63 }
64