|
| 1 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +# or more contributor license agreements. See the NOTICE file |
| 3 | +# distributed with this work for additional information |
| 4 | +# regarding copyright ownership. The ASF licenses this file |
| 5 | +# to you under the Apache License, Version 2.0 (the |
| 6 | +# "License"); you may not use this file except in compliance |
| 7 | +# with the License. You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, |
| 12 | +# software distributed under the License is distributed on an |
| 13 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +# KIND, either express or implied. See the License for the |
| 15 | +# specific language governing permissions and limitations |
| 16 | +# under the License. |
| 17 | + |
| 18 | +"""Convert sphinx-multiversion metadata into the version switcher JSON. |
| 19 | +
|
| 20 | +Usage: |
| 21 | + python docs/tools/write_versions_json.py <html_root> [--base-url /] |
| 22 | +""" |
| 23 | + |
| 24 | +from __future__ import annotations |
| 25 | + |
| 26 | +import argparse |
| 27 | +import json |
| 28 | +from datetime import datetime |
| 29 | +from pathlib import Path |
| 30 | + |
| 31 | +from packaging import version as pkg_version |
| 32 | + |
| 33 | +ROOT_VERSION = "main" |
| 34 | +DEFAULT_BASE_URL = "/" |
| 35 | +METADATA_NAME = "versions_metadata.json" |
| 36 | + |
| 37 | + |
| 38 | +def _parse_creatordate(raw: str) -> datetime: |
| 39 | + try: |
| 40 | + return datetime.strptime(raw, "%Y-%m-%d %H:%M:%S %z") |
| 41 | + except Exception: |
| 42 | + return datetime.min.replace(tzinfo=None) |
| 43 | + |
| 44 | + |
| 45 | +def _load_versions(metadata_path: Path) -> list[dict[str, object]]: |
| 46 | + metadata = json.loads(metadata_path.read_text(encoding="utf-8")) |
| 47 | + versions = [] |
| 48 | + for name, entry in metadata.items(): |
| 49 | + version_label = entry.get("version") or name |
| 50 | + if version_label in {"0.0.0", "0+unknown"}: |
| 51 | + version_label = name |
| 52 | + versions.append( |
| 53 | + { |
| 54 | + "name": name, |
| 55 | + "version": version_label, |
| 56 | + "is_released": bool(entry.get("is_released")), |
| 57 | + "creatordate": _parse_creatordate(entry.get("creatordate", "")), |
| 58 | + } |
| 59 | + ) |
| 60 | + return versions |
| 61 | + |
| 62 | + |
| 63 | +def _pick_preferred(versions: list[dict[str, object]], latest: str) -> str: |
| 64 | + released = [v for v in versions if v["is_released"]] |
| 65 | + if released: |
| 66 | + return max(released, key=lambda v: v["creatordate"])["name"] |
| 67 | + for v in versions: |
| 68 | + if v["name"] == latest: |
| 69 | + return latest |
| 70 | + return versions[0]["name"] |
| 71 | + |
| 72 | + |
| 73 | +def _to_switcher( |
| 74 | + versions: list[dict[str, object]], preferred_name: str, base_url: str |
| 75 | +) -> list[dict[str, object]]: |
| 76 | + base = base_url.rstrip("/") |
| 77 | + main_entry: dict[str, object] | None = None |
| 78 | + tag_entries: list[dict[str, object]] = [] |
| 79 | + |
| 80 | + for v in versions: |
| 81 | + entry = { |
| 82 | + "name": v["name"], |
| 83 | + "version": v["version"], |
| 84 | + "url": f"{base}/{v['name']}/" if base else f"/{v['name']}/", |
| 85 | + "preferred": v["name"] == preferred_name, |
| 86 | + } |
| 87 | + if v["name"] == "main": |
| 88 | + main_entry = entry |
| 89 | + else: |
| 90 | + tag_entries.append(entry) |
| 91 | + |
| 92 | + def _sort_key(entry: dict[str, object]) -> pkg_version.Version: |
| 93 | + name = str(entry["name"]) |
| 94 | + label = name[1:] if name.startswith("v") else name |
| 95 | + try: |
| 96 | + return pkg_version.parse(label) |
| 97 | + except Exception: |
| 98 | + return pkg_version.parse("0") |
| 99 | + |
| 100 | + tag_entries.sort(key=_sort_key, reverse=True) |
| 101 | + |
| 102 | + ordered = [] |
| 103 | + if main_entry: |
| 104 | + ordered.append(main_entry) |
| 105 | + ordered.extend(tag_entries) |
| 106 | + return ordered |
| 107 | + |
| 108 | + |
| 109 | +def _write_root_index(html_root: Path, target_version: str, base_url: str) -> str: |
| 110 | + base = base_url.rstrip("/") or "/" |
| 111 | + target = f"{base}/{target_version}/" if base != "/" else f"/{target_version}/" |
| 112 | + html_root.mkdir(parents=True, exist_ok=True) |
| 113 | + index_path = html_root / "index.html" |
| 114 | + index_path.write_text( |
| 115 | + "\n".join( |
| 116 | + [ |
| 117 | + "<!DOCTYPE html>", |
| 118 | + '<meta charset="utf-8" />', |
| 119 | + "<title>tvm-ffi docs</title>", |
| 120 | + f'<meta http-equiv="refresh" content="0; url={target}" />', |
| 121 | + "<script>", |
| 122 | + f"location.replace('{target}');", |
| 123 | + "</script>", |
| 124 | + f'<p>Redirecting to <a href="{target}">{target}</a>.</p>', |
| 125 | + ] |
| 126 | + ), |
| 127 | + encoding="utf-8", |
| 128 | + ) |
| 129 | + return target |
| 130 | + |
| 131 | + |
| 132 | +def main() -> int: |
| 133 | + """Entrypoint.""" |
| 134 | + parser = argparse.ArgumentParser() |
| 135 | + parser.add_argument( |
| 136 | + "html_root", |
| 137 | + type=Path, |
| 138 | + help="Root of the built HTML output (expects _static/versions_metadata.json inside)", |
| 139 | + ) |
| 140 | + parser.add_argument( |
| 141 | + "--base-url", |
| 142 | + default=DEFAULT_BASE_URL, |
| 143 | + help="Base URL prefix (leading slash, no trailing slash) for version links, e.g. '/' or '/ffi'", |
| 144 | + ) |
| 145 | + args = parser.parse_args() |
| 146 | + |
| 147 | + html_root = args.html_root |
| 148 | + metadata_path = html_root / "_static" / METADATA_NAME |
| 149 | + metadata_path.parent.mkdir(parents=True, exist_ok=True) |
| 150 | + |
| 151 | + versions = _load_versions(metadata_path) |
| 152 | + preferred_name = _pick_preferred(versions, ROOT_VERSION) |
| 153 | + output = _to_switcher(versions, preferred_name, args.base_url) |
| 154 | + |
| 155 | + out_path = html_root / "_static" / "versions.json" |
| 156 | + out_path.parent.mkdir(parents=True, exist_ok=True) |
| 157 | + out_path.write_text(json.dumps(output, indent=2), encoding="utf-8") |
| 158 | + print(f"Wrote version switcher data for {len(output)} entries to {out_path}") |
| 159 | + |
| 160 | + target = _write_root_index(html_root, ROOT_VERSION, args.base_url) |
| 161 | + print(f"Wrote root index redirect to {target}") |
| 162 | + return 0 |
| 163 | + |
| 164 | + |
| 165 | +if __name__ == "__main__": |
| 166 | + raise SystemExit(main()) |
0 commit comments