149 lines
6.4 KiB
Python
149 lines
6.4 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).
|
|
#
|
|
# 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
|
|
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 = load(path)
|
|
inputs = [path, os.path.abspath(__file__)] + [os.path.join(ROOT, p) for p in getattr(mod, "INPUTS", [])]
|
|
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()
|