Files
rosetta/tools/docs_check.py
T

256 lines
11 KiB
Python

#!/usr/bin/env python3
# Docs check (python3 -I tools/docs_check.py [page ...] [--list]): turns every code snippet of docs/guide/*.md and every
# example under examples/*.luau into tests, so a snippet that drifts from the API fails `bash tools/test.sh`.
# tools/fixtures/docs.py calls generate() (test.sh runs the fixture generators first), and running this script by
# hand regenerates the tests of the named pages (all by default).
#
# Snippets. Every ```luau block of a guide page runs, under both runtimes, unless a marker comment sits on the line
# right before its fence (an HTML comment, invisible when the page is rendered):
# <!-- doc:display <why> --> shown, not run: code that needs Roblox, LÖVE or a plug-in. ```lua blocks (LÖVE / plain
# LuaJIT code) must carry it too; other languages (sh, json, ...) are never run.
# <!-- doc:files --> runs only on hosts with a file system (LuaJIT): string literals starting with "assets/
# or "out/ point into tests/gen/docs_files/, where the input generators put their files.
# <!-- doc:continue --> runs in the same scope as the snippet before it (its locals are visible).
# A snippet sees `F` (the library) and its input variables: every name it uses that ends in Bytes (a buffer) or Text
# (a string), e.g. pngBytes, srtText, looked up in the inputs the tools/fixtures/docs_*.py generators emit (each emits
# tests/gen/docs_<x>.luau = { files = { [file name] = bytes }, vars = { [variable] = file name } } through emit_inputs
# below). print is silenced. A snippet fails when it throws: write the expectations as assert(...).
#
# Examples. examples/*.luau are standalone programs (luau examples/image.luau from the repo root); each is copied into
# a test as it is.
#
# Output: tests/docs/snippets/<page>.luau and example_<name>.luau (gitignored, regenerated), plus _inputs.luau.
import os, re, sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
GUIDE = os.path.join(ROOT, "docs", "guide")
EXAMPLES = os.path.join(ROOT, "examples")
OUT = os.path.join(ROOT, "tests", "docs", "snippets")
FIXTURES = os.path.join(ROOT, "tools", "fixtures")
FILES_DIR = "tests/gen/docs_files" # relative to the repo root (the tests run from there)
MARKER = re.compile(r"^\s*<!--\s*doc:(\w+)\b(.*?)-->\s*$")
FENCE = re.compile(r"^```\s*([\w+-]*)\s*$")
VAR = re.compile(r"(?<![\w.:])([a-z]\w*(?:Bytes|Text))\b")
PATHLIT = re.compile(r"""(["'])(assets|out)/""")
LUA_LANGS = ("luau", "lua")
class DocError(Exception):
pass
def snippets(path):
"""[(line, lang, code, marker)] for the fenced blocks of a markdown file"""
lines = open(path, encoding="utf-8").read().split("\n")
out, i = [], 0
while i < len(lines):
m = FENCE.match(lines[i])
if not m or not m.group(1):
if m:
raise DocError("%s:%d: a code fence without a language" % (os.path.relpath(path, ROOT), i + 1))
i += 1
continue
lang, start = m.group(1), i + 1
prev = lines[i - 1] if i > 0 else ""
mk = MARKER.match(prev)
marker = mk.group(1) if mk else None
j = i + 1
while j < len(lines) and not lines[j].startswith("```"):
j += 1
if j >= len(lines):
raise DocError("%s:%d: unclosed code fence" % (os.path.relpath(path, ROOT), start))
out.append((start, lang, "\n".join(lines[i + 1:j]), marker))
i = j + 1
return out
def input_modules():
"""the tests/gen modules the input generators emit: docs_<x> for every tools/fixtures/docs_<x>.py"""
return sorted(f[:-3] for f in os.listdir(FIXTURES) if f.startswith("docs_") and f.endswith(".py"))
def inputs_module():
mods = input_modules()
req = "\n".join('\trequire("@tests/gen/%s"),' % m for m in mods)
return """-- tests/docs/snippets/_inputs: GENERATED by tools/docs_check.py - do not edit. The inputs the guide snippets read:
-- DocIN.pngBytes -> a fresh buffer of the file the variable names, DocIN.srtText -> a string (tools/fixtures/docs_*.py).
local mods = {
%s
}
local function find(var: string): string?
for _, m in mods do
local file = m.vars[var]
if file then
return m.files[file]
end
end
return nil
end
return setmetatable({}, {
__index = function(_, var: string): any
local data = find(var)
if data == nil then
error("docs: no input named " .. var .. " (add it to a tools/fixtures/docs_*.py generator)", 2)
end
if string.sub(var, -4) == "Text" then
return data
end
return buffer.fromstring(data)
end,
})
""" % req
def indent(code, n=2):
pad = "\t" * n
return "\n".join(pad + l if l.strip() else "" for l in code.split("\n"))
def page_test(path):
"""(test source, run count, display count) for one guide page"""
rel = os.path.relpath(path, ROOT)
name = os.path.basename(path)[:-3]
chunks = [] # { line, files, code, vars }
shown = 0
for line, lang, code, marker in snippets(path):
if lang not in LUA_LANGS:
continue
if marker not in (None, "display", "files", "continue"):
raise DocError("%s:%d: unknown marker doc:%s" % (rel, line, marker))
if marker == "display":
shown += 1
continue
if lang != "luau":
raise DocError("%s:%d: a ```lua block must be marked <!-- doc:display ... --> (only luau blocks run)" % (rel, line))
files = marker == "files"
if files:
code = PATHLIT.sub(lambda m: m.group(1) + FILES_DIR + "/" + m.group(2) + "/", code)
if marker == "continue":
if not chunks:
raise DocError("%s:%d: doc:continue on the first snippet" % (rel, line))
prev = chunks[-1]
prev["code"] += "\n-- docs line %d\n" % line + code
prev["vars"] |= set(VAR.findall(code))
prev["files"] = prev["files"] or files
continue
chunks.append({"line": line, "files": files, "code": code, "vars": set(VAR.findall(code))})
out = ["-- tests/docs/snippets/%s: GENERATED by tools/docs_check.py from %s - do not edit (edit the page)" % (name, rel),
'local F = require("@formats")',
'local DocT = require("@tests/T")',
'local DocIN = require("@tests/docs/snippets/_inputs")',
'local t = DocT.suite("docs/%s")' % name,
"local print = function(...: any) end",
"local snippets: { { line: number, files: boolean, run: () -> () } } = {}"]
for c in chunks:
decl = "".join("\t\tlocal %s = DocIN.%s\n" % (v, v) for v in sorted(c["vars"]))
out.append("snippets[#snippets + 1] = { line = %d, files = %s, run = function()\n%s%s\n\tend }"
% (c["line"], "true" if c["files"] else "false", decl, indent(c["code"])))
out.append("""local ran, skipped = 0, 0
for _, s in snippets do
if s.files and not F.host.hasFiles then
skipped += 1
else
local ok, err = xpcall(s.run, debug.traceback)
t:check(ok, "%s:" .. s.line .. ": " .. tostring(err))
ran += 1
end
end
t:note("%%d snippets ran, %%d need a file system (skipped on %%s)", ran, skipped, F.host.name)
local _ = print
t:done()
""" % rel)
return "\n".join(out), len(chunks), shown
def example_test(path):
name = os.path.basename(path)[:-5]
src = open(path, encoding="utf-8").read()
head = "-- tests/docs/snippets/example_%s: GENERATED by tools/docs_check.py from examples/%s.luau - do not edit\n" % (name, name)
return head + src
def pages(filters=()):
if not os.path.isdir(GUIDE):
return []
out = sorted(os.path.join(GUIDE, f) for f in os.listdir(GUIDE) if f.endswith(".md"))
return [p for p in out if not filters or any(f in os.path.basename(p) for f in filters)]
def examples():
if not os.path.isdir(EXAMPLES):
return []
return sorted(os.path.join(EXAMPLES, f) for f in os.listdir(EXAMPLES) if f.endswith(".luau"))
def write(path, text):
os.makedirs(os.path.dirname(path), exist_ok=True)
if os.path.exists(path) and open(path, encoding="utf-8").read() == text:
return
with open(path, "w", encoding="utf-8") as f:
f.write(text)
def generate(filters=()):
"""writes the tests; returns (output paths, runnable snippets, display-only snippets, examples)"""
os.makedirs(OUT, exist_ok=True)
os.makedirs(os.path.join(ROOT, FILES_DIR, "assets"), exist_ok=True)
os.makedirs(os.path.join(ROOT, FILES_DIR, "out"), exist_ok=True)
want, nrun, nshow = {}, 0, 0
want[os.path.join(OUT, "_inputs.luau")] = inputs_module()
for p in pages(filters):
src, r, s = page_test(p)
want[os.path.join(OUT, os.path.basename(p)[:-3] + ".luau")] = src
nrun, nshow = nrun + r, nshow + s
exs = examples() if not filters else [e for e in examples() if any(f in e for f in filters)]
for e in exs:
want[os.path.join(OUT, "example_" + os.path.basename(e))] = example_test(e)
if not filters:
for f in os.listdir(OUT):
p = os.path.join(OUT, f)
if f.endswith(".luau") and p not in want:
os.remove(p)
for p, text in want.items():
write(p, text)
return list(want), nrun, nshow, len(exs)
def emit_inputs(ctx, files, vars):
"""for tools/fixtures/docs_<x>.py: emits tests/gen/docs_<x>.luau ({ files, vars }) and writes the files into
tests/gen/docs_files/assets/ (the doc:files snippets read them there on hosts with a file system).
files: { file name: bytes }; vars: { variable name (ends in Bytes / Text): file name }"""
for v, f in vars.items():
if not VAR.fullmatch(v):
raise DocError("docs input variable %s must end in Bytes or Text" % v)
if f not in files:
raise DocError("docs input %s names a missing file %s" % (v, f))
adir = os.path.join(ctx.root, FILES_DIR, "assets")
os.makedirs(adir, exist_ok=True)
os.makedirs(os.path.join(ctx.root, FILES_DIR, "out"), exist_ok=True)
for f, data in files.items():
p = os.path.join(adir, f)
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "wb") as fh:
fh.write(data if isinstance(data, bytes) else data.encode())
ctx.emit(ctx.name, {"files": files, "vars": vars})
def main():
args = [a for a in sys.argv[1:] if not a.startswith("--")]
if "--list" in sys.argv:
for p in pages(args):
for line, lang, code, marker in snippets(p):
if lang in LUA_LANGS:
print("%s:%d %s %s" % (os.path.relpath(p, ROOT), line, lang, marker or "run"))
return
try:
paths, nrun, nshow, nex = generate(args)
except DocError as e:
print("docs_check: " + str(e))
sys.exit(1)
print("docs_check: %d snippets to run, %d display-only, %d examples -> %s" % (nrun, nshow, nex, os.path.relpath(OUT, ROOT)))
if __name__ == "__main__":
main()