|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import argparse |
| 4 | +import importlib.util |
| 5 | +import shutil |
| 6 | +import subprocess |
| 7 | +import sys |
| 8 | +import traceback |
| 9 | +import types |
| 10 | +import typing |
| 11 | +from pathlib import Path |
| 12 | + |
| 13 | +from lib import SNIPPETS_DIR, CollectedSnippetsType, collect_snippets, log |
| 14 | +from lib.languages import ALL_LANGUAGES, CompileResult, Language, parse_languages |
| 15 | + |
| 16 | + |
| 17 | +def main() -> None: |
| 18 | + parser = argparse.ArgumentParser() |
| 19 | + default_langs = ",".join([lang.NAME for lang in ALL_LANGUAGES]) |
| 20 | + |
| 21 | + parser.add_argument( |
| 22 | + "-l", |
| 23 | + "--langs", |
| 24 | + help=f"comma-separated list of languages, default is {default_langs}", |
| 25 | + default=default_langs, |
| 26 | + ) |
| 27 | + parser.add_argument( |
| 28 | + "command", |
| 29 | + help="command to execute", |
| 30 | + choices=["build", "run", "test"], |
| 31 | + ) |
| 32 | + parser.add_argument( |
| 33 | + "snippets", |
| 34 | + nargs="*", |
| 35 | + help=f"Snippet filenames/directories to process, default: {SNIPPETS_DIR}", |
| 36 | + default=[SNIPPETS_DIR], |
| 37 | + type=Path, |
| 38 | + metavar="SNIPPET_PATH", |
| 39 | + ) |
| 40 | + |
| 41 | + args = parser.parse_args() |
| 42 | + |
| 43 | + languages = parse_languages(args.langs) |
| 44 | + snippets = collect_snippets(args.snippets, languages) |
| 45 | + assert args.command in ("build", "run", "test") |
| 46 | + |
| 47 | + # Q: Why not `tempfile.TemporaryDirectory()`? |
| 48 | + # A: Harder to debug/inspect generated files. |
| 49 | + tmpdir = Path(__file__).parent / "tmp" |
| 50 | + shutil.rmtree(tmpdir, ignore_errors=True) |
| 51 | + tmpdir.mkdir(parents=True) |
| 52 | + build_and_run(tmpdir=tmpdir, snippets=snippets, mode=args.command) |
| 53 | + |
| 54 | + |
| 55 | +def build_and_run( |
| 56 | + tmpdir: Path, |
| 57 | + snippets: CollectedSnippetsType, |
| 58 | + mode: typing.Literal[ |
| 59 | + "build", # just build |
| 60 | + "run", # build and run each snippet |
| 61 | + "test", # build, then run/test all snippets that have a test.py file |
| 62 | + ], |
| 63 | +) -> None: |
| 64 | + snippets_by_lang: dict[type[Language], list[Path]] = {} |
| 65 | + |
| 66 | + for snippets2 in snippets.values(): |
| 67 | + for lang, fname in snippets2.items(): |
| 68 | + snippets_by_lang.setdefault(lang, []).append(fname) |
| 69 | + |
| 70 | + compile_results: dict[type[Language], CompileResult] = {} |
| 71 | + errors: list[str] = [] |
| 72 | + |
| 73 | + # Load test modules before compilation. |
| 74 | + # We want them to crash early. |
| 75 | + test_modules: dict[Path, types.ModuleType] = {} |
| 76 | + if mode == "test": |
| 77 | + for snippet_dir in snippets: |
| 78 | + test_file = snippet_dir / "test.py" |
| 79 | + if not test_file.exists(): |
| 80 | + continue |
| 81 | + spec = importlib.util.spec_from_file_location("test_module", test_file) |
| 82 | + assert spec is not None |
| 83 | + mod = importlib.util.module_from_spec(spec) |
| 84 | + assert spec.loader is not None |
| 85 | + spec.loader.exec_module(mod) |
| 86 | + test_modules[snippet_dir] = mod |
| 87 | + |
| 88 | + log("Compile stage") |
| 89 | + for lang, fnames in snippets_by_lang.items(): |
| 90 | + log(f"· Compiling {lang.NAME} snippets") |
| 91 | + try: |
| 92 | + res = lang.compile(tmpdir / lang.NAME, fnames) |
| 93 | + if res.has_issues: |
| 94 | + log(f"· · Compilation had issues for {lang.NAME}") |
| 95 | + errors.append(f"Compilation had issues for {lang.NAME}") |
| 96 | + compile_results[lang] = res |
| 97 | + except Exception as e: |
| 98 | + log(f"· · Compilation failed for {lang.NAME}") |
| 99 | + errors.append(f"Compilation failed for {lang.NAME}") |
| 100 | + if not isinstance(e, subprocess.CalledProcessError): |
| 101 | + traceback.print_exc() |
| 102 | + |
| 103 | + if mode in ("run", "test"): |
| 104 | + log("Run stage") |
| 105 | + for snippet_dir, snippets2 in snippets.items(): |
| 106 | + if mode == "run": |
| 107 | + for lang, snippet_fname in snippets2.items(): |
| 108 | + if (compile_result := compile_results.get(lang)) is None: |
| 109 | + continue |
| 110 | + |
| 111 | + log(f"· Running {snippet_fname}") |
| 112 | + p = subprocess.run( |
| 113 | + compile_result.run_args[snippet_fname], |
| 114 | + text=True, |
| 115 | + ) |
| 116 | + if p.returncode != 0: |
| 117 | + log(f"· · Exit code {p.returncode}") |
| 118 | + |
| 119 | + if mode == "test" and snippet_dir in test_modules: |
| 120 | + log(f"· Testing snippets in {snippet_dir}") |
| 121 | + mod = test_modules[snippet_dir] |
| 122 | + |
| 123 | + for lang, snippet_fname in snippets2.items(): |
| 124 | + compile_result = compile_results.get(lang) |
| 125 | + if compile_result is None: |
| 126 | + continue |
| 127 | + |
| 128 | + log(f"· · Testing {snippet_fname}") |
| 129 | + |
| 130 | + output = None |
| 131 | + try: |
| 132 | + if hasattr(mod, "prepare"): |
| 133 | + mod.prepare() |
| 134 | + |
| 135 | + p = subprocess.run( |
| 136 | + compile_result.run_args[snippet_fname], |
| 137 | + stdout=subprocess.PIPE, |
| 138 | + stderr=subprocess.STDOUT, |
| 139 | + text=True, |
| 140 | + ) |
| 141 | + |
| 142 | + output = p.stdout |
| 143 | + if p.returncode != 0: |
| 144 | + msg = f"Process exited with code {p.returncode}" |
| 145 | + raise RuntimeError(msg) |
| 146 | + |
| 147 | + if hasattr(mod, "check"): |
| 148 | + mod.check() |
| 149 | + except Exception: |
| 150 | + log(f"· · · Testing {snippet_fname} failed") |
| 151 | + if output: |
| 152 | + print(output.rstrip()) |
| 153 | + traceback.print_exc() |
| 154 | + errors.append(f"Testing {snippet_fname} failed") |
| 155 | + finally: |
| 156 | + try: |
| 157 | + if hasattr(mod, "cleanup"): |
| 158 | + mod.cleanup() |
| 159 | + except Exception: |
| 160 | + log(f"· · · Teardown for {snippet_fname} failed") |
| 161 | + errors.append(f"Teardown for {snippet_fname} failed") |
| 162 | + traceback.print_exc() |
| 163 | + |
| 164 | + if errors: |
| 165 | + log("Errors encountered:") |
| 166 | + for err in errors: |
| 167 | + log(f"· {err}") |
| 168 | + sys.exit(1) |
| 169 | + elif mode == "test": |
| 170 | + log("All tests passed successfully.") |
| 171 | + |
| 172 | + |
| 173 | +if __name__ == "__main__": |
| 174 | + main() |
0 commit comments