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, Optional, 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 parser.add_argument('--google-analytics-id', 67 const=None, 68 help='Enables Google Analytics with the provided ID') 69 return parser.parse_args() 70 71 72def build_docs(src_dir: str, 73 dst_dir: str, 74 google_analytics_id: Optional[str] = None) -> int: 75 """Runs Sphinx to render HTML documentation from a doc tree.""" 76 77 # TODO(frolv): Specify the Sphinx script from a prebuilts path instead of 78 # requiring it in the tree. 79 command = ['sphinx-build', '-W', '-b', 'html', '-d', f'{dst_dir}/help'] 80 81 if google_analytics_id is not None: 82 command.append(f'-Dgoogle_analytics_id={google_analytics_id}') 83 84 command.extend([src_dir, f'{dst_dir}/html']) 85 86 return subprocess.call(command) 87 88 89def copy_doc_tree(args: argparse.Namespace) -> None: 90 """Copies doc source and input files into a build tree.""" 91 def build_path(path): 92 """Converts a source path to a filename in the build directory.""" 93 if path.startswith(args.gn_root): 94 path = os.path.relpath(path, args.gn_root) 95 elif path.startswith(args.gn_gen_root): 96 path = os.path.relpath(path, args.gn_gen_root) 97 98 return os.path.join(args.sphinx_build_dir, path) 99 100 source_files = json.load(args.metadata) 101 copy_paths = [build_path(f) for f in source_files] 102 103 os.makedirs(args.sphinx_build_dir) 104 for source_path in args.sources: 105 os.link(source_path, 106 f'{args.sphinx_build_dir}/{Path(source_path).name}') 107 os.link(args.conf, f'{args.sphinx_build_dir}/conf.py') 108 109 # Map of directory path to list of source and destination file paths. 110 dirs: Dict[str, List[Tuple[str, str]]] = collections.defaultdict(list) 111 112 for source_file, copy_path in zip(source_files, copy_paths): 113 dirname = os.path.dirname(copy_path) 114 dirs[dirname].append((source_file, copy_path)) 115 116 for directory, file_pairs in dirs.items(): 117 os.makedirs(directory, exist_ok=True) 118 for src, dst in file_pairs: 119 os.link(src, dst) 120 121 122def main() -> int: 123 """Script entry point.""" 124 125 args = parse_args() 126 127 # Clear out any existing docs for the target. 128 if os.path.exists(args.sphinx_build_dir): 129 shutil.rmtree(args.sphinx_build_dir) 130 131 # TODO(pwbug/164): Printing the header causes unicode problems on Windows. 132 # Disabled for now; re-enable once the root issue is fixed. 133 # print(SCRIPT_HEADER) 134 copy_doc_tree(args) 135 136 # Flush all script output before running Sphinx. 137 print('-' * 80, flush=True) 138 139 return build_docs(args.sphinx_build_dir, args.out_dir, 140 args.google_analytics_id) 141 142 143if __name__ == '__main__': 144 sys.exit(main()) 145