|
| 1 | +""" |
| 2 | +Build script for the lambda calculus web app. |
| 3 | +
|
| 4 | +Reads pylambda.py (stripping the __main__ block), appends browser-specific code, |
| 5 | +and injects the combined Python code into web/template.html to produce |
| 6 | +the deployable index.html. |
| 7 | +""" |
| 8 | + |
| 9 | +import re |
| 10 | +from pathlib import Path |
| 11 | + |
| 12 | +ROOT = Path(__file__).parent |
| 13 | +WEB = ROOT / "web" |
| 14 | +OUTPUT = ROOT / "_site" |
| 15 | + |
| 16 | +PLACEHOLDER = "<!-- PYTHON_CODE -->" |
| 17 | + |
| 18 | +BROWSER_CODE = """ |
| 19 | +from browser import document |
| 20 | +
|
| 21 | +def on_input(ev): |
| 22 | + try: |
| 23 | + expr = parse_expr(document["input"].value) |
| 24 | + result = reduce(expr) |
| 25 | + document["output"].value = str(result) |
| 26 | + except Exception: |
| 27 | + document["output"].value = "" |
| 28 | +
|
| 29 | +document["input"].bind("input", on_input) |
| 30 | +""" |
| 31 | + |
| 32 | + |
| 33 | +def strip_main_block(source: str) -> str: |
| 34 | + """Remove the if __name__ == '__main__': block from the source.""" |
| 35 | + return re.sub( |
| 36 | + r'\n*if __name__\s*==\s*["\']__main__["\']\s*:.*', |
| 37 | + "", |
| 38 | + source, |
| 39 | + flags=re.DOTALL, |
| 40 | + ).rstrip() + "\n" |
| 41 | + |
| 42 | + |
| 43 | +def build(): |
| 44 | + template_path = WEB / "template.html" |
| 45 | + pylambda_path = ROOT / "pylambda.py" |
| 46 | + |
| 47 | + if not template_path.exists(): |
| 48 | + print(f"Error: {template_path} not found.") |
| 49 | + return |
| 50 | + if not pylambda_path.exists(): |
| 51 | + print(f"Error: {pylambda_path} not found.") |
| 52 | + return |
| 53 | + |
| 54 | + template = template_path.read_text(encoding="utf-8") |
| 55 | + pylambda = pylambda_path.read_text(encoding="utf-8") |
| 56 | + |
| 57 | + # Strip the __main__ block |
| 58 | + core_code = strip_main_block(pylambda) |
| 59 | + |
| 60 | + # Combine: core library + browser bindings |
| 61 | + combined = core_code + "\n" + BROWSER_CODE |
| 62 | + |
| 63 | + # Indent the Python code to match the <script> block indentation (4 spaces) |
| 64 | + indented = "\n".join(" " + line if line.strip() else "" for line in combined.splitlines()) |
| 65 | + |
| 66 | + # Inject into template |
| 67 | + html = template.replace(PLACEHOLDER, indented) |
| 68 | + |
| 69 | + OUTPUT.mkdir(exist_ok=True) |
| 70 | + (OUTPUT / "index.html").write_text(html, encoding="utf-8") |
| 71 | + print(f"Built {OUTPUT / 'index.html'}") |
| 72 | + |
| 73 | + |
| 74 | +if __name__ == "__main__": |
| 75 | + build() |
| 76 | + |
0 commit comments