Files
scadaproj/ZB.MOM.WW.Theme/build/export-web-assets.py
T

281 lines
11 KiB
Python

#!/usr/bin/env python3
"""Export immutable Technical-Light web assets from a reviewed Theme nupkg.
The CSS reader handles the canonical, top-level :root declaration block, not an
arbitrary CSS cascade. Token values (including var() references) remain raw;
consumers own platform-specific resolution. Source revision/tag are explicit
caller-supplied provenance; the release workflow must establish their truth.
"""
from __future__ import annotations
import argparse
import hashlib
import io
import json
import os
from pathlib import Path
import re
import tempfile
import xml.etree.ElementTree as ET
import zipfile
PACKAGE_ID = "ZB.MOM.WW.Theme"
ASSET_PATHS = (
"css/theme.css", "css/layout.css",
"fonts/ibm-plex-sans-400.woff2", "fonts/ibm-plex-sans-600.woff2",
"fonts/ibm-plex-mono-500.woff2",
)
REQUIRED_TOKENS = frozenset({
"--paper", "--card", "--ink", "--ink-soft", "--ink-faint", "--rule",
"--accent", "--accent-deep", "--accent-tint", "--accent-border", "--accent-focus", "--on-accent",
"--ok-ink", "--warn-ink", "--bad-ink", "--idle-ink",
"--ok-bg", "--warn-bg", "--bad-bg", "--idle-bg",
"--info-ink", "--info-bg", "--info-border", "--active-bg", "--sans", "--mono",
})
def _without_comments(css: str) -> str:
"""Remove real comments without interpreting quoted text as CSS syntax."""
result = []
quote = None
index = 0
while index < len(css):
char = css[index]
if char == "\\":
if index + 1 == len(css):
raise ValueError("Malformed CSS: dangling escape")
result.extend(css[index:index + 2])
index += 2
continue
if quote:
result.append(char)
if char == quote:
quote = None
elif char in "\"'":
quote = char
result.append(char)
elif css.startswith("/*", index):
end = css.find("*/", index + 2)
if end < 0:
raise ValueError("Malformed CSS: unterminated comment")
result.append(" ")
index = end + 2
continue
else:
result.append(char)
index += 1
if quote:
raise ValueError("Malformed CSS: unterminated quoted value")
return "".join(result)
def _canonical_root(css: str) -> str:
"""Locate exactly one top-level :root, rejecting unbalanced CSS structure."""
stack = []
quote = None
escaped = False
header_start = 0
root_start = None
blocks = []
pairs = {"}": "{", ")": "(", "]": "["}
for index, char in enumerate(css):
if escaped:
escaped = False
continue
if char == "\\":
escaped = True
continue
if quote:
if char == quote:
quote = None
continue
if char in "\"'":
quote = char
elif char in "{([":
if char == "{" and not stack and css[header_start:index].strip() == ":root":
root_start = index + 1
stack.append(char)
elif char in "})]":
if not stack or stack.pop() != pairs[char]:
raise ValueError("Malformed CSS: mismatched delimiters")
if char == "}" and not stack:
if root_start is not None:
blocks.append(css[root_start:index])
root_start = None
header_start = index + 1
elif char == ";" and not stack:
header_start = index + 1
if stack or quote or escaped:
raise ValueError("Malformed CSS: unfinished structure")
if len(blocks) != 1:
raise ValueError("Expected exactly one canonical top-level :root block")
return blocks[0]
def parse_tokens(css_bytes: bytes) -> dict[str, str]:
"""Read every custom property in canonical :root, preserving raw values."""
try:
body = _canonical_root(_without_comments(css_bytes.decode("utf-8-sig")))
except UnicodeDecodeError as exc:
raise ValueError("Theme CSS must be UTF-8") from exc
pieces = []
start = 0
quote = None
escaped = False
stack = []
for index, char in enumerate(body):
if escaped:
escaped = False
continue
if char == "\\":
escaped = True
continue
if quote:
if char == quote:
quote = None
continue
if char in "\"'":
quote = char
elif char in "{}":
raise ValueError("Canonical :root may contain declarations only")
elif char in "([":
stack.append(char)
elif char in ")]":
if not stack or stack.pop() != {")": "(", "]": "["}[char]:
raise ValueError("Malformed token value")
elif char == ";" and not stack:
pieces.append(body[start:index])
start = index + 1
if stack or quote or escaped:
raise ValueError("Malformed token value")
pieces.append(body[start:]) # A final declaration may omit its semicolon in valid CSS.
tokens = {}
for declaration in pieces:
if not declaration.strip():
continue
name, colon, value = declaration.partition(":")
name, value = name.strip(), value.strip()
if not colon or not re.fullmatch(r"--[A-Za-z_][A-Za-z0-9_-]*", name) or not value:
raise ValueError("Malformed canonical custom-property declaration")
if name in tokens:
raise ValueError(f"Duplicate canonical token: {name}")
tokens[name] = value
missing = sorted(REQUIRED_TOKENS - tokens.keys())
if missing:
raise ValueError("Missing required semantic tokens: " + ", ".join(missing))
return tokens
def _safe_entries(archive: zipfile.ZipFile) -> list[str]:
names = []
seen = set()
for entry in archive.infolist():
name = entry.filename
parts = name.rstrip("/").split("/")
if (not name or name.startswith("/") or "\\" in name or "\x00" in name
or re.match(r"^[A-Za-z]:", name)
or any(part in ("", ".", "..") for part in parts)):
raise ValueError(f"Unsafe package entry: {name!r}")
if name in seen:
raise ValueError(f"Duplicate package entry: {name}")
seen.add(name)
names.append(name)
return names
def _metadata(archive: zipfile.ZipFile, names: list[str]) -> str:
nuspecs = [name for name in names if name.lower().endswith(".nuspec")]
if len(nuspecs) != 1:
raise ValueError("Package must contain exactly one nuspec")
try:
document = ET.fromstring(archive.read(nuspecs[0]))
except ET.ParseError as exc:
raise ValueError("Malformed nuspec XML") from exc
metadata = [node for node in document if node.tag.split("}")[-1] == "metadata"]
if document.tag.split("}")[-1] != "package" or len(metadata) != 1:
raise ValueError("Missing or ambiguous nuspec metadata")
def field(name: str) -> str:
nodes = [node for node in metadata[0] if node.tag.split("}")[-1] == name]
if len(nodes) != 1 or not (nodes[0].text or "").strip():
raise ValueError(f"Missing or ambiguous package {name}")
return nodes[0].text.strip()
if field("id") != PACKAGE_ID:
raise ValueError(f"Expected package ID {PACKAGE_ID}")
version = field("version")
if not re.fullmatch(r"[0-9]+(?:\.[0-9]+){1,3}(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?", version):
raise ValueError("Malformed package version")
return version
def _json_bytes(value: dict) -> bytes:
return (json.dumps(value, sort_keys=True, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
def export_package(package: Path, output: Path, *, source_revision: str, source_tag: str) -> Path:
"""Validate the complete input before atomically replacing a deterministic export."""
package, output = Path(package), Path(output)
# resolve() does not canonicalize case on case-insensitive APFS. Check the
# actual existing file identity as well, including hard-link aliases.
if package.resolve() == output.resolve() or (output.exists() and output.samefile(package)):
raise ValueError("Output must not replace the input package or an existing alias")
if not re.fullmatch(r"(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64})", source_revision):
raise ValueError("Source revision must be a full Git commit hash")
if not source_tag.strip() or any(char in source_tag for char in "\r\n\x00"):
raise ValueError("Source tag must be explicit (use an untagged marker where appropriate)")
package_bytes = package.read_bytes()
try:
with zipfile.ZipFile(io.BytesIO(package_bytes)) as archive:
names = _safe_entries(archive)
version = _metadata(archive, names)
payloads = {}
for name in ASSET_PATHS:
source = "staticwebassets/" + name
if source not in names:
raise ValueError(f"Missing required static asset: {source}")
payloads[name] = archive.read(source)
except zipfile.BadZipFile as exc:
raise ValueError("Input is not a valid nupkg ZIP") from exc
tokens = parse_tokens(payloads["css/theme.css"])
payloads["tokens.json"] = _json_bytes({"schemaVersion": 1, "themeVersion": version, "tokens": tokens})
manifest = {
"schemaVersion": 1, "themeVersion": version, "sourcePackage": PACKAGE_ID,
"sourcePackageSha256": hashlib.sha256(package_bytes).hexdigest(),
"sourceRevision": source_revision, "sourceTag": source_tag,
"files": {name: hashlib.sha256(data).hexdigest() for name, data in sorted(payloads.items())},
}
payloads["manifest.json"] = _json_bytes(manifest)
output.parent.mkdir(parents=True, exist_ok=True)
temporary = None
try:
with tempfile.NamedTemporaryFile(dir=output.parent, prefix=".theme-export-", suffix=".tmp", delete=False) as handle:
temporary = Path(handle.name)
with zipfile.ZipFile(temporary, "w", compression=zipfile.ZIP_STORED) as archive:
for name, data in sorted(payloads.items()):
info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0))
info.create_system = 3
info.external_attr = 0o100644 << 16
archive.writestr(info, data)
os.replace(temporary, output)
finally:
if temporary is not None:
temporary.unlink(missing_ok=True)
return output
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--package", required=True, type=Path)
parser.add_argument("--source-revision", required=True)
parser.add_argument("--source-tag", required=True)
parser.add_argument("--output", required=True, type=Path)
args = parser.parse_args()
try:
result = export_package(args.package, args.output, source_revision=args.source_revision, source_tag=args.source_tag)
except (ValueError, OSError) as exc:
parser.error(str(exc))
print(result)
if __name__ == "__main__":
main()