1#!/usr/bin/env python3
2
3# Copyright (C) 2023 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
17import glob
18import json
19import os
20import shutil
21import subprocess
22import sys
23
24HEADER_TARGETS = [
25    '//libchrome:install_basever',
26    '//libchrome:install_buildflag_header',
27    '//libchrome:install_header',
28]
29
30
31def gn_desc(target):
32    """ Run gn desc on given target and return json output."""
33    return json.loads(subprocess.check_output(['gn', 'desc', '--format=json', 'out/Release', target]))
34
35
36def install_headers(target_dir):
37    """ Install headers into target directory. """
38    for target in HEADER_TARGETS:
39        desc = gn_desc(target)
40        install_config = desc[target]['metadata']['_install_config'][0]
41
42        # Make sure install path doesn't have absolute path
43        install_path = install_config['install_path'].lstrip('/')
44        try:
45            relative_to = install_config['tree_relative_to']
46        except:
47            relative_to = os.path.join(os.getcwd(), 'libchrome')
48        sources = install_config['sources']
49
50        # Generate rsync commands for each source mapping. Cp would require
51        # running makedir which we don't want to do.
52        for source in sources:
53            files = glob.glob(source, recursive=True)
54            for file in files:
55                target_file = os.path.join(target_dir, install_path, os.path.relpath(file, relative_to))
56                # Create dirs before copying
57                os.makedirs(os.path.dirname(target_file), exist_ok=True)
58                shutil.copyfile(file, target_file)
59
60
61def main():
62    if len(sys.argv) != 2:
63        raise Exception('Expecting 2 params, got {}'.format(sys.argv))
64        return
65
66    install_headers(sys.argv[1])
67
68
69if __name__ == '__main__':
70    main()
71