182 lines
6.9 KiB
Python
182 lines
6.9 KiB
Python
#!/usr/bin/env python3
|
|
# Registry generator (python3 -I tools/gen_registry.py [--check]): scans the format folders
|
|
# src/Formats/<category>/<fmt>/init.luau and writes
|
|
# src/Formats/Registry.luau a static list (Roblox has no dynamic require): each format's contract metadata, copied
|
|
# from its init.luau, and a load() that requires the module on first use
|
|
# docs/FORMATS.md the capability matrix, from each contract's caps
|
|
# The metadata fields must be one-line literals in the contract table (tools/lint.sh CONTRACT checks the shape):
|
|
# name = "png", category = "image", extensions = { ... }, mime = { ... }, deps = { ... }, caps = { ... },
|
|
# --check: exit 1 when either file is out of date (tools/lint.sh runs this).
|
|
import os, re, sys
|
|
|
|
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
SRC = os.path.join(ROOT, "src", "Formats")
|
|
CATEGORIES = ["image", "audio", "video", "model", "cad", "font", "archive", "data", "vector", "layered", "subtitle",
|
|
"music", "playlist"]
|
|
FIELDS = ["name", "category", "extensions", "mime", "deps", "caps"]
|
|
FIELD = re.compile(r"^\t(name|category|extensions|mime|deps|caps) = (.*),\s*(--.*)?$")
|
|
|
|
|
|
def contract(path):
|
|
"""The one-line contract fields of a format's init.luau: {field: luau literal text}."""
|
|
out = {}
|
|
with open(path) as f:
|
|
for line in f:
|
|
m = FIELD.match(line.rstrip("\n"))
|
|
if m and m.group(1) not in out:
|
|
out[m.group(1)] = m.group(2).strip()
|
|
return out
|
|
|
|
|
|
def lua_strings(lit):
|
|
return re.findall(r'"([^"]*)"', lit)
|
|
|
|
|
|
def scan():
|
|
formats = []
|
|
for cat in CATEGORIES:
|
|
d = os.path.join(SRC, cat)
|
|
if not os.path.isdir(d):
|
|
continue
|
|
for fmt in sorted(os.listdir(d)):
|
|
init = os.path.join(d, fmt, "init.luau")
|
|
if not os.path.isfile(init):
|
|
continue
|
|
c = contract(init)
|
|
missing = [k for k in FIELDS if k not in c]
|
|
if missing:
|
|
sys.exit("gen_registry: %s/%s/init.luau: missing contract fields %s" % (cat, fmt, ", ".join(missing)))
|
|
c["path"] = cat + "/" + fmt
|
|
c["folder_category"] = cat
|
|
formats.append(c)
|
|
return formats
|
|
|
|
|
|
def registry(formats):
|
|
out = [
|
|
"--!strict",
|
|
"-- Registry: GENERATED by tools/gen_registry.py from the format folders - do not edit.",
|
|
"-- One entry per format: the contract metadata (copied from its init.luau) and load(), which requires the format",
|
|
"-- module on first use (a static require, as Roblox needs). Order: category, then name.",
|
|
"export type Entry = {",
|
|
"\tname: string,",
|
|
"\tcategory: string,",
|
|
"\tpath: string,",
|
|
"\textensions: { string },",
|
|
"\tmime: { string },",
|
|
"\tdeps: { string },",
|
|
"\tcaps: { [string]: any },",
|
|
"\tload: () -> any,",
|
|
"}",
|
|
"",
|
|
"local list: { Entry } = {",
|
|
]
|
|
for c in formats:
|
|
out += [
|
|
"\t{",
|
|
"\t\tname = %s," % c["name"],
|
|
"\t\tcategory = %s," % c["category"],
|
|
'\t\tpath = "%s",' % c["path"],
|
|
"\t\textensions = %s," % c["extensions"],
|
|
"\t\tmime = %s," % c["mime"],
|
|
"\t\tdeps = %s," % c["deps"],
|
|
"\t\tcaps = %s," % c["caps"],
|
|
"\t\tload = function()",
|
|
'\t\t\treturn require("@formats/%s")' % c["path"],
|
|
"\t\tend,",
|
|
"\t},",
|
|
]
|
|
out += ["}", "", "return list", ""]
|
|
return "\n".join(out)
|
|
|
|
|
|
def caps_dict(lit):
|
|
"""{ decode = true, depths = { 8 } } -> ordered [(key, text)] at the top level."""
|
|
body = lit.strip()[1:-1]
|
|
items, depth, cur = [], 0, ""
|
|
for ch in body:
|
|
if ch == "{":
|
|
depth += 1
|
|
elif ch == "}":
|
|
depth -= 1
|
|
if ch == "," and depth == 0:
|
|
items.append(cur)
|
|
cur = ""
|
|
else:
|
|
cur += ch
|
|
if cur.strip():
|
|
items.append(cur)
|
|
out = []
|
|
for it in items:
|
|
if "=" in it:
|
|
k, v = it.split("=", 1)
|
|
out.append((k.strip(), v.strip()))
|
|
return out
|
|
|
|
|
|
def formats_md(formats):
|
|
lines = [
|
|
"# Formats",
|
|
"",
|
|
"GENERATED by `tools/gen_registry.py` from each format's contract (`caps`) - do not edit. Every format listed here",
|
|
"is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build) by `bash tools/test.sh`.",
|
|
"",
|
|
"| Category | Format | Extensions | Read | Write | Capabilities | Test |",
|
|
"|---|---|---|---|---|---|---|",
|
|
]
|
|
for c in formats:
|
|
caps = caps_dict(c["caps"])
|
|
cd = dict(caps)
|
|
other = ", ".join("%s: %s" % (k, v.replace("{ ", "").replace(" }", "")) for k, v in caps if k not in ("decode", "encode"))
|
|
test = "tests/%s/%s.luau" % (c["folder_category"], lua_strings(c["name"])[0])
|
|
has = os.path.isfile(os.path.join(ROOT, test))
|
|
lines.append("| %s | %s | %s | %s | %s | %s | %s |" % (
|
|
c["folder_category"], lua_strings(c["name"])[0], " ".join("." + e for e in lua_strings(c["extensions"])),
|
|
"yes" if cd.get("decode") == "true" else "-", "yes" if cd.get("encode") == "true" else "-",
|
|
other or "", "`%s`" % test if has else "**missing**"))
|
|
lines += ["", "Codecs (layer 1, shared by formats; not loadable on their own):", ""]
|
|
cdir = os.path.join(SRC, "codecs")
|
|
for name in sorted(os.listdir(cdir)) if os.path.isdir(cdir) else []:
|
|
p = os.path.join(cdir, name)
|
|
init = os.path.join(p, "init.luau") if os.path.isdir(p) else p
|
|
if os.path.isfile(init):
|
|
first = ""
|
|
with open(init) as f:
|
|
for line in f:
|
|
if line.startswith("-- codecs/"):
|
|
first = line[3:].strip()
|
|
break
|
|
lines.append("- %s" % (first or name))
|
|
lines.append("")
|
|
return "\n".join(lines)
|
|
|
|
|
|
def main():
|
|
formats = scan()
|
|
outputs = {
|
|
os.path.join(SRC, "Registry.luau"): registry(formats),
|
|
os.path.join(ROOT, "docs", "FORMATS.md"): formats_md(formats),
|
|
}
|
|
check = "--check" in sys.argv
|
|
stale = []
|
|
for path, text in outputs.items():
|
|
old = open(path).read() if os.path.exists(path) else None
|
|
if old != text:
|
|
stale.append(os.path.relpath(path, ROOT))
|
|
if not check:
|
|
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
with open(path, "w") as f:
|
|
f.write(text)
|
|
if check:
|
|
if stale:
|
|
print("gen_registry: out of date: %s (run python3 -I tools/gen_registry.py)" % ", ".join(stale))
|
|
sys.exit(1)
|
|
print("gen_registry: up to date (%d formats)" % len(formats))
|
|
else:
|
|
print("gen_registry: %d formats -> src/Formats/Registry.luau, docs/FORMATS.md%s" % (
|
|
len(formats), "" if stale else " (unchanged)"))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|