295 lines
13 KiB
Python
295 lines
13 KiB
Python
#!/usr/bin/env python3
|
|
# Registry generator (python3 -I tools/gen_registry.py [--check]): scans the format folders
|
|
# src/Rosetta/<category>/<fmt>/init.luau and writes
|
|
# src/Rosetta/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
|
|
# src/Rosetta/Sniffs.luau each format's sniff, copied with what it reaches (tools/sniff_extract.py), so detection
|
|
# runs without requiring the format modules
|
|
# docs/FORMATS.md the capability matrix, from each contract's caps
|
|
# README.md the format table (read / write) and the codec + container list, between the markers
|
|
# <!-- formats:begin --> / <!-- formats:end --> and <!-- codecs:begin --> / <!-- codecs:end -->
|
|
# 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 any of them is out of date (tools/lint.sh runs this).
|
|
import os, re, sys
|
|
|
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
import sniff_extract
|
|
|
|
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
SRC = os.path.join(ROOT, "src", "Rosetta")
|
|
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
|
|
text = open(init).read()
|
|
c["sniff_cost"], c["sniff_block"], self_name = sniff_extract.extract(text, c["path"])
|
|
c["variant"] = sniff_extract.has_variant(text, self_name)
|
|
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.",
|
|
"-- sniff: where detection finds the format's sniff (tools/sniff_extract.py): 0 Sniffs.luau, 1 Sniffs.luau reaching a",
|
|
"-- codec / container on first call, 2 the format module. variant: the module has variant(r).",
|
|
"export type Entry = {",
|
|
"\tname: string,",
|
|
"\tcategory: string,",
|
|
"\tpath: string,",
|
|
"\textensions: { string },",
|
|
"\tmime: { string },",
|
|
"\tdeps: { string },",
|
|
"\tcaps: { [string]: any },",
|
|
"\tsniff: number,",
|
|
"\tvariant: boolean?,",
|
|
"\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\tsniff = %d," % c["sniff_cost"],
|
|
] + (["\t\tvariant = true,"] if c["variant"] else []) + [
|
|
"\t\tload = function()",
|
|
'\t\t\treturn require("@rosetta/%s")' % c["path"],
|
|
"\t\tend,",
|
|
"\t},",
|
|
]
|
|
out += ["}", "", "return list", ""]
|
|
return "\n".join(out)
|
|
|
|
|
|
def sniffs(formats):
|
|
out = [
|
|
"--!strict",
|
|
"--!optimize 2",
|
|
"-- Sniffs: GENERATED by tools/gen_registry.py from the format folders - do not edit.",
|
|
"-- Each format's sniff (format path -> sniff(r)), copied from its init.luau with the top-level locals and types it",
|
|
"-- reaches (tools/sniff_extract.py), so detection requires no format module. Requires outside core/ are proxies that",
|
|
"-- require on first use. Formats whose sniff needs their module (Registry sniff = 2) are not here.",
|
|
"local S: { [string]: (any) -> number } = {}",
|
|
"",
|
|
"local function lazy(load: () -> any): any",
|
|
"\tlocal proxy = {}",
|
|
"\treturn setmetatable(proxy, {",
|
|
"\t\t__index = function(_, k: any): any",
|
|
"\t\t\tlocal m = load()",
|
|
"\t\t\tsetmetatable(proxy, { __index = m })",
|
|
"\t\t\treturn m[k]",
|
|
"\t\tend,",
|
|
"\t})",
|
|
"end",
|
|
"",
|
|
] + sniff_extract.shared_lines()
|
|
for c in formats:
|
|
if c["sniff_block"] is None:
|
|
continue
|
|
out.append("do -- %s" % c["path"])
|
|
out += c["sniff_block"]
|
|
out += ["end", ""]
|
|
out += ["return S", ""]
|
|
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 3, shared by formats; not loadable on their own), by domain:", ""]
|
|
cdir = os.path.join(SRC, "codecs")
|
|
for domain in sorted(os.listdir(cdir)) if os.path.isdir(cdir) else []:
|
|
ddir = os.path.join(cdir, domain)
|
|
if not os.path.isdir(ddir):
|
|
continue
|
|
lines.append("- **%s**" % domain)
|
|
for name in sorted(os.listdir(ddir)):
|
|
p = os.path.join(ddir, name)
|
|
init = os.path.join(p, "init.luau") if os.path.isdir(p) else p
|
|
if os.path.isfile(init) and init.endswith(".luau"):
|
|
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)
|
|
|
|
|
|
LABELS = {"image": "Images", "audio": "Audio", "video": "Video", "model": "3D models", "cad": "CAD", "font": "Fonts",
|
|
"archive": "Archives", "data": "Data", "vector": "Vector graphics and tile maps", "layered": "Layered images",
|
|
"subtitle": "Subtitles", "music": "Music", "playlist": "Playlists"}
|
|
|
|
|
|
def module_list(rel):
|
|
"""[(name, file)] of the modules directly under src/Rosetta/<rel> (Foo.luau or Foo/init.luau)"""
|
|
d = os.path.join(SRC, rel)
|
|
out = []
|
|
for name in sorted(os.listdir(d)) if os.path.isdir(d) else []:
|
|
p = os.path.join(d, name)
|
|
f = os.path.join(p, "init.luau") if os.path.isdir(p) else p
|
|
if os.path.isfile(f) and f.endswith(".luau"):
|
|
out.append((name[:-5] if name.endswith(".luau") else name, f))
|
|
return out
|
|
|
|
|
|
def readme_formats(formats):
|
|
by = {}
|
|
for c in formats:
|
|
by.setdefault(c["folder_category"], []).append(c)
|
|
lines = ["%d formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md)"
|
|
% len(formats), "adds each format's capabilities.", "",
|
|
"| Category | Format | Extensions | Read | Write |", "|---|---|---|---|---|"]
|
|
for cat in CATEGORIES:
|
|
for c in by.get(cat, []):
|
|
cd = dict(caps_dict(c["caps"]))
|
|
lines.append("| %s | %s | %s | %s | %s |" % (
|
|
LABELS[cat], 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 "-"))
|
|
return "\n".join(lines)
|
|
|
|
|
|
def readme_codecs():
|
|
lines = ["Shared by the formats, not loadable on their own (`src/Rosetta/codecs/<domain>/`, `src/Rosetta/containers/`;",
|
|
"[docs/FORMATS.md](docs/FORMATS.md) describes each). The bundles reach them as `F._internal(\"codecs/video/Mpeg1\")`.",
|
|
"", "| Domain | Modules |", "|---|---|"]
|
|
cdir = os.path.join(SRC, "codecs")
|
|
for domain in sorted(os.listdir(cdir)):
|
|
if os.path.isdir(os.path.join(cdir, domain)):
|
|
lines.append("| %s | %s |" % (domain, ", ".join(n for n, _ in module_list("codecs/" + domain))))
|
|
lines.append("| containers | %s |" % ", ".join(n for n, _ in module_list("containers")))
|
|
return "\n".join(lines)
|
|
|
|
|
|
def readme(formats, path):
|
|
"""README.md with its generated sections replaced"""
|
|
text = open(path, encoding="utf-8").read()
|
|
for tag, body in (("formats", readme_formats(formats)), ("codecs", readme_codecs())):
|
|
begin, end = "<!-- %s:begin -->" % tag, "<!-- %s:end -->" % tag
|
|
m = re.search(re.escape(begin) + r".*?" + re.escape(end), text, re.S)
|
|
if not m:
|
|
sys.exit("gen_registry: README.md has no %s ... %s section" % (begin, end))
|
|
text = text[:m.start()] + begin + "\n" + body + "\n" + end + text[m.end():]
|
|
return text
|
|
|
|
|
|
def main():
|
|
formats = scan()
|
|
readme_path = os.path.join(ROOT, "README.md")
|
|
outputs = {
|
|
os.path.join(SRC, "Registry.luau"): registry(formats),
|
|
os.path.join(SRC, "Sniffs.luau"): sniffs(formats),
|
|
os.path.join(ROOT, "docs", "FORMATS.md"): formats_md(formats),
|
|
readme_path: readme(formats, readme_path),
|
|
}
|
|
check = "--check" in sys.argv
|
|
stale = []
|
|
for path, text in outputs.items():
|
|
old = open(path, encoding="utf-8").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", encoding="utf-8") 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/Rosetta/Registry.luau, Sniffs.luau, docs/FORMATS.md, README.md%s" % (
|
|
len(formats), "" if stale else " (unchanged)"))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|