| #!/usr/bin/env python3 | |
| # | |
| # Copyright 2026 The Fuchsia Authors | |
| # | |
| # Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 | |
| # <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT | |
| # license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. | |
| # This file may not be copied, modified, or distributed except according to | |
| # those terms. | |
| """Stage `site/` and root `ACKNOWLEDGMENTS.md` into a temp dir and run Zola. | |
| Anneal forbids symlinks repository-wide and keeps `ACKNOWLEDGMENTS.md` at the | |
| repository root as a single source of truth. This script copies `site/` into a | |
| temporary directory, converts `ACKNOWLEDGMENTS.md` into a template-safe Zola | |
| page at `site/content/acknowledgments.md`, and invokes `zola check`, `zola | |
| build`, or `zola serve`. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import os | |
| from pathlib import Path | |
| import re | |
| import shutil | |
| import stat | |
| import subprocess | |
| import sys | |
| import tempfile | |
| GITHUB_REPO_URL = "https://github.com/google/anneal" | |
| FRONTMATTER = ( | |
| '+++\n' | |
| 'title = "Acknowledgments"\n' | |
| 'template = "acknowledgments.html"\n' | |
| 'path = "acknowledgments"\n' | |
| '+++\n\n' | |
| ) | |
| FENCE_RE = re.compile(r"^\s*(`{3,}|~{3,})(.*)$") | |
| # Match CommonMark inline links, including optional inner whitespace, | |
| # angle-bracketed destinations (`<path>`), and optional link titles (`"..."`, | |
| # `'...'`, or `(...)`). | |
| INLINE_LINK_RE = re.compile( | |
| r"(\]\(\s*)(?:<([^>\n]+)>|([^)\s]+))" | |
| r"(\s*(?:(?:\"[^\"\\]*(?:\\.[^\"\\]*)*\"" | |
| r"|'[^'\\]*(?:\\.[^'\\]*)*'" | |
| r"|\([^)\\]*(?:\\.[^)\\]*)*\))\s*)?\))" | |
| ) | |
| REFDEF_RE = re.compile( | |
| r"^(\s{0,3}\[[^\]]+\]:\s*)(?:<([^>\n]+)>|(\S+))(.*)$" | |
| ) | |
| CODE_SPAN_RE = re.compile(r"`+[^`]*`+") | |
| DISPLAY_MATH_RE = re.compile(r"\$\$.+?\$\$") | |
| # Exact pandoc `tex_math_dollars` inline math grammar: opening `$` is not | |
| # escaped and not followed by whitespace; closing `$` is not escaped, not | |
| # preceded by whitespace, and not immediately followed by an ASCII digit (so | |
| # currency phrases like `$5 or $10` pass while `$\mathbb{F}_2$` and `$x+1$` | |
| # fail closed). | |
| INLINE_MATH_RE = re.compile( | |
| r"(?<!\\)\$(?=\S)(?:[^$\\]|\\.)*?(?<=[^\s\\])\$(?![0-9])" | |
| ) | |
| # Zola evaluates Tera delimiters across page Markdown before rendering, even | |
| # inside code spans and fences; rejecting `{%` also prevents `{% endraw %}` | |
| # breakout from the defense-in-depth `{% raw %}` wrapper. | |
| TERA_RE = re.compile(r"\{\{|\{%|\{#") | |
| class BuildError(Exception): | |
| """Raised when `ACKNOWLEDGMENTS.md` fails staging validation.""" | |
| def _fence(line: str) -> str | None: | |
| """Return the fence delimiter char if `line` opens/closes a code fence.""" | |
| m = FENCE_RE.match(line) | |
| if not m: | |
| return None | |
| if m.group(1)[0] == "`" and "`" in m.group(2): | |
| return None | |
| return m.group(1)[0] | |
| def _resolve_link(target: str, repo_root: Path) -> str: | |
| """Resolve a Markdown link target, rewriting verified repo-relative paths.""" | |
| if target.startswith(("http://", "https://", "mailto:", "#")): | |
| return target | |
| path_part, _, fragment = target.partition("#") | |
| if not path_part: | |
| return target | |
| if os.path.isabs(path_part): | |
| raise BuildError(f"relative link escapes repository root: {target}") | |
| rel = os.path.normpath(path_part) | |
| if rel == ".." or rel.startswith("../") or os.path.isabs(rel): | |
| raise BuildError(f"relative link escapes repository root: {target}") | |
| full = (repo_root / rel).resolve() | |
| try: | |
| full.relative_to(repo_root.resolve()) | |
| except ValueError as e: | |
| raise BuildError( | |
| f"relative link escapes repository root: {target}" | |
| ) from e | |
| if not full.exists(): | |
| raise BuildError(f"relative link target does not exist: {target}") | |
| kind = "tree" if full.is_dir() else "blob" | |
| url = f"{GITHUB_REPO_URL}/{kind}/main/{rel.replace(os.sep, '/')}" | |
| return f"{url}#{fragment}" if fragment else url | |
| def _replace_link_match(m: re.Match[str], repo_root: Path) -> str: | |
| """Resolve group 2 (`<dest>`) or group 3 (`dest`) preserving wrappers.""" | |
| if m.group(2) is not None: | |
| return (m.group(1) + "<" + _resolve_link(m.group(2), repo_root) | |
| + ">" + m.group(4)) | |
| return m.group(1) + _resolve_link(m.group(3), repo_root) + m.group(4) | |
| def _rewrite_inline_links(line: str, repo_root: Path) -> str: | |
| """Rewrite inline links outside backtick code spans on a single line.""" | |
| parts: list[str] = [] | |
| pos = 0 | |
| for code_match in CODE_SPAN_RE.finditer(line): | |
| seg = line[pos:code_match.start()] | |
| parts.append( | |
| INLINE_LINK_RE.sub( | |
| lambda m: _replace_link_match(m, repo_root), | |
| seg, | |
| ) | |
| ) | |
| parts.append(code_match.group(0)) | |
| pos = code_match.end() | |
| tail = line[pos:] | |
| parts.append( | |
| INLINE_LINK_RE.sub( | |
| lambda m: _replace_link_match(m, repo_root), | |
| tail, | |
| ) | |
| ) | |
| return "".join(parts) | |
| def transform_acknowledgments(text: str, repo_root: Path) -> str: | |
| """Validate and convert root `ACKNOWLEDGMENTS.md` to a Zola page.""" | |
| lines = text.splitlines() | |
| i = 0 | |
| while i < len(lines): | |
| if not lines[i].strip(): | |
| i += 1 | |
| continue | |
| if lines[i].lstrip().startswith("<!--"): | |
| while "-->" not in lines[i]: | |
| i += 1 | |
| if i >= len(lines): | |
| raise BuildError("unterminated leading HTML comment") | |
| i += 1 | |
| continue | |
| break | |
| if i >= len(lines) or lines[i].strip() != "# Acknowledgments": | |
| raise BuildError( | |
| "ACKNOWLEDGMENTS.md must start with '# Acknowledgments' after " | |
| "leading HTML comments" | |
| ) | |
| body = lines[i + 1:] | |
| for line_no, line in enumerate(body, i + 2): | |
| if TERA_RE.search(line): | |
| raise BuildError( | |
| f"ACKNOWLEDGMENTS.md:{line_no}: Tera delimiter ({{{{, {{%, " | |
| "or {#) is not allowed; Zola evaluates page content as Tera" | |
| ) | |
| out: list[str] = [] | |
| in_fence: str | None = None | |
| for line_no, line in enumerate(body, i + 2): | |
| tok = _fence(line) | |
| if tok is not None: | |
| if in_fence is None: | |
| in_fence = tok | |
| elif in_fence == tok: | |
| in_fence = None | |
| out.append(line) | |
| continue | |
| if in_fence is not None: | |
| out.append(line) | |
| continue | |
| visible = CODE_SPAN_RE.sub("", line) | |
| if DISPLAY_MATH_RE.search(visible) or INLINE_MATH_RE.search(visible): | |
| raise BuildError( | |
| f"ACKNOWLEDGMENTS.md:{line_no}: GFM $...$ math does not " | |
| "render in Zola; use Unicode such as 𝔽₂" | |
| ) | |
| ref_match = REFDEF_RE.match(line) | |
| if ref_match: | |
| line = _replace_link_match(ref_match, repo_root) | |
| else: | |
| line = _rewrite_inline_links(line, repo_root) | |
| out.append(line) | |
| rendered_body = "\n".join(out).strip("\n") | |
| return f"{FRONTMATTER}{{% raw %}}\n{rendered_body}\n{{% endraw %}}\n" | |
| def _make_tree_owner_writable(root: Path) -> None: | |
| """Ensure staged copies from read-only source trees are writable.""" | |
| for dirpath, _, filenames in os.walk(root): | |
| dpath = Path(dirpath) | |
| dmode = stat.S_IMODE(dpath.stat().st_mode) | |
| os.chmod(dpath, dmode | stat.S_IRWXU) | |
| for name in filenames: | |
| fpath = dpath / name | |
| fmode = stat.S_IMODE(fpath.stat().st_mode) | |
| os.chmod(fpath, fmode | stat.S_IRUSR | stat.S_IWUSR) | |
| def stage_site(repo_root: Path, temp_dir: Path) -> Path: | |
| """Copy `site/` into `temp_dir` and generate `content/acknowledgments.md`.""" | |
| site_src = repo_root / "site" | |
| ack_src = repo_root / "ACKNOWLEDGMENTS.md" | |
| if not site_src.is_dir(): | |
| raise BuildError(f"missing site directory: {site_src}") | |
| if not ack_src.is_file(): | |
| raise BuildError(f"missing root acknowledgments file: {ack_src}") | |
| staged = temp_dir / "site" | |
| shutil.copytree(site_src, staged, symlinks=False) | |
| _make_tree_owner_writable(staged) | |
| ack_text = ack_src.read_text(encoding="utf-8") | |
| (staged / "content" / "acknowledgments.md").write_text( | |
| transform_acknowledgments(ack_text, repo_root), | |
| encoding="utf-8", | |
| ) | |
| return staged | |
| def main(argv: list[str] | None = None) -> int: | |
| default_root = str(Path(__file__).resolve().parents[1]) | |
| parser = argparse.ArgumentParser( | |
| description=__doc__.split("\n\n", 1)[0], | |
| ) | |
| sub = parser.add_subparsers(dest="cmd", required=True) | |
| build_p = sub.add_parser("build", help="check and/or build the site") | |
| build_p.add_argument("--base-url", required=True, | |
| help="base URL passed to `zola build --base-url`") | |
| build_p.add_argument("--output-dir", required=True, | |
| help="output directory for `zola build`") | |
| build_p.add_argument("--check", action="store_true", | |
| help="run `zola check --skip-external-links` first") | |
| build_p.add_argument("--repo-root", default=default_root, | |
| help="repository root (default: script parent dir)") | |
| serve_p = sub.add_parser("serve", help="preview the site locally") | |
| serve_p.add_argument("--port", default="1111", help="local server port") | |
| serve_p.add_argument("--interface", default="127.0.0.1", | |
| help="bind interface") | |
| serve_p.add_argument("--repo-root", default=default_root, | |
| help="repository root (default: script parent dir)") | |
| args = parser.parse_args(argv) | |
| repo_root = Path(args.repo_root).resolve() | |
| zola = os.environ.get("ZOLA", "zola") | |
| try: | |
| with tempfile.TemporaryDirectory(prefix="anneal-site-stage-") as td: | |
| staged = stage_site(repo_root, Path(td)) | |
| if args.cmd == "build": | |
| out_dir = str(Path(args.output_dir).resolve()) | |
| if args.check: | |
| subprocess.run( | |
| [zola, "check", "--skip-external-links"], | |
| cwd=staged, check=True, | |
| ) | |
| subprocess.run( | |
| [zola, "build", "--base-url", args.base_url, | |
| "--output-dir", out_dir], | |
| cwd=staged, check=True, | |
| ) | |
| else: | |
| print( | |
| "note: staged into a temporary directory; re-run after " | |
| "editing ACKNOWLEDGMENTS.md or site/.", | |
| file=sys.stderr, | |
| ) | |
| subprocess.run( | |
| [zola, "serve", "--port", args.port, | |
| "--interface", args.interface], | |
| cwd=staged, check=True, | |
| ) | |
| except BuildError as e: | |
| print(f"build_site: error: {e}", file=sys.stderr) | |
| return 2 | |
| except FileNotFoundError as e: | |
| print(f"build_site: error: {e}", file=sys.stderr) | |
| return 2 | |
| except subprocess.CalledProcessError as e: | |
| return e.returncode or 1 | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) |