ws-docs: tools/docs_check.py (guide snippets and examples become tests under both runtimes), docs inputs generator
This commit is contained in:
1 parent
9941113b7b
commit
cdcbd76b9e
4 files changed
+362
No files matched your search
@@ -0,0 +1,2 @@
|
|||||||
|
# generated by tools/docs_check.py (tools/fixtures/docs.py)
|
||||||
|
snippets/
|
||||||
@@ -0,0 +1,255 @@
|
|||||||
|
#!/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()
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
# Docs snippets (tools/fixtures.py): every ```luau block of docs/guide/*.md and every examples/*.luau becomes a test
|
||||||
|
# under tests/docs/snippets/ (tools/docs_check.py explains the markers). Generated here so `bash tools/test.sh`
|
||||||
|
# always tests the pages as they are; the inputs the snippets read come from tools/fixtures/docs_*.py.
|
||||||
|
import importlib.util, os
|
||||||
|
|
||||||
|
INPUTS = ["docs/guide", "examples", "tools/docs_check.py"]
|
||||||
|
|
||||||
|
|
||||||
|
def generate(ctx):
|
||||||
|
spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py"))
|
||||||
|
dc = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(dc)
|
||||||
|
paths, nrun, nshow, nex = dc.generate()
|
||||||
|
print("fixtures: docs: %d snippets to run, %d display-only, %d examples" % (nrun, nshow, nex))
|
||||||
|
ctx.outputs.extend(paths)
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
# Docs inputs (tools/fixtures.py): the shared files the guide snippets read (tools/docs_check.py), made by reference
|
||||||
|
# tools: a PNG written here (zlib), GIF / JPEG / WebP by ImageMagick, a stereo tone as WAV (Python's wave), FLAC, MP3
|
||||||
|
# and Ogg Vorbis by ffmpeg with tags.
|
||||||
|
# tests/gen/docs_inputs.luau { files = { [name] = bytes }, vars = { pngBytes = "photo.png", ... } }
|
||||||
|
# tests/gen/docs_files/assets/<name> the same files, for the snippets that load by path
|
||||||
|
import importlib.util, io, math, os, struct, tempfile, wave, zlib
|
||||||
|
|
||||||
|
INPUTS = ["tools/docs_check.py"]
|
||||||
|
|
||||||
|
|
||||||
|
def docs_check(ctx):
|
||||||
|
spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py"))
|
||||||
|
m = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(m)
|
||||||
|
return m
|
||||||
|
|
||||||
|
|
||||||
|
def png(w, h, rgba):
|
||||||
|
def chunk(t, d):
|
||||||
|
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xffffffff)
|
||||||
|
raw = b"".join(b"\0" + rgba[y * w * 4:(y + 1) * w * 4] for y in range(h))
|
||||||
|
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)) +
|
||||||
|
chunk(b"IDAT", zlib.compress(raw, 9)) + chunk(b"IEND", b""))
|
||||||
|
|
||||||
|
|
||||||
|
def photo(w, h):
|
||||||
|
"""a gradient with a soft-edged disc: red across, green down, a translucent right edge"""
|
||||||
|
out = bytearray()
|
||||||
|
for y in range(h):
|
||||||
|
for x in range(w):
|
||||||
|
d = math.hypot(x - w / 2, y - h / 2) / (h / 2)
|
||||||
|
out += bytes((x * 255 // (w - 1), y * 255 // (h - 1), 255 if d < 0.6 else 64, 255 if x < w - 8 else 128))
|
||||||
|
return bytes(out)
|
||||||
|
|
||||||
|
|
||||||
|
def tone(rate, seconds, channels=2):
|
||||||
|
n = int(rate * seconds)
|
||||||
|
b = io.BytesIO()
|
||||||
|
with wave.open(b, "wb") as wv:
|
||||||
|
wv.setnchannels(channels)
|
||||||
|
wv.setsampwidth(2)
|
||||||
|
wv.setframerate(rate)
|
||||||
|
frames = bytearray()
|
||||||
|
for i in range(n):
|
||||||
|
env = min(1.0, i / 441, (n - i) / 441)
|
||||||
|
for c in range(channels):
|
||||||
|
f = 440 if c == 0 else 660
|
||||||
|
frames += struct.pack("<h", int(12000 * env * math.sin(2 * math.pi * f * i / rate)))
|
||||||
|
wv.writeframes(bytes(frames))
|
||||||
|
return b.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def generate(ctx):
|
||||||
|
dc = docs_check(ctx)
|
||||||
|
files = {}
|
||||||
|
w, h = 64, 48
|
||||||
|
files["photo.png"] = png(w, h, photo(w, h))
|
||||||
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
src = os.path.join(d, "photo.png")
|
||||||
|
with open(src, "wb") as f:
|
||||||
|
f.write(files["photo.png"])
|
||||||
|
for name, args in (("photo.jpg", ["-quality", "90"]), ("photo.webp", ["-define", "webp:lossless=true"])):
|
||||||
|
out = os.path.join(d, name)
|
||||||
|
ctx.nix("imagemagick", ["magick", src] + args + [out])
|
||||||
|
files[name] = open(out, "rb").read()
|
||||||
|
gif = os.path.join(d, "anim.gif")
|
||||||
|
ctx.nix("imagemagick", ["magick", "-delay", "10", "-size", "32x24", "xc:red", "xc:lime", "xc:blue",
|
||||||
|
"-loop", "0", gif])
|
||||||
|
files["anim.gif"] = open(gif, "rb").read()
|
||||||
|
files["tone.wav"] = tone(44100, 1.0)
|
||||||
|
wav = os.path.join(d, "tone.wav")
|
||||||
|
with open(wav, "wb") as f:
|
||||||
|
f.write(files["tone.wav"])
|
||||||
|
tags = ["-metadata", "title=Docs Tone", "-metadata", "artist=formats-luau", "-metadata", "album=Guide",
|
||||||
|
"-metadata", "date=2026"]
|
||||||
|
for name, codec in (("tone.flac", ["-c:a", "flac"]), ("tone.mp3", ["-c:a", "libmp3lame", "-b:a", "128k"]),
|
||||||
|
("tone.ogg", ["-c:a", "libvorbis", "-q:a", "3"])):
|
||||||
|
out = os.path.join(d, name)
|
||||||
|
ctx.nix("ffmpeg", ["ffmpeg", "-v", "error", "-y", "-i", wav] + codec + tags + [out])
|
||||||
|
files[name] = open(out, "rb").read()
|
||||||
|
dc.emit_inputs(ctx, files, {
|
||||||
|
"pngBytes": "photo.png",
|
||||||
|
"jpegBytes": "photo.jpg",
|
||||||
|
"webpBytes": "photo.webp",
|
||||||
|
"gifBytes": "anim.gif",
|
||||||
|
"wavBytes": "tone.wav",
|
||||||
|
"flacBytes": "tone.flac",
|
||||||
|
"mp3Bytes": "tone.mp3",
|
||||||
|
"oggBytes": "tone.ogg",
|
||||||
|
})
|
||||||
Reference in new issue
Block a user