dotfiles

My PC Dotfiles & Website

site/scripts/optimize_fonts.py (2480B)


 1"""Subset generated webfonts, retaining all text glyphs and referenced Nerd icons"""
 2
 3import argparse
 4import html
 5import re
 6from pathlib import Path
 7
 8from fontTools import subset
 9from fontTools.ttLib import TTFont
10
11
12def private_use(codepoint):
13    return (
14        0xE000 <= codepoint <= 0xF8FF
15        or 0xF0000 <= codepoint <= 0xFFFFD
16        or 0x100000 <= codepoint <= 0x10FFFD
17    )
18
19
20def optimize(output, source):
21    used = set()
22    for path in sorted(output.rglob("*")):
23        if path.suffix not in {".html", ".css", ".js", ".json", ".txt"}:
24            continue
25        text = html.unescape(path.read_text(encoding="utf-8"))
26        used.update(map(ord, text))
27        # CSS content escapes and JavaScript/JSON Unicode escapes
28        used.update(
29            int(value, 16) for value in re.findall(r"\\([0-9a-fA-F]{1,6})", text)
30        )
31        used.update(
32            int(value, 16) for value in re.findall(r"\\u\{?([0-9a-fA-F]{4,6})", text)
33        )
34
35    fonts = sorted(source.glob("JetBrainsMono-Nerd-*.woff2"))
36    if not fonts:
37        raise FileNotFoundError(f"No source webfonts in {source}")
38    for path in fonts:
39        font = TTFont(path, recalcTimestamp=False)
40        required = {
41            codepoint for codepoint in font.getBestCmap() if not private_use(codepoint)
42        } | used
43        options = subset.Options()
44        options.layout_features = ["*"]
45        options.name_IDs = ["*"]
46        options.name_legacy = True
47        options.name_languages = ["*"]
48        options.drop_tables += ["FFTM", "PfEd"]  # FontForge editor metadata
49        subsetter = subset.Subsetter(options=options)
50        subsetter.populate(unicodes=required)
51        subsetter.subset(font)
52        target = output / "fonts" / path.name
53        target.parent.mkdir(parents=True, exist_ok=True)
54        font.save(target)
55        font.close()
56        print(f"{path.name}: {path.stat().st_size:,} → {target.stat().st_size:,} bytes")
57
58
59if __name__ == "__main__":
60    parser = argparse.ArgumentParser(description=__doc__)
61    parser.add_argument("output", type=Path)
62    parser.add_argument("--source", type=Path, default=Path("static/fonts"))
63    args = parser.parse_args()
64    if not args.output.is_dir():
65        parser.error("output must be an existing generated site directory")
66    if (args.output / "fonts").resolve() == args.source.resolve():
67        parser.error("output fonts must be separate from the source fonts")
68    optimize(args.output, args.source)