1# Copyright 2019 The Pigweed Authors 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); you may not 4# use this file except in compliance with the License. You may obtain a copy of 5# the License at 6# 7# https://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12# License for the specific language governing permissions and limitations under 13# the License. 14"""Renders HTML documentation using Sphinx.""" 15 16# TODO(frolv): Figure out a solution for installing all library dependencies 17# to run Sphinx and build RTD docs. 18 19import argparse 20import collections 21import json 22import os 23import shutil 24import subprocess 25import sys 26 27from pathlib import Path 28from typing import Dict, List, Tuple 29 30SCRIPT_HEADER: str = ''' 31██████╗ ██╗ ██████╗ ██╗ ██╗███████╗███████╗██████╗ ██████╗ ██████╗ ██████╗███████╗ 32██╔══██╗██║██╔════╝ ██║ ██║██╔════╝██╔════╝██╔══██╗ ██╔══██╗██╔═══██╗██╔════╝██╔════╝ 33██████╔╝██║██║ ███╗██║ █╗ ██║█████╗ █████╗ ██║ ██║ ██║ ██║██║ ██║██║ ███████╗ 34██╔═══╝ ██║██║ ██║██║███╗██║██╔══╝ ██╔══╝ ██║ ██║ ██║ ██║██║ ██║██║ ╚════██║ 35██║ ██║╚██████╔╝╚███╔███╔╝███████╗███████╗██████╔╝ ██████╔╝╚██████╔╝╚██████╗███████║ 36╚═╝ ╚═╝ ╚═════╝ ╚══╝╚══╝ ╚══════╝╚══════╝╚═════╝ ╚═════╝ ╚═════╝ ╚═════╝╚══════╝ 37''' 38 39 40def parse_args() -> argparse.Namespace: 41 """Parses command-line arguments.""" 42 43 parser = argparse.ArgumentParser(description=__doc__) 44 parser.add_argument('--sphinx-build-dir', 45 required=True, 46 help='Directory in which to build docs') 47 parser.add_argument('--conf', 48 required=True, 49 help='Path to conf.py file for Sphinx') 50 parser.add_argument('--gn-root', 51 required=True, 52 help='Root of the GN build tree') 53 parser.add_argument('--gn-gen-root', 54 required=True, 55 help='Root of the GN gen tree') 56 parser.add_argument('sources', 57 nargs='+', 58 help='Paths to the root level rst source files') 59 parser.add_argument('--out-dir', 60 required=True, 61 help='Output directory for rendered HTML docs') 62 parser.add_argument('--metadata', 63 required=True, 64 type=argparse.FileType('r'), 65 help='Metadata JSON file') 66 return parser.parse_args() 67 68 69def build_docs(src_dir: str, dst_dir: str) -> int: 70 """Runs Sphinx to render HTML documentation from a doc tree.""" 71 72 # TODO(frolv): Specify the Sphinx script from a prebuilts path instead of 73 # requiring it in the tree. 74 command = [ 75 'sphinx-build', '-W', '-b', 'html', '-d', f'{dst_dir}/help', src_dir, 76 f'{dst_dir}/html' 77 ] 78 return subprocess.call(command) 79 80 81def mkdir(dirname: str, exist_ok: bool = False) -> None: 82 """Wrapper around os.makedirs that prints the operation.""" 83 print(f'MKDIR {dirname}') 84 os.makedirs(dirname, exist_ok=exist_ok) 85 86 87def copy_doc_tree(args: argparse.Namespace) -> None: 88 """Copies doc source and input files into a build tree.""" 89 def build_path(path): 90 """Converts a source path to a filename in the build directory.""" 91 if path.startswith(args.gn_root): 92 path = os.path.relpath(path, args.gn_root) 93 elif path.startswith(args.gn_gen_root): 94 path = os.path.relpath(path, args.gn_gen_root) 95 96 return os.path.join(args.sphinx_build_dir, path) 97 98 source_files = json.load(args.metadata) 99 copy_paths = [build_path(f) for f in source_files] 100 101 mkdir(args.sphinx_build_dir) 102 for source_path in args.sources: 103 os.link(source_path, 104 f'{args.sphinx_build_dir}/{Path(source_path).name}') 105 os.link(args.conf, f'{args.sphinx_build_dir}/conf.py') 106 107 # Map of directory path to list of source and destination file paths. 108 dirs: Dict[str, List[Tuple[str, str]]] = collections.defaultdict(list) 109 110 for source_file, copy_path in zip(source_files, copy_paths): 111 dirname = os.path.dirname(copy_path) 112 dirs[dirname].append((source_file, copy_path)) 113 114 for directory, file_pairs in dirs.items(): 115 mkdir(directory, exist_ok=True) 116 for src, dst in file_pairs: 117 os.link(src, dst) 118 119 120def main() -> int: 121 """Script entry point.""" 122 123 args = parse_args() 124 125 # Clear out any existing docs for the target. 126 if os.path.exists(args.sphinx_build_dir): 127 shutil.rmtree(args.sphinx_build_dir) 128 129 # TODO(pwbug/164): Printing the header causes unicode problems on Windows. 130 # Disabled for now; re-enable once the root issue is fixed. 131 # print(SCRIPT_HEADER) 132 copy_doc_tree(args) 133 134 # Flush all script output before running Sphinx. 135 print('-' * 80, flush=True) 136 137 return build_docs(args.sphinx_build_dir, args.out_dir) 138 139 140if __name__ == '__main__': 141 sys.exit(main()) 142