"""Read a delivered example with independent format readers. Used only by verify-deliveries.mjs.""" import base64 import hashlib from html.parser import HTMLParser import json from pathlib import Path import sys from urllib.parse import parse_qs, urlsplit import xml.etree.ElementTree as ET from zipfile import ZipFile import zlib from PIL import Image import tinycss2 def digest(data): return hashlib.sha256(data).hexdigest() class Preview(HTMLParser): def __init__(self): super().__init__() self.tags = set() self.assets = [] def handle_starttag(self, tag, attrs): self.tags.add(tag) attrs = dict(attrs) key = "href" if tag == "link" else "src" if tag in {"link", "script", "img"} and attrs.get(key): self.assets.append(attrs[key]) def read_image(file, expected): with Image.open(file) as image: assert image.size == tuple(expected["size"]), (file, image.size, expected["size"]) frames = expected["frames"] assert image.n_frames == len(frames), (file, image.n_frames, len(frames)) if "loop" in expected: # A GIF that plays once omits the optional Netscape loop extension. assert image.info.get("loop") == expected["loop"], (file, image.info.get("loop"), expected) for index, frame in enumerate(frames): image.seek(index) if "ms" in frame: assert abs(image.info["duration"] - frame["ms"]) < 0.001, (file, index, image.info["duration"], frame["ms"]) rgba = image.convert("RGBA") if frame.get("scale", 1) > 1: scale = frame["scale"] small = rgba.resize((rgba.width // scale, rgba.height // scale), Image.Resampling.NEAREST) assert small.resize(rgba.size, Image.Resampling.NEAREST).tobytes() == rgba.tobytes(), (file, index, "nearest-neighbour enlargement") rgba = small if "rgba" in frame: assert digest(rgba.tobytes()) == frame["rgba"], (file, index, "decoded pixels differ") if "envelope" in expected: assert json.loads(image.info["pixelbolt-recipe"]) == expected["envelope"], file def read_atlas(file): atlas = json.loads(file.read_text(encoding="utf-8")) with Image.open(file.parent / atlas["meta"]["image"]) as image: sheet = image.convert("RGBA") assert sheet.size == (atlas["meta"]["size"]["w"], atlas["meta"]["size"]["h"]), file for name, entry in atlas["frames"].items(): rect = entry["frame"] x, y, w, h = (rect[k] for k in ("x", "y", "w", "h")) assert x >= 0 and y >= 0 and x + w <= sheet.width and y + h <= sheet.height, (file, name) region = sheet.crop((x, y, x + w, y + h)) with Image.open(file.parent / "frames" / (name + ".png")) as frame: expected = frame.convert("RGBA") if entry["trimmed"]: box = entry["spriteSourceSize"] assert (w, h) == (box["w"], box["h"]), (file, name) full = Image.new("RGBA", expected.size) full.paste(region, (box["x"], box["y"])) region = full assert region.size == expected.size and region.tobytes() == expected.tobytes(), (file, name, "atlas rectangle") def read_css(text, file): def visit(rules): for rule in rules: assert rule.type in {"at-rule", "qualified-rule"}, (file, rule) if rule.type == "at-rule" and rule.content is not None: if rule.lower_at_keyword in {"media", "keyframes", "supports"}: visit(tinycss2.parse_rule_list(rule.content, skip_comments=True, skip_whitespace=True)) elif rule.type == "qualified-rule": declarations = tinycss2.parse_declaration_list(rule.content, skip_comments=True, skip_whitespace=True) assert all(d.type == "declaration" for d in declarations), (file, declarations) for decl in declarations: for token in decl.value: if token.type == "function" and token.lower_name == "url": asset = tinycss2.serialize(token.arguments).strip().strip("\\\"'") if not urlsplit(asset).scheme: assert (file.parent / asset).is_file(), (file, asset) rules = tinycss2.parse_stylesheet(text, skip_comments=True, skip_whitespace=True) assert rules, file visit(rules) def main(): if not __debug__: raise RuntimeError('Run the independent readers with Python assertions enabled') plan_file = Path(sys.argv[1]) root = plan_file.parent plan = json.loads(plan_file.read_text(encoding="utf-8")) expected = plan["files"] actual = {f.relative_to(root).as_posix() for f in root.rglob("*") if f.is_file() and f != plan_file} assert actual == set(expected), (actual - set(expected), set(expected) - actual) for name, kind in expected.items(): file = root / name if kind == "image": read_image(file, plan["images"][name]) elif kind == "zip": with ZipFile(file) as archive: members = plan["zips"][name] assert sorted(archive.namelist()) == sorted(members), file for member, sha in members.items(): assert digest(archive.read(member)) == sha, (file, member) elif kind == "link": fragment = parse_qs(urlsplit(file.read_text()).fragment, strict_parsing=True) packed = fragment["r"][0] body = zlib.decompress(base64.urlsafe_b64decode(packed + "=" * (-len(packed) % 4)), -15) assert json.loads(body) == plan["source"] and fragment["v"] == [plan["version"]], file elif kind == "html": page = Preview() page.feed(file.read_text(encoding="utf-8")) page.close() assert "html" in page.tags and page.tags & {"img", "canvas"}, file for asset in page.assets: if not urlsplit(asset).scheme and not asset.startswith("#"): assert (file.parent / asset).is_file(), (file, asset) elif kind == "css": read_css(file.read_text(encoding="utf-8"), file) elif kind == "json": assert isinstance(json.loads(file.read_text(encoding="utf-8")), (dict, list)), file if name.endswith(".atlas.json"): read_atlas(file) elif kind in {"tmx", "tsx"}: doc = ET.parse(file).getroot() assert doc.tag == {"tmx": "map", "tsx": "tileset"}[kind], file elif kind in {"js", "tres", "tscn", "txt"}: # JS is also parsed by Node and Godot loads each resource from its project. assert file.read_text(encoding="utf-8").strip(), file else: raise ValueError((file, kind)) if __name__ == "__main__": main()