1#!/usr/bin/env python3
2#
3# Copyright (C) 2020 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# 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, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17"""Generates the NDK API docs for local viewing.
18
19Note that the local docs will not exactly match the docs that are uploaded to
20devsite. The theming is different and the per-file view is not available.
21Ensure that your documentation is accessible from the module view or it will
22not be discoverable on devsite.
23"""
24import argparse
25import os
26from pathlib import Path
27import shutil
28import subprocess
29import sys
30
31THIS_DIR = Path(__file__).resolve().parent
32ANDROID_TOP = THIS_DIR.parents[2]
33
34
35def check_environment() -> None:
36    """Validates that we have everything we need from the environment."""
37    if shutil.which('doxygen') is None:
38        sys.exit('Doxygen not found. Run `sudo apt install doxygen`.')
39
40    if 'ANDROID_PRODUCT_OUT' not in os.environ:
41        sys.exit('Could not find ANDROID_PRODUCT_OUT. Run lunch.')
42
43
44def build_ndk() -> None:
45    """Builds the NDK sysroot."""
46    subprocess.run(["build/soong/soong_ui.bash", "--make-mode", "ndk"],
47                   cwd=ANDROID_TOP,
48                   check=True)
49
50
51def generate_docs() -> None:
52    """Generates the NDK API reference."""
53    product_out = Path(os.environ['ANDROID_PRODUCT_OUT'])
54    out_dir = product_out.parents[1] / 'common/ndk-docs'
55    html_dir = out_dir / 'html'
56    input_dir = product_out.parents[2] / 'soong/ndk/sysroot/usr/include'
57    doxyfile_template = ANDROID_TOP / 'frameworks/native/docs/Doxyfile'
58    out_dir.mkdir(parents=True, exist_ok=True)
59    doxyfile = out_dir / 'Doxyfile'
60
61    doxyfile_contents = doxyfile_template.read_text()
62    doxyfile_contents += f'\nINPUT={input_dir}\nHTML_OUTPUT={html_dir}'
63    doxyfile.write_text(doxyfile_contents)
64
65    subprocess.run(['doxygen', str(doxyfile)], cwd=ANDROID_TOP, check=True)
66    index = html_dir / 'index.html'
67    print(f'Generated NDK API documentation to {index.as_uri()}')
68
69
70def parse_args() -> argparse.Namespace:
71    """Parses command line arguments."""
72    parser = argparse.ArgumentParser(description=sys.modules[__name__].__doc__)
73    return parser.parse_args()
74
75
76def main() -> None:
77    """Program entry point."""
78    _ = parse_args()
79    check_environment()
80    build_ndk()
81    generate_docs()
82
83
84if __name__ == '__main__':
85    main()
86