char/sorcery

static-files based git repo viewer

git clone https://git.t4t.associates/char/sorcery

Charlotte Somadd custom theme.cssb45076d

main
6.2 KiB183 linesraw
1use std::env;
2use std::fs;
3use std::path::{Path, PathBuf};
4
5use sha2::{Digest, Sha256};
6
7fn files(root: &Path, dir: &Path, output: &mut Vec<PathBuf>) {
8    let mut entries = fs::read_dir(dir)
9        .unwrap_or_else(|error| panic!("reading {}: {error}", dir.display()))
10        .map(|entry| entry.unwrap().path())
11        .collect::<Vec<_>>();
12    entries.sort();
13    for path in entries {
14        if path.is_dir() {
15            files(root, &path, output);
16        } else {
17            output.push(path.strip_prefix(root).unwrap().to_owned());
18        }
19    }
20}
21
22fn hash(bytes: &[u8], length: usize) -> String {
23    format!("{:x}", Sha256::digest(bytes))[..length].to_owned()
24}
25
26fn main() {
27    for path in [
28        "src/style.css",
29        "assets/fonts",
30        "web/dist",
31        ".glisten/dist/manifest.json",
32    ] {
33        println!("cargo::rerun-if-changed={path}");
34    }
35    let manifest = fs::read(".glisten/dist/manifest.json")
36        .expect("missing .glisten/dist/manifest.json; run deno task glisten first");
37    let entries = fs::read_dir("web/dist")
38        .expect("missing web/dist; run deno task build")
39        .map(|entry| entry.expect("reading web/dist entry"))
40        .filter(|entry| entry.file_type().expect("reading web asset type").is_file())
41        .map(|entry| {
42            entry
43                .file_name()
44                .into_string()
45                .expect("non-UTF-8 web asset")
46        })
47        .collect::<Vec<_>>();
48    let entry = |prefix: &str| {
49        let matches = entries
50            .iter()
51            .filter(|name| {
52                name.starts_with(prefix) && name.ends_with(".js") && name.len() > prefix.len() + 3
53            })
54            .collect::<Vec<_>>();
55        assert!(
56            matches.len() == 1,
57            "expected exactly one {prefix}*.js in web/dist; run deno task build"
58        );
59        matches[0].as_str()
60    };
61    let main_js = entry("main-");
62    let worker_js = entry("highlight-worker-");
63
64    let mut digest = Sha256::new();
65    let root = Path::new("assets/fonts");
66    let mut paths = Vec::new();
67    files(root, root, &mut paths);
68    paths.sort();
69    let fonts = paths
70        .iter()
71        .map(|path| {
72            let source = path.to_str().expect("non-UTF-8 font path");
73            let bytes = fs::read(root.join(path)).expect("reading font");
74            let content_hash = Sha256::digest(&bytes);
75            digest.update((source.len() as u64).to_be_bytes());
76            digest.update(source.as_bytes());
77            digest.update(content_hash);
78            let staged = if path.extension().is_some_and(|ext| ext == "woff2") {
79                let stem = path.file_stem().unwrap().to_str().unwrap();
80                let hash = format!("{content_hash:x}");
81                path.with_file_name(format!("{stem}-{}.woff2", &hash[..12]))
82                    .to_str()
83                    .unwrap()
84                    .to_owned()
85            } else {
86                source.to_owned()
87            };
88            (source.to_owned(), staged)
89        })
90        .collect::<Vec<_>>();
91
92    let css = fs::read_to_string("src/style.css").expect("reading stylesheet");
93    let root = css
94        .split_once(":root {")
95        .expect("stylesheet has a :root block")
96        .1
97        .split_once('}')
98        .expect("stylesheet :root block is closed")
99        .0;
100    let mut declarations = root
101        .lines()
102        .filter_map(|line| {
103            let trimmed = line.trim();
104            if trimmed.is_empty() {
105                Some("")
106            } else if [
107                "color-scheme:",
108                "--bg-",
109                "--fg-",
110                "--accent-",
111                "--selection-col:",
112                "--hl-",
113            ]
114            .iter()
115            .any(|prefix| trimmed.starts_with(prefix))
116            {
117                Some(line)
118            } else {
119                None
120            }
121        })
122        .collect::<Vec<_>>();
123    declarations.dedup_by(|a, b| a.is_empty() && b.is_empty());
124    let declarations = declarations.join("\n");
125    let declarations = declarations.trim_matches('\n');
126    let theme = format!("/*\n:root {{\n{declarations}\n}}\n*/\n");
127    let mut rewritten = String::new();
128    let mut rest = css.as_str();
129    while let Some(index) = rest.find("/fonts/") {
130        rewritten.push_str(&rest[..index]);
131        rest = &rest[index + "/fonts/".len()..];
132        let end = rest
133            .find(|c: char| matches!(c, '\'' | '"' | ')' | '(') || c.is_whitespace())
134            .unwrap_or(rest.len());
135        let source = &rest[..end];
136        let staged = fonts
137            .iter()
138            .find(|(path, _)| path == source && path.ends_with(".woff2"))
139            .unwrap_or_else(|| panic!("unknown stylesheet font: /fonts/{source}"));
140        rewritten.push_str("/fonts/");
141        rewritten.push_str(&staged.1);
142        rest = &rest[end..];
143    }
144    rewritten.push_str(rest);
145    let style = format!("style-{}.css", hash(rewritten.as_bytes(), 12));
146    for bytes in [
147        style.as_bytes(),
148        main_js.as_bytes(),
149        worker_js.as_bytes(),
150        manifest.as_slice(),
151    ] {
152        digest.update((bytes.len() as u64).to_be_bytes());
153        digest.update(bytes);
154    }
155    let root = Path::new("web/dist");
156    let mut paths = Vec::new();
157    files(root, root, &mut paths);
158    paths.sort();
159    for path in paths {
160        let name = path.to_str().expect("non-UTF-8 web asset path");
161        let bytes = fs::read(root.join(&path)).expect("reading web asset");
162        digest.update((name.len() as u64).to_be_bytes());
163        digest.update(name.as_bytes());
164        digest.update((bytes.len() as u64).to_be_bytes());
165        digest.update(bytes);
166    }
167    let digest = format!("{:x}", digest.finalize());
168    let generated = format!(
169        "pub const MAIN_JS_FILE: &str = {main_js:?};\n\
170         pub const WORKER_JS_FILE: &str = {worker_js:?};\n\
171         pub const STYLE_CSS_FILE: &str = {style:?};\n\
172         pub const STYLESHEET: &str = {rewritten:?};\n\
173         pub const THEME_STYLESHEET: &str = {theme:?};\n\
174         pub const FONT_FILES: &[(&str, &str)] = &{fonts:?};\n\
175         pub const ASSET_DIGEST: &str = {:?};\n",
176        &digest[..16]
177    );
178    fs::write(
179        Path::new(&env::var_os("OUT_DIR").unwrap()).join("assets.rs"),
180        generated,
181    )
182    .expect("writing asset manifest");
183}