|
| 1 | +"""Generate an interactive HTML page for decoding curl corpus files.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import argparse |
| 6 | +from datetime import datetime, timezone |
| 7 | +from collections.abc import Sequence |
| 8 | +from pathlib import Path |
| 9 | + |
| 10 | +from jinja2 import Environment, FileSystemLoader, select_autoescape |
| 11 | + |
| 12 | +from .corpus import BaseType |
| 13 | +from .logger import common_logging |
| 14 | + |
| 15 | +_TEMPLATE_NAME = "corpus_decoder.html" |
| 16 | +_DEFAULT_OUTPUT = Path("docs/corpus-decoder/index.html") |
| 17 | + |
| 18 | + |
| 19 | +def _jinja_env() -> Environment: |
| 20 | + template_dir = Path(__file__).with_name("templates") |
| 21 | + if not template_dir.exists(): |
| 22 | + raise FileNotFoundError(f"Template directory not found at {template_dir}") |
| 23 | + return Environment( |
| 24 | + loader=FileSystemLoader(template_dir), |
| 25 | + autoescape=select_autoescape(["html", "xml"]), |
| 26 | + trim_blocks=True, |
| 27 | + lstrip_blocks=True, |
| 28 | + ) |
| 29 | + |
| 30 | + |
| 31 | +def _render_html(env: Environment) -> str: |
| 32 | + template = env.get_template(_TEMPLATE_NAME) |
| 33 | + generated_at = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d %H:%M:%SZ") |
| 34 | + typemap = {str(key): value for key, value in BaseType.TYPEMAP.items()} |
| 35 | + return template.render(generated_at=generated_at, typemap=typemap) |
| 36 | + |
| 37 | + |
| 38 | +def generate_html(output: Path) -> Path: |
| 39 | + """Generate the HTML decoder page to the provided output path.""" |
| 40 | + env = _jinja_env() |
| 41 | + html = _render_html(env) |
| 42 | + |
| 43 | + output.parent.mkdir(parents=True, exist_ok=True) |
| 44 | + output.write_text(html, encoding="utf-8") |
| 45 | + return output |
| 46 | + |
| 47 | + |
| 48 | +def _parse_args() -> argparse.Namespace: |
| 49 | + parser = argparse.ArgumentParser(description=__doc__) |
| 50 | + parser.add_argument( |
| 51 | + "--output", |
| 52 | + type=Path, |
| 53 | + default=_DEFAULT_OUTPUT, |
| 54 | + help=f"Target path for the generated HTML file (default: {_DEFAULT_OUTPUT})", |
| 55 | + ) |
| 56 | + return parser.parse_args() |
| 57 | + |
| 58 | + |
| 59 | +def main() -> Path: |
| 60 | + """CLI entry point for generating the decoder HTML.""" |
| 61 | + args = _parse_args() |
| 62 | + output_path = args.output |
| 63 | + generated_file = generate_html(output_path) |
| 64 | + print(f"Generated decoder HTML at {generated_file}") |
| 65 | + return generated_file |
| 66 | + |
| 67 | + |
| 68 | +def run() -> None: |
| 69 | + """Wrapper to set up logging before running the tool.""" |
| 70 | + common_logging(__name__, __file__) |
| 71 | + main() |
| 72 | + |
| 73 | + |
| 74 | +if __name__ == "__main__": |
| 75 | + run() |
0 commit comments