rcom/tools/import_themes.py

251 lines
16 KiB
Python

#!/usr/bin/env python3
"""Audited, development-only kitty theme importer. Runtime never fetches themes."""
from __future__ import annotations
import argparse
import hashlib
import json
import subprocess
from dataclasses import dataclass
from pathlib import Path
KITTY_COMMIT = "a35d12290c3d6a74b1f94debc81281cb637f3568"
MIT_LICENSE = "MIT"
@dataclass(frozen=True)
class Expected:
author: str
source_sha256: str
upstream_repo: str
upstream_commit: str
upstream_license: str
notice_sha256: str
EXPECTED = {
"dracula": Expected("Keegan Carruthers-Smith", "a4075ea3798795960e0205638ff55f6a506f60437938d94dc2a1aab62140d3ae", "https://github.com/dracula/kitty", "87717a3f00e3dff0fc10c93f5ff535ea4092de70", "MIT", "cec9a8b95af931c9ae66cc8bf793899251db01a13f0d68d26b92c9f44b87a8d5"),
"catppuccin-mocha": Expected("Pocco81 (https://github.com/Pocco81)", "9d3f69cdb6d14d651782f7265ad9f00a687344fe8508b171b16688da9ae2bfa0", "https://github.com/catppuccin/kitty", "177d447f0c3626959ef001b4605f5d844541fd63", "MIT", "814096d2c34cc216c624738a49356f32b7237733b4f7edb0685f4e50ef5074ba"),
"catppuccin-latte": Expected("Pocco81 (https://github.com/Pocco81)", "3e32d197b44d817db2e2c5835e698184c66b43b85fd78dce1e1b235b0d014974", "https://github.com/catppuccin/kitty", "177d447f0c3626959ef001b4605f5d844541fd63", "MIT", "814096d2c34cc216c624738a49356f32b7237733b4f7edb0685f4e50ef5074ba"),
"gruvbox-dark": Expected("Pavel Pertsev", "3c7162ea53fde5e0437d025563689d9868970839e28a7bbd35bd52bfd5f30afa", "https://github.com/gruvbox-community/gruvbox", "180ad85971343df68be3422a5630fa84e45a9ab2", "MIT", "6d3c2ebc79cb645dc1d2068f413d2d1dfcdbd869e4708773afcf2c388bef1f36"),
"gruvbox-light": Expected("Pavel Pertsev", "7304f0b97be113af68d3a8ae85cbeca7a24346ce5847bd3710c837e6107e1073", "https://github.com/gruvbox-community/gruvbox", "180ad85971343df68be3422a5630fa84e45a9ab2", "MIT", "6d3c2ebc79cb645dc1d2068f413d2d1dfcdbd869e4708773afcf2c388bef1f36"),
"solarized-dark": Expected("Ethan Schoonover", "fc23242afc7cbbc7b6b97ac45a4607e1e9181d4823b42054dc3d9099fd9e1743", "https://github.com/altercation/solarized", "62f656a02f93c5190a8753159e34b385588d5ff3", "MIT", "494aefdabf86acce06bd63001ad8aedad4ee38da23509d3f917d95aa3368b9a6"),
"solarized-light": Expected("Ethan Schoonover", "3c5064623dbe2deb76d1efa2f304893182486d511567893a9653fef65ae8c9d4", "https://github.com/altercation/solarized", "62f656a02f93c5190a8753159e34b385588d5ff3", "MIT", "494aefdabf86acce06bd63001ad8aedad4ee38da23509d3f917d95aa3368b9a6"),
"tokyo-night": Expected("Folke Lemaitre", "e92085fb339ca9be916e3bc47fa6813843c6007b155d4f9bcb9fb5af545adc5c", "https://github.com/folke/tokyonight.nvim", "d8e9ca64c0b8e574051f14bf1486ecd12b81de89", "Apache-2.0", "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4"),
"tokyo-night-day": Expected("Folke Lemaitre", "3f6bb553ce120c20ce04c9f71eb811d4a4b3c3298370c1a04aa933ea244ec5bd", "https://github.com/folke/tokyonight.nvim", "d8e9ca64c0b8e574051f14bf1486ecd12b81de89", "Apache-2.0", "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4"),
"one-half-dark": Expected("Son A. Pham", "187e3e44bb61305f8d94bfa1513d5c19253672879e5429c96dba0add22f26120", "https://github.com/sonph/onehalf", "75eb2e97acd74660779fed8380989ee7891eec56", "MIT", "bb4a23db094e79ed8ffd9a38fbc6ff45cbdf9a1f4182fc7ff2667793a012c9a1"),
"one-half-light": Expected("Son A. Pham", "5329fccb5d0ba8cbd86292756bd7aa7cc1fca9098b51466cf4a419ae8eb3d797", "https://github.com/sonph/onehalf", "75eb2e97acd74660779fed8380989ee7891eec56", "MIT", "bb4a23db094e79ed8ffd9a38fbc6ff45cbdf9a1f4182fc7ff2667793a012c9a1"),
"rose-pine": Expected("mvllow", "0e8885538373c1e279553d2a6ce1ee2bf6a8302beaa9ccded9e39818225971ce", "https://github.com/rose-pine/kitty", "efd4f01cb9887feaa7114ff21a887464295d0205", "MIT", "b2ec9e48689252be5807d35d80689bbc40481c54d1f228c94dde8ffad1bdc824"),
"rose-pine-dawn": Expected("mvllow", "8a7a2de3d2e3018c02f6ab16e80b9600f151a8891da8ad8c2764e145adbd6f7a", "https://github.com/rose-pine/kitty", "efd4f01cb9887feaa7114ff21a887464295d0205", "MIT", "b2ec9e48689252be5807d35d80689bbc40481c54d1f228c94dde8ffad1bdc824"),
"everforest-dark-medium": Expected("Sainnhe Park", "038bf240b421f1430507f4432b7704403e917fbe69866b3bcaaeb55ec1a4be60", "https://github.com/sainnhe/everforest", "85a86eb62409e3ec88713bff3d1b9d7374e112e4", "MIT", "6504b9e62794cb58b61c90ea5fe598274086119f2126b8d8245708b2bfcc0e36"),
"everforest-light-medium": Expected("Sainnhe Park", "5009e7e9f24d0e5ea42ddd0fd481d74317bdd04bd53384b2c8fbe2bd8cab246d", "https://github.com/sainnhe/everforest", "85a86eb62409e3ec88713bff3d1b9d7374e112e4", "MIT", "6504b9e62794cb58b61c90ea5fe598274086119f2126b8d8245708b2bfcc0e36"),
"github-dark": Expected("GitHub", "db70f8f1b4204098dc464ea47c3de5071697bd6cc2c4f9d36068c30dd96eb824", "https://github.com/primer/github-vscode-theme", "738b0ac78f6a7cc16c8d541a71fa103d8637a64a", "MIT", "e2c871bb6effe9f6ec8d94d6596db33c4bfe4dd94969a6a9a2fb0473ebe6442e"),
"github-light": Expected("GitHub", "02dc60b8e33709fcaf728daec85882039ece71569bfc1e5c8757181b249dce9c", "https://github.com/primer/github-vscode-theme", "738b0ac78f6a7cc16c8d541a71fa103d8637a64a", "MIT", "e2c871bb6effe9f6ec8d94d6596db33c4bfe4dd94969a6a9a2fb0473ebe6442e"),
"flexoki-dark": Expected("Kepano", "126a74cd3d403611104aeaeb53d55a4b92f0a47ea1745f75b412e59aebc60975", "https://github.com/kepano/flexoki", "8d723bac4a9ac46adfdf99d42155286977aac72a", "MIT", "b0aeda2f9ebf5e09c6bfbf9323813ebeaedeabcc8cb441323c9f47aef9b05ba3"),
"flexoki-light": Expected("Kepano", "10c914e13591d500704750599728b35b9277635f33e76af7b52fc27039cbb284", "https://github.com/kepano/flexoki", "8d723bac4a9ac46adfdf99d42155286977aac72a", "MIT", "b0aeda2f9ebf5e09c6bfbf9323813ebeaedeabcc8cb441323c9f47aef9b05ba3"),
}
# id, source file, display name, expected mode, explicit upstream when kitty omits it
THEMES = [
("dracula", "Dracula.conf", "Dracula", "dark", None),
("catppuccin-mocha", "Catppuccin-Mocha.conf", "Catppuccin Mocha", "dark", None),
("catppuccin-latte", "Catppuccin-Latte.conf", "Catppuccin Latte", "light", None),
("gruvbox-dark", "gruvbox-dark.conf", "Gruvbox Dark", "dark", None),
("gruvbox-light", "gruvbox-light.conf", "Gruvbox Light", "light", None),
("solarized-dark", "Solarized_Dark.conf", "Solarized Dark", "dark", "https://github.com/altercation/solarized"),
("solarized-light", "Solarized_Light.conf", "Solarized Light", "light", "https://github.com/altercation/solarized"),
("tokyo-night", "tokyo_night_night.conf", "Tokyo Night", "dark", None),
("tokyo-night-day", "tokyo_night_day.conf", "Tokyo Night Day", "light", None),
("one-half-dark", "OneHalfDark.conf", "One Half Dark", "dark", None),
("one-half-light", "OneHalfLight.conf", "One Half Light", "light", None),
("rose-pine", "rose-pine.conf", "Rosé Pine", "dark", None),
("rose-pine-dawn", "rose-pine-dawn.conf", "Rosé Pine Dawn", "light", None),
("everforest-dark-medium", "everforest_dark_medium.conf", "Everforest Dark Medium", "dark", None),
("everforest-light-medium", "everforest_light_medium.conf", "Everforest Light Medium", "light", None),
("github-dark", "GitHub_Dark.conf", "GitHub Dark", "dark", "https://github.com/primer/github-vscode-theme"),
("github-light", "GitHub_Light.conf", "GitHub Light", "light", "https://github.com/primer/github-vscode-theme"),
("flexoki-dark", "flexoki_dark.conf", "Flexoki Dark", "dark", None),
("flexoki-light", "flexoki_light.conf", "Flexoki Light", "light", None),
]
LICENSE_REPOS = {
"dracula": "dracula/kitty",
"catppuccin-mocha": "catppuccin/kitty",
"catppuccin-latte": "catppuccin/kitty",
"gruvbox-dark": "gruvbox-community/gruvbox",
"gruvbox-light": "gruvbox-community/gruvbox",
"solarized-dark": "altercation/solarized",
"solarized-light": "altercation/solarized",
"tokyo-night": "folke/tokyonight.nvim",
"tokyo-night-day": "folke/tokyonight.nvim",
"one-half-dark": "sonph/onehalf",
"one-half-light": "sonph/onehalf",
"rose-pine": "rose-pine/kitty",
"rose-pine-dawn": "rose-pine/kitty",
"everforest-dark-medium": "sainnhe/everforest",
"everforest-light-medium": "sainnhe/everforest",
"github-dark": "primer/github-vscode-theme",
"github-light": "primer/github-vscode-theme",
"flexoki-dark": "kepano/flexoki",
"flexoki-light": "kepano/flexoki",
}
def parse_color(source: str, key: str, line_number: int) -> tuple[int, int, int]:
if len(source) != 7 or not source.startswith("#"):
raise ValueError(f"unsupported {key} at line {line_number}: {source!r}")
try:
return tuple(int(source[index:index + 2], 16) for index in (1, 3, 5))
except ValueError as error:
raise ValueError(f"invalid {key} at line {line_number}") from error
def parse_conf(path: Path) -> dict[str, tuple[int, int, int]]:
allowed = {"foreground", "background", "selection_foreground", "selection_background", "tab_bar_background", "inactive_tab_background", "inactive_tab_foreground", "active_border_color", "url_color"}
allowed.update(f"color{index}" for index in range(16))
result = {}
for line_number, raw in enumerate(path.read_text().splitlines(), 1):
line = raw.strip()
if not line or line.startswith("#"):
continue
fields = line.split()
key = fields[0]
if key not in allowed:
continue
if len(fields) != 2:
raise ValueError(f"unsupported color syntax in {path}:{line_number}")
value = fields[1]
if value in {"none", "system", "background"}:
continue
result[key] = parse_color(value, key, line_number)
for required in ["foreground", "background", *(f"color{index}" for index in range(16))]:
if required not in result:
raise ValueError(f"missing required {required} in {path}")
return result
def rust_color(color: tuple[int, int, int]) -> str:
return f"Color::Rgb(0x{color[0]:02x}, 0x{color[1]:02x}, 0x{color[2]:02x})"
def optional_color(colors: dict, key: str) -> str:
return f"Some({rust_color(colors[key])})" if key in colors else "None"
def import_theme(entry, source: Path, license_cache: Path) -> tuple[dict, dict]:
theme_id, filename, display, expected_mode, upstream_override = entry
expected = EXPECTED[theme_id]
metadata = next(item for item in source["metadata"] if item["file"] == f"themes/{filename}")
if metadata.get("author") != expected.author:
raise ValueError(f"author mismatch for {theme_id}")
if metadata.get("license") not in {"MIT", "MIT/X11"}:
raise ValueError(f"unsupported license for {theme_id}")
mode = "dark" if metadata.get("is_dark") is True else "light"
if mode != expected_mode:
raise ValueError(f"mode mismatch for {theme_id}")
source_path = source["root"] / "themes" / filename
content = source_path.read_bytes()
if hashlib.sha256(content).hexdigest() != expected.source_sha256:
raise ValueError(f"source hash mismatch for {theme_id}")
colors = parse_conf(source_path)
upstream = upstream_override or metadata.get("upstream")
if not upstream:
raise ValueError(f"missing upstream for {theme_id}")
repo = LICENSE_REPOS[theme_id]
license_name = repo.replace("/", "__")
license_path = license_cache / f"{license_name}.txt"
license_meta_path = license_cache / f"{license_name}.json"
if not license_path.is_file() or not license_meta_path.is_file():
raise ValueError(f"missing upstream license cache for {theme_id}: {repo}")
license_meta = json.loads(license_meta_path.read_text())
upstream_license = license_meta.get("license", {})
if license_meta.get("repo") != expected.upstream_repo.removeprefix("https://github.com/"):
raise ValueError(f"upstream repository mismatch for {theme_id}")
if license_meta.get("commit") != expected.upstream_commit:
raise ValueError(f"upstream license commit mismatch for {theme_id}")
expected_spdx = None if theme_id.startswith("solarized-") else expected.upstream_license
if upstream_license.get("spdx_id") != expected_spdx:
raise ValueError(f"upstream license mismatch for {theme_id}")
notice = license_path.read_bytes()
if not notice.strip() or hashlib.sha256(notice).hexdigest() != expected.notice_sha256:
raise ValueError(f"upstream notice hash mismatch for {theme_id}")
manifest = {
"id": theme_id,
"display_name": display,
"mode": mode,
"origin": "kitty",
"author": metadata.get("author"),
"license": MIT_LICENSE,
"source": {
"repository": "https://github.com/kovidgoyal/kitty-themes",
"commit": KITTY_COMMIT,
"file": f"themes/{filename}",
"sha256": hashlib.sha256(content).hexdigest(),
},
"upstream": {
"url": upstream,
"license_repository": f"https://github.com/{repo}",
"license_commit": license_meta["commit"],
"license": upstream_license.get("spdx_id"),
"license_file": f"LICENSES/themes/{license_name}.txt",
},
"derivation_version": 1,
}
return manifest, colors
def emit_theme(manifest: dict, colors: dict) -> str:
ansi = ",\n ".join(rust_color(colors[f"color{index}"]) for index in range(16))
panel = optional_color(colors, "tab_bar_background")
if panel == "None":
panel = optional_color(colors, "inactive_tab_background")
active = optional_color(colors, "active_border_color")
if active == "None":
active = optional_color(colors, "url_color")
return f""" ThemeDefinition {{
id: {json.dumps(manifest['id'], ensure_ascii=False)},
display_name: {json.dumps(manifest['display_name'], ensure_ascii=False)},
mode: ThemeMode::{manifest['mode'].title()},
origin: ThemeOrigin::Kitty,
native_palette: None,
seed: Some(ThemeSeed {{
background: {rust_color(colors['background'])},
text: {rust_color(colors['foreground'])},
panel: {panel},
muted: {optional_color(colors, 'inactive_tab_foreground')},
active: {active},
selection_background: {optional_color(colors, 'selection_background')},
selection_text: {optional_color(colors, 'selection_foreground')},
ansi: [{ansi}],
}}),
}},"""
def write_if_changed(path: Path, content: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
if path.is_file() and path.read_text() == content:
return
path.write_text(content)
def verify_source_commit(source: Path) -> None:
result = subprocess.run(
["git", "-C", str(source), "rev-parse", "HEAD"],
check=True,
capture_output=True,
text=True,
)
if result.stdout.strip() != KITTY_COMMIT:
raise ValueError(f"kitty checkout HEAD must be pinned {KITTY_COMMIT}")
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("source", type=Path, help="Local kitty-themes checkout")
parser.add_argument("license_cache", type=Path)
parser.add_argument("--output", type=Path, default=Path.cwd())
args = parser.parse_args()
verify_source_commit(args.source)
source = {"root": args.source, "metadata": json.loads((args.source / "themes.json").read_text())}
imported = [import_theme(entry, source, args.license_cache) for entry in THEMES]
manifest = [item[0] for item in imported]
seeds = ",\n\n".join(emit_theme(item[0], item[1]).removesuffix(",") for item in imported)
write_if_changed(args.output / "themes/manifest.json", json.dumps(manifest, ensure_ascii=False, indent=2) + "\n")
write_if_changed(args.output / "src/ui/themes_data.rs", "// Generated by tools/import_themes.py; do not edit manually.\n\n&[\n" + seeds + ",\n]\n")
for repo in sorted(set(LICENSE_REPOS.values())):
name = repo.replace("/", "__")
text = (args.license_cache / f"{name}.txt").read_text()
write_if_changed(args.output / f"LICENSES/themes/{name}.txt", text)
print(f"Imported {len(manifest)} themes at pinned {KITTY_COMMIT}")
if __name__ == "__main__":
main()