|
| 1 | +#!/usr/bin/env python3 |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +import argparse |
| 5 | +import importlib.util |
| 6 | +import subprocess |
| 7 | +import sys |
| 8 | +from functools import partial |
| 9 | +from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer |
| 10 | +from pathlib import Path |
| 11 | + |
| 12 | +ROOT = Path(__file__).resolve().parents[1] |
| 13 | +DOCS_DIR = ROOT / "docs" |
| 14 | +BUILD_DIR = DOCS_DIR / "_build" / "html" |
| 15 | +DEFAULT_HOST = "127.0.0.1" |
| 16 | +DEFAULT_PORT = 8000 |
| 17 | +DOCS_MODULES = ("sphinx", "sphinx_rtd_theme", "sphinx_click") |
| 18 | + |
| 19 | + |
| 20 | +def parse_args(argv: list[str] | None = None) -> argparse.Namespace: |
| 21 | + parser = argparse.ArgumentParser( |
| 22 | + description="Build and preview the cwms-cli docs locally." |
| 23 | + ) |
| 24 | + parser.add_argument( |
| 25 | + "--port", |
| 26 | + type=int, |
| 27 | + default=DEFAULT_PORT, |
| 28 | + help=f"Local port for the preview server (default: {DEFAULT_PORT}).", |
| 29 | + ) |
| 30 | + return parser.parse_args(argv) |
| 31 | + |
| 32 | + |
| 33 | +def find_missing_docs_modules() -> list[str]: |
| 34 | + return [name for name in DOCS_MODULES if importlib.util.find_spec(name) is None] |
| 35 | + |
| 36 | + |
| 37 | +def build_docs() -> int: |
| 38 | + result = subprocess.run( |
| 39 | + [ |
| 40 | + sys.executable, |
| 41 | + "-m", |
| 42 | + "sphinx", |
| 43 | + "-nW", |
| 44 | + "-b", |
| 45 | + "html", |
| 46 | + str(DOCS_DIR), |
| 47 | + str(BUILD_DIR), |
| 48 | + ], |
| 49 | + cwd=ROOT, |
| 50 | + check=False, |
| 51 | + ) |
| 52 | + return result.returncode |
| 53 | + |
| 54 | + |
| 55 | +def serve_docs(port: int) -> None: |
| 56 | + handler = partial(SimpleHTTPRequestHandler, directory=str(BUILD_DIR)) |
| 57 | + server = ThreadingHTTPServer((DEFAULT_HOST, port), handler) |
| 58 | + print(f"Docs preview available at http://{DEFAULT_HOST}:{port}/") |
| 59 | + print(f"Serving files from {BUILD_DIR}") |
| 60 | + try: |
| 61 | + server.serve_forever() |
| 62 | + except KeyboardInterrupt: |
| 63 | + print("\nStopping docs preview server.") |
| 64 | + finally: |
| 65 | + server.server_close() |
| 66 | + |
| 67 | + |
| 68 | +def main(argv: list[str] | None = None) -> int: |
| 69 | + args = parse_args(argv) |
| 70 | + missing = find_missing_docs_modules() |
| 71 | + if missing: |
| 72 | + missing_list = ", ".join(missing) |
| 73 | + print( |
| 74 | + "Missing docs dependencies " |
| 75 | + f"({missing_list}). Install them with:\n" |
| 76 | + f"{sys.executable} -m pip install -r docs/requirements.txt", |
| 77 | + file=sys.stderr, |
| 78 | + ) |
| 79 | + return 1 |
| 80 | + |
| 81 | + build_status = build_docs() |
| 82 | + if build_status != 0: |
| 83 | + return build_status |
| 84 | + |
| 85 | + serve_docs(args.port) |
| 86 | + return 0 |
| 87 | + |
| 88 | + |
| 89 | +if __name__ == "__main__": |
| 90 | + raise SystemExit(main()) |
0 commit comments