mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-06 05:53:08 -05:00
264 lines
15 KiB
Rust
264 lines
15 KiB
Rust
//! `cargo xtask web-fonts`: the Trunk `post_build` hook (`apps/*-web/Trunk.toml`). Copies the
|
|
//! craft-fonts faces listed in `crates/text/web-fonts.txt` from `$CRAFT_FONTS_DIR` into the site,
|
|
//! each at `fonts/<first 16 hex digits of its SHA-256>/<file>` with its licence beside it: the URLs
|
|
//! `crates/text/build.rs` puts in `WEB_FONTS` (both use `crates/text/build/web_fonts.rs`). The
|
|
//! `startup` and `demand` faces are also published under `fonts/ui/`, where the interface font stack
|
|
//! fetches them (`SERVED_FONTS`), with the craft-fonts-build `Embed::serve` that build.rs uses.
|
|
//!
|
|
//! A no-op without `CRAFT_FONTS_DIR`. A listed face the checkout lacks (an older craft-fonts) is
|
|
//! skipped with a warning, as `build.rs` does; a file whose SHA-256 doesn't match the manifest is an
|
|
//! error (a corrupt checkout). Rust rather than a shell script, so the hook runs wherever cargo does.
|
|
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use crate::sha256;
|
|
|
|
#[allow(dead_code)] // build.rs uses the rest (sri, base64)
|
|
#[path = "../../crates/text/build/web_fonts.rs"]
|
|
mod list;
|
|
|
|
/// The hook: reads `CRAFT_FONTS_DIR` and Trunk's `TRUNK_STAGING_DIR`.
|
|
pub fn run(root: &Path) -> Result<(), String> {
|
|
let var = |name| std::env::var_os(name).filter(|v| !v.is_empty()).map(PathBuf::from);
|
|
run_with(root, var("CRAFT_FONTS_DIR"), var("TRUNK_STAGING_DIR"))
|
|
}
|
|
|
|
fn run_with(root: &Path, craft_fonts: Option<PathBuf>, staging: Option<PathBuf>) -> Result<(), String> {
|
|
let Some(dir) = craft_fonts else { return Ok(()) };
|
|
// Relative like build.rs: from the workspace root, not the directory Trunk runs hooks in.
|
|
let dir = if dir.is_absolute() { dir } else { root.join(dir) };
|
|
let staging = staging.ok_or("TRUNK_STAGING_DIR is unset: run this as the Trunk post_build hook")?;
|
|
let (copied, skipped) = copy(&root.join("crates/text/web-fonts.txt"), &dir, &staging)?;
|
|
if !skipped.is_empty() {
|
|
eprintln!("warning: web build won't fetch {} (not in CRAFT_FONTS_DIR={}; an older craft-fonts?)", skipped.join(", "), dir.display());
|
|
}
|
|
println!("web-fonts: copied {copied} font(s) into {}", staging.join("fonts").display());
|
|
let served = serve(&root.join("crates/text/web-fonts.txt"), &dir, &staging, None)?;
|
|
println!("web-fonts: published {served} interface font(s) into {}", staging.join(SERVED_URL).display());
|
|
Ok(())
|
|
}
|
|
|
|
/// Where the site serves the interface font stack's faces: the URL prefix `crates/text/build.rs`
|
|
/// gives them in `SERVED_FONTS`.
|
|
const SERVED_URL: &str = "fonts/ui/";
|
|
|
|
/// Publish the faces the web interface's font stack fetches (the list's `startup` and `demand`
|
|
/// lines) into `site` at their `fonts/ui/…` URLs. `crates/text/build.rs` serves the same faces with
|
|
/// the same craft-fonts-build `Embed::serve` into its `OUT_DIR`, for the URLs, sizes and integrity
|
|
/// values of `SERVED_FONTS`; this puts the files where those URLs point. `required` overrides
|
|
/// `CRAFT_FONTS_REQUIRED`, which decides it otherwise, as in build.rs. Returns how many faces.
|
|
fn serve(list_path: &Path, dir: &Path, site: &Path, required: Option<bool>) -> Result<usize, String> {
|
|
let list = std::fs::read_to_string(list_path).map_err(|e| format!("{}: {e}", list_path.display()))?;
|
|
let faces: Vec<(String, String)> =
|
|
list::parse_list(&list)?.into_iter().filter(|e| e.startup || e.demand).map(|e| (e.family.to_owned(), e.style.to_owned())).collect();
|
|
// build.rs's table is the one the app uses; this copy, and Embed's hash cache beside it, go.
|
|
// A private folder this call creates (random name, created exclusively, owner-only on Unix)
|
|
// and removes when `scratch` drops, so nothing another process made is reused or removed.
|
|
let scratch = tempfile::Builder::new().prefix("vectorcraft-web-fonts-").tempdir().map_err(|e| format!("scratch folder: {e}"))?;
|
|
let embed = craft_fonts_build::Embed::new().dir(dir);
|
|
let embed = match required {
|
|
Some(required) => embed.required(required),
|
|
None => embed,
|
|
};
|
|
let served = embed
|
|
.filter(move |f| faces.iter().any(|(family, style)| f.family == *family && f.style == *style))
|
|
.serve(site.join(SERVED_URL), SERVED_URL)
|
|
.write(scratch.path().join("served.rs"));
|
|
served.map(|faces| faces.len()).map_err(|e| e.to_string())
|
|
}
|
|
|
|
/// Copy the faces `list_path` names from the craft-fonts checkout `dir` into `site` (at their
|
|
/// `fonts/…` URLs). Returns how many were copied and the listed faces the checkout lacks.
|
|
fn copy(list_path: &Path, dir: &Path, site: &Path) -> Result<(usize, Vec<String>), String> {
|
|
let read = |p: &Path| std::fs::read_to_string(p).map_err(|e| format!("{}: {e}", p.display()));
|
|
let list = read(list_path)?;
|
|
let manifest = read(&dir.join("fonts/manifest.txt"))?;
|
|
let rows: Vec<Vec<&str>> =
|
|
manifest.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')).map(|l| l.split(" | ").map(str::trim).collect()).collect();
|
|
let (mut copied, mut skipped) = (0, Vec::new());
|
|
for e in list::parse_list(&list)? {
|
|
let Some(row) = rows.iter().find(|r| r.first() == Some(&e.family) && r.get(1) == Some(&e.style)) else {
|
|
skipped.push(format!("{} {}", e.family, e.style));
|
|
continue;
|
|
};
|
|
let (Some(file), Some(licence), Some(sha)) = (row.get(2), row.get(5), row.get(6)) else {
|
|
return Err(format!("malformed manifest row for {} {}", e.family, e.style));
|
|
};
|
|
let root = std::fs::canonicalize(dir).map_err(|err| format!("{}: {err}", dir.display()))?;
|
|
let bytes = std::fs::read(inside(&root, file)?).map_err(|err| format!("{file}: {err}"))?;
|
|
let got = sha256::hex(&bytes);
|
|
if got != *sha {
|
|
return Err(format!("{file}: sha256 {got}, manifest says {sha}"));
|
|
}
|
|
let dest = site.join(list::url(sha, file));
|
|
let folder = dest.parent().ok_or_else(|| format!("{}: no parent folder", dest.display()))?;
|
|
std::fs::create_dir_all(folder).map_err(|err| format!("{}: {err}", folder.display()))?;
|
|
std::fs::write(&dest, &bytes).map_err(|err| format!("{}: {err}", dest.display()))?;
|
|
let src = inside(&root, licence)?;
|
|
// Served as plain text whatever the supplier named it: a `.html` licence would be a page.
|
|
let stem = src.file_stem().ok_or_else(|| format!("{licence}: not a file"))?.to_string_lossy();
|
|
std::fs::copy(&src, folder.join(format!("{stem}.txt"))).map_err(|err| format!("{licence}: {err}"))?;
|
|
copied += 1;
|
|
}
|
|
Ok((copied, skipped))
|
|
}
|
|
|
|
/// The biggest font or licence file copied (bytes).
|
|
const MAX_FILE: u64 = 64 << 20;
|
|
|
|
/// Manifest path `file` (supplier data) as a regular file of at most [`MAX_FILE`] bytes inside the
|
|
/// canonical checkout `root`: no `..`, absolute path or symlink out of it, and no device or FIFO.
|
|
fn inside(root: &Path, file: &str) -> Result<PathBuf, String> {
|
|
let src = std::fs::canonicalize(root.join(file)).map_err(|err| format!("{file}: {err}"))?;
|
|
let meta = std::fs::metadata(&src).map_err(|err| format!("{file}: {err}"))?;
|
|
if !src.starts_with(root) || !meta.is_file() || meta.len() > MAX_FILE {
|
|
return Err(format!("{file}: not a file of at most {MAX_FILE} bytes inside the font checkout"));
|
|
}
|
|
Ok(src)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
/// A fake craft-fonts checkout with one face, and a list naming it plus one it lacks.
|
|
fn fixture(name: &str, manifest_sha: Option<&str>) -> (PathBuf, PathBuf, PathBuf, String) {
|
|
let base = std::env::temp_dir().join(format!("xtask-web-fonts-{name}-{}", std::process::id()));
|
|
let _ = std::fs::remove_dir_all(&base);
|
|
let dir = base.join("craft-fonts");
|
|
std::fs::create_dir_all(dir.join("fonts/a")).unwrap();
|
|
std::fs::write(dir.join("fonts/a/A-Regular.ttf"), b"font bytes").unwrap();
|
|
std::fs::write(dir.join("fonts/a/OFL.txt"), b"licence").unwrap();
|
|
let sha = sha256::hex(b"font bytes");
|
|
let row_sha = manifest_sha.map_or(sha.clone(), str::to_string);
|
|
std::fs::write(
|
|
dir.join("fonts/manifest.txt"),
|
|
format!("# family | style | file | scripts | licence | licence file | sha256 | source\nA Sans | Regular | fonts/a/A-Regular.ttf | Arab | OFL-1.1 | fonts/a/OFL.txt | {row_sha} | https://example.invalid\n"),
|
|
)
|
|
.unwrap();
|
|
let list = base.join("web-fonts.txt");
|
|
std::fs::write(&list, "startup | A Sans | Regular\nbackground | Missing Sans | Bold\n").unwrap();
|
|
(list, dir, base.join("site"), sha)
|
|
}
|
|
|
|
#[test]
|
|
fn copies_listed_faces_with_their_licence_to_their_urls() {
|
|
let (list, dir, site, sha) = fixture("copy", None);
|
|
let (copied, skipped) = copy(&list, &dir, &site).unwrap();
|
|
assert_eq!(copied, 1);
|
|
let at = site.join("fonts").join(&sha[..16]);
|
|
assert_eq!(std::fs::read(at.join("A-Regular.ttf")).unwrap(), b"font bytes");
|
|
assert_eq!(std::fs::read(at.join("OFL.txt")).unwrap(), b"licence");
|
|
assert_eq!(format!("fonts/{}/A-Regular.ttf", &sha[..16]), list::url(&sha, "fonts/a/A-Regular.ttf"));
|
|
assert_eq!(skipped, ["Missing Sans Bold"], "a face the checkout lacks is skipped, not an error");
|
|
}
|
|
|
|
/// The interface font stack fetches `startup` and `demand` faces from `fonts/ui/` (build.rs's
|
|
/// `SERVED_FONTS`), so the site holds them there, licence beside; `background` faces are only
|
|
/// fetched from `fonts/<sha16>/`.
|
|
#[test]
|
|
fn publishes_the_interface_faces_at_their_served_urls() {
|
|
let (list, dir, site, _) = fixture("serve", None);
|
|
assert_eq!(serve(&list, &dir, &site, Some(false)).unwrap(), 1);
|
|
let at = site.join("fonts/ui/a");
|
|
assert_eq!(std::fs::read(at.join("A-Regular.ttf")).unwrap(), b"font bytes");
|
|
assert_eq!(std::fs::read(at.join("OFL.txt")).unwrap(), b"licence");
|
|
|
|
let (list, dir, site, _) = fixture("serve-demand", None);
|
|
std::fs::write(&list, "demand | A Sans | Regular\n").unwrap();
|
|
assert_eq!(serve(&list, &dir, &site, Some(false)).unwrap(), 1);
|
|
assert!(site.join("fonts/ui/a/A-Regular.ttf").exists(), "a face fetched on demand is an interface face");
|
|
|
|
let (list, dir, site, _) = fixture("serve-background", None);
|
|
std::fs::write(&list, "background | A Sans | Regular\n").unwrap();
|
|
assert_eq!(serve(&list, &dir, &site, Some(false)).unwrap(), 0);
|
|
assert!(!site.join("fonts/ui/a/A-Regular.ttf").exists(), "a background face is not an interface face");
|
|
}
|
|
|
|
#[test]
|
|
fn a_file_that_does_not_match_its_manifest_hash_is_an_error() {
|
|
let (list, dir, site, _) = fixture("mismatch", Some(&"0".repeat(64)));
|
|
let e = copy(&list, &dir, &site).unwrap_err();
|
|
assert!(e.contains("A-Regular.ttf") && e.contains("sha256"), "{e}");
|
|
}
|
|
|
|
#[test]
|
|
fn a_licence_path_that_leaves_the_checkout_is_refused() {
|
|
let (list, dir, site, _) = fixture("escape", None);
|
|
std::fs::write(dir.parent().unwrap().join("secret.txt"), b"secret").unwrap();
|
|
let m = dir.join("fonts/manifest.txt");
|
|
let text = std::fs::read_to_string(&m).unwrap().replace("fonts/a/OFL.txt", "../secret.txt");
|
|
std::fs::write(&m, text).unwrap();
|
|
let e = copy(&list, &dir, &site).unwrap_err();
|
|
assert!(e.contains("inside the font checkout"), "{e}");
|
|
}
|
|
|
|
#[test]
|
|
fn a_font_path_that_leaves_the_checkout_or_is_no_file_is_refused() {
|
|
let (list, dir, site, _) = fixture("font-escape", None);
|
|
let m = dir.join("fonts/manifest.txt");
|
|
let manifest = std::fs::read_to_string(&m).unwrap();
|
|
let outside = dir.parent().unwrap().join("secret.ttf");
|
|
std::fs::write(&outside, b"secret").unwrap();
|
|
for path in ["../secret.ttf", outside.to_str().unwrap(), "fonts/a"] {
|
|
std::fs::write(&m, manifest.replace("fonts/a/A-Regular.ttf", path)).unwrap();
|
|
let e = copy(&list, &dir, &site).unwrap_err();
|
|
assert!(e.contains("inside the font checkout"), "{path}: {e}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_licence_is_published_as_text() {
|
|
let (list, dir, site, sha) = fixture("html-licence", None);
|
|
std::fs::write(dir.join("fonts/a/LICENSE.html"), b"<script>").unwrap();
|
|
let m = dir.join("fonts/manifest.txt");
|
|
std::fs::write(&m, std::fs::read_to_string(&m).unwrap().replace("fonts/a/OFL.txt", "fonts/a/LICENSE.html")).unwrap();
|
|
copy(&list, &dir, &site).unwrap();
|
|
let at = site.join("fonts").join(&sha[..16]);
|
|
assert!(at.join("LICENSE.txt").exists() && !at.join("LICENSE.html").exists());
|
|
}
|
|
|
|
/// The real hook on the real list: every `startup` and `demand` face (Gujarati included) lands
|
|
/// in the packaged site under `fonts/ui/`, byte for byte the file the craft-fonts manifest
|
|
/// hashes. Needs a craft-fonts checkout in `CRAFT_FONTS_DIR`; skips without one unless
|
|
/// `CRAFT_FONTS_REQUIRED=1`.
|
|
#[test]
|
|
fn the_packaged_site_serves_every_interface_face_as_the_manifest_hashes_it() {
|
|
let root = Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap();
|
|
let Some(dir) = std::env::var_os("CRAFT_FONTS_DIR").filter(|v| !v.is_empty()).map(PathBuf::from) else {
|
|
assert!(std::env::var("CRAFT_FONTS_REQUIRED").as_deref() != Ok("1"), "CRAFT_FONTS_REQUIRED=1 but CRAFT_FONTS_DIR is unset");
|
|
eprintln!("skipping: set CRAFT_FONTS_DIR to a craft-fonts checkout");
|
|
return;
|
|
};
|
|
let dir = if dir.is_absolute() { dir } else { root.join(dir) };
|
|
let site = tempfile::tempdir().unwrap();
|
|
run_with(root, Some(dir.clone()), Some(site.path().to_path_buf())).unwrap();
|
|
|
|
let list = std::fs::read_to_string(root.join("crates/text/web-fonts.txt")).unwrap();
|
|
let manifest = std::fs::read_to_string(dir.join("fonts/manifest.txt")).unwrap();
|
|
let mut checked = Vec::new();
|
|
for e in list::parse_list(&list).unwrap().into_iter().filter(|e| e.startup || e.demand) {
|
|
let row = manifest
|
|
.lines()
|
|
.map(|l| l.split(" | ").map(str::trim).collect::<Vec<_>>())
|
|
.find(|r| r.first() == Some(&e.family) && r.get(1) == Some(&e.style));
|
|
let Some(row) = row else { continue }; // an older craft-fonts lacks it; build.rs skips it too
|
|
let file = row[2].strip_prefix("fonts/").unwrap();
|
|
let bytes = std::fs::read(site.path().join(SERVED_URL).join(file)).unwrap_or_else(|err| panic!("{SERVED_URL}{file}: {err}"));
|
|
assert_eq!(sha256::hex(&bytes), row[6], "{SERVED_URL}{file} differs from the manifest");
|
|
checked.push(e.family.to_owned());
|
|
}
|
|
// An older craft-fonts without the Gujarati face stays valid; one that has it must publish it.
|
|
if manifest.lines().any(|l| l.starts_with("Noto Sans Gujarati | Regular |")) {
|
|
assert!(checked.iter().any(|f| f == "Noto Sans Gujarati"), "the Gujarati face was not published: {checked:?}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn without_craft_fonts_the_hook_does_nothing() {
|
|
let (_, _, site, _) = fixture("noop", None);
|
|
run_with(Path::new("/nonexistent"), None, None).unwrap();
|
|
assert!(!site.exists());
|
|
}
|
|
}
|