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