| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- #!/usr/bin/env python3
- """Compile every standalone C++ fenced block in course Markdown files."""
- from __future__ import annotations
- import re
- import subprocess
- import sys
- import tempfile
- from pathlib import Path
- def main() -> int:
- root = Path(sys.argv[1] if len(sys.argv) > 1 else "课程")
- documents = sorted(root.rglob("*.md"))
- failed = 0
- compiled = 0
- snippets = 0
- with tempfile.TemporaryDirectory(prefix="course-cpp-") as temp:
- directory = Path(temp)
- for source in sorted(Path("参考实现").rglob("*.cpp")):
- compiled += 1
- output = directory / f"attachment-{compiled}"
- result = subprocess.run(
- [
- "g++",
- "-std=c++17",
- "-Wall",
- "-Wextra",
- "-Wpedantic",
- str(source),
- "-o",
- str(output),
- ],
- text=True,
- capture_output=True,
- check=False,
- )
- if result.returncode != 0:
- failed += 1
- print(f"FAIL {source}", file=sys.stderr)
- print(result.stderr, file=sys.stderr)
- for document in documents:
- text = document.read_text(encoding="utf-8")
- blocks = re.findall(r"```(?:cpp|c\+\+)\n(.*?)```", text, flags=re.DOTALL)
- for index, code in enumerate(blocks, 1):
- if not re.search(r"\bint\s+main\s*\(", code):
- snippets += 1
- continue
- compiled += 1
- source = directory / f"block-{compiled}.cpp"
- output = directory / f"block-{compiled}"
- source.write_text(code, encoding="utf-8")
- result = subprocess.run(
- [
- "g++",
- "-std=c++17",
- "-Wall",
- "-Wextra",
- "-Wpedantic",
- str(source),
- "-o",
- str(output),
- ],
- text=True,
- capture_output=True,
- check=False,
- )
- if result.returncode != 0:
- failed += 1
- print(f"FAIL {document}:{index}", file=sys.stderr)
- print(result.stderr, file=sys.stderr)
- print(f"compiled={compiled} snippets_skipped={snippets} failed={failed}")
- return 1 if failed else 0
- if __name__ == "__main__":
- raise SystemExit(main())
|