tools/gen_registry.py now also writes src/Rosetta/Sniffs.luau: each format's sniff copied (tools/sniff_extract.py) with the top-level locals, types and load-time loops it reaches; requires outside core/ become proxies that require on first field access. 198 of 199 sniffs are copied (model/fbx reads Binary.MAGIC at load time: its module sniffs). Registry entries gain sniff (0 copy, 1 copy reaching a codec / container, 2 module) and variant (the module has variant(r)). init.luau detect: the extension's formats first, then by sniff cost and registry order; a sniff runs only while its cap (1, or LATE) could still win, ties to registry order, so results equal the eager path. F.detect loads the winner only when it has variant(). tests/detect.luau: every copied sniff against its module's on samples of every fixture module (tools/fixtures/detect.py), scores within 0..1, and F.detect against the eager reference with no name, the right / wrong / unknown extension and per category. Outside init / Registry / gen_registry: tools/fixtures.py (LAST generators run after the others and rerun when their outputs change), tools/lint_rules.py (Sniffs is api layer, skipped by DUP), docs/STYLE.md and docs/API.md notes, build/ regenerated.
154 lines
6.8 KiB
Python
154 lines
6.8 KiB
Python
#!/usr/bin/env python3
|
|
# Test fixtures (python3 -I tools/fixtures.py [filter] [--force] [--list]): runs every generator in tools/fixtures/*.py
|
|
# (or those whose name contains filter). Each writes Luau modules into tests/gen/ (gitignored) that return the fixture
|
|
# data as string literals, because the luau CLI has no file I/O; the LuaJIT test build copies them as they are, so
|
|
# both runtimes read the same bytes through the same require("@tests/gen/<name>").
|
|
#
|
|
# A generator is tools/fixtures/<name>.py with:
|
|
# INPUTS = ["tests/fixtures/pngsuite", ...] # optional: files / dirs whose change triggers a rebuild
|
|
# def generate(ctx): ... # ctx.emit("png_suite", value), ctx.nix("imagemagick", [...]), ...
|
|
# A generator is skipped while all its outputs are newer than itself and its INPUTS (--force reruns it).
|
|
# LAST = True runs it after the others; it also reruns when any other generator's output changed (it reads them)
|
|
#
|
|
# ctx.emit(name, value): writes tests/gen/<name>.luau returning value. Python values map to Luau: bytes -> string
|
|
# literal (any bytes), str -> string literal, int / float / bool, list / tuple -> array, dict -> table (string keys
|
|
# become fields). None is not allowed (nil cannot sit in a table): leave the key out.
|
|
# ctx.nix(packages, argv, input=None) -> stdout bytes: runs argv under `nix shell nixpkgs#<pkg>...` (reference tools:
|
|
# ffmpeg, imagemagick, libwebp, flac, lame, opus-tools, ...). ctx.python(packages, code, input=None): a nix python3
|
|
# with the given python packages (pypng, pillow, fonttools, msgpack, cbor2, ...).
|
|
# ctx.rng(seed): a random.Random. ctx.root / ctx.gen: paths. ctx.read(relpath) -> bytes from the repo.
|
|
import importlib.util, os, random, subprocess, sys
|
|
|
|
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
GEN = os.path.join(ROOT, "tests", "gen")
|
|
GENERATORS = os.path.join(ROOT, "tools", "fixtures")
|
|
|
|
ESC = [chr(c) if 32 <= c < 127 and c not in (34, 92) else "\\x%02x" % c for c in range(256)]
|
|
|
|
|
|
def lit(b):
|
|
"""bytes / str -> a Luau (and Lua 5.1 / LuaJIT) string literal"""
|
|
if isinstance(b, str):
|
|
b = b.encode()
|
|
return '"' + "".join(map(ESC.__getitem__, b)) + '"'
|
|
|
|
|
|
def luau(v, indent=1):
|
|
if isinstance(v, bool):
|
|
return "true" if v else "false"
|
|
if isinstance(v, (bytes, bytearray, str)):
|
|
return lit(bytes(v) if not isinstance(v, str) else v)
|
|
if isinstance(v, int):
|
|
return str(v)
|
|
if isinstance(v, float):
|
|
if v != v:
|
|
return "(0/0)"
|
|
if v in (float("inf"), float("-inf")):
|
|
return "math.huge" if v > 0 else "-math.huge"
|
|
return repr(v)
|
|
pad = "\t" * indent
|
|
if isinstance(v, (list, tuple)):
|
|
if not v:
|
|
return "{}"
|
|
return "{\n" + "".join("%s%s,\n" % (pad, luau(x, indent + 1)) for x in v) + "\t" * (indent - 1) + "}"
|
|
if isinstance(v, dict):
|
|
if not v:
|
|
return "{}"
|
|
out = []
|
|
for k, x in v.items():
|
|
if isinstance(k, str) and k.isidentifier() and k not in LUA_KEYWORDS:
|
|
key = k
|
|
else:
|
|
key = "[%s]" % luau(k)
|
|
out.append("%s%s = %s,\n" % (pad, key, luau(x, indent + 1)))
|
|
return "{\n" + "".join(out) + "\t" * (indent - 1) + "}"
|
|
raise TypeError("fixtures: cannot emit %r" % type(v))
|
|
|
|
|
|
LUA_KEYWORDS = {"and", "break", "do", "else", "elseif", "end", "false", "for", "function", "if", "in", "local", "nil",
|
|
"not", "or", "repeat", "return", "then", "true", "until", "while", "continue"}
|
|
|
|
|
|
class Ctx:
|
|
def __init__(self, name):
|
|
self.name = name
|
|
self.root = ROOT
|
|
self.gen = GEN
|
|
self.outputs = []
|
|
|
|
def emit(self, name, value):
|
|
path = os.path.join(GEN, name + ".luau")
|
|
with open(path, "w") as f:
|
|
f.write("-- generated by tools/fixtures.py (tools/fixtures/%s.py) - do not edit\nreturn %s\n" % (self.name, luau(value)))
|
|
self.outputs.append(path)
|
|
|
|
def rng(self, seed):
|
|
return random.Random(seed)
|
|
|
|
def read(self, rel):
|
|
with open(os.path.join(ROOT, rel), "rb") as f:
|
|
return f.read()
|
|
|
|
def nix(self, packages, argv, input=None):
|
|
if isinstance(packages, str):
|
|
packages = [packages]
|
|
cmd = ["nix", "shell"] + ["nixpkgs#" + p for p in packages] + ["-c"] + list(argv)
|
|
return subprocess.run(cmd, input=input, capture_output=True, check=True).stdout
|
|
|
|
def python(self, packages, code, input=None):
|
|
expr = "with import <nixpkgs> {}; python3.withPackages (p: [%s])" % " ".join("p." + p for p in packages)
|
|
cmd = ["nix", "shell", "--impure", "--expr", expr, "-c", "python3", "-I", "-c", code]
|
|
return subprocess.run(cmd, input=input, capture_output=True, check=True).stdout
|
|
|
|
|
|
def load(path):
|
|
spec = importlib.util.spec_from_file_location("fixture_" + os.path.basename(path)[:-3], path)
|
|
mod = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(mod)
|
|
return mod
|
|
|
|
|
|
def mtime(p):
|
|
if os.path.isdir(p):
|
|
return max([os.path.getmtime(p)] + [mtime(os.path.join(p, f)) for f in os.listdir(p)])
|
|
return os.path.getmtime(p) if os.path.exists(p) else float("inf")
|
|
|
|
|
|
def main():
|
|
args = [a for a in sys.argv[1:] if not a.startswith("--")]
|
|
force = "--force" in sys.argv
|
|
os.makedirs(GEN, exist_ok=True)
|
|
stamps = os.path.join(GEN, ".stamps")
|
|
os.makedirs(stamps, exist_ok=True)
|
|
names = sorted(f[:-3] for f in os.listdir(GENERATORS) if f.endswith(".py") and not f.startswith("_"))
|
|
if "--list" in sys.argv:
|
|
print("\n".join(names))
|
|
return
|
|
mods = {name: load(os.path.join(GENERATORS, name + ".py")) for name in names}
|
|
names.sort(key=lambda n: bool(getattr(mods[n], "LAST", False)))
|
|
for name in names:
|
|
if args and not any(a in name for a in args):
|
|
continue
|
|
path = os.path.join(GENERATORS, name + ".py")
|
|
mod = mods[name]
|
|
inputs = [path, os.path.abspath(__file__)] + [os.path.join(ROOT, p) for p in getattr(mod, "INPUTS", [])]
|
|
if getattr(mod, "LAST", False):
|
|
inputs += [os.path.join(stamps, n) for n in names if n != name and not getattr(mods[n], "LAST", False)]
|
|
stamp = os.path.join(stamps, name)
|
|
if not force and os.path.exists(stamp):
|
|
outs = open(stamp).read().split("\n")
|
|
newest = max(mtime(p) for p in inputs)
|
|
if all(os.path.exists(o) and os.path.getmtime(o) > newest for o in outs if o):
|
|
print("fixtures: %s up to date" % name)
|
|
continue
|
|
ctx = Ctx(name)
|
|
mod.generate(ctx)
|
|
with open(stamp, "w") as f:
|
|
f.write("\n".join(ctx.outputs))
|
|
size = sum(os.path.getsize(o) for o in ctx.outputs)
|
|
print("fixtures: %s -> %s (%.1f MB)" % (name, ", ".join(os.path.relpath(o, ROOT) for o in ctx.outputs), size / 1e6))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|