#!/usr/bin/env python3 from base64 import b64decode from contextlib import closing from http.client import HTTPSConnection from io import StringIO from json import load from os import PathLike from pathlib import Path from time import sleep INDEX_HBS_DOMAIN = "api.github.com" INDEX_HBS_PORT = 443 INDEX_HBS_PROTO = "GET" INDEX_HBS_PATH = "/repos/rust-lang/mdBook/contents/src/theme/index.hbs?ref=v0.4.40" INDEX_HBS_DATA = None INDEX_HBS_HEADERS = { "user-agent": "Update index.hbs for +https://github.com/askama-rs/askama", } SIDEBAR_STYLE = 'style="display:flex; flex-direction:column"' SCROLLBOX_END = r"""
""" TOC_START = '
' TOC_END = "
" SIDEBAR_END = r""" """ def update_theme(target: PathLike) -> None: for i in reversed(range(3)): with closing(HTTPSConnection(INDEX_HBS_DOMAIN, INDEX_HBS_PORT)) as conn: conn.request(INDEX_HBS_PROTO, INDEX_HBS_PATH, INDEX_HBS_DATA, INDEX_HBS_HEADERS) res = conn.getresponse() if res.status == 200: data = load(res) break if i != 0: sleep(1.0) else: raise Exception(f"Status={res.status!r}") if data["encoding"] != "base64": raise Exception(f'Encoding={data["encoding"]!r}') input_f = StringIO(str(b64decode(data["content"]), "UTF-8")) output_f = StringIO() _, revision = data["git_url"].rsplit("/", 1) print("Source revision:", revision) state = "before-sidebar" for line in input_f: match state: case "before-sidebar" if '": indent = line[: len(line) - len(line.lstrip())] for s in SIDEBAR_END.splitlines(): if s: print(indent, s, sep=" ", file=output_f) state = "after-sidebar" output_f.write(line) if state != "after-sidebar": raise Exception(f"state={state!r}") output_f.seek(0, 0) with open(target, "wt") as f: print(output_f.read(), end="", file=f) if __name__ == "__main__": update_theme(Path(__file__).absolute().parent / "theme" / "index.hbs")