1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3# Copyright (c) 2024 Huawei Device Co., Ltd.
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#     http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16import argparse
17import json
18import os
19import time
20import stat
21import utils
22
23
24def _get_args():
25    parser = argparse.ArgumentParser(add_help=True)
26    parser.add_argument(
27        "-p", "--input_path",
28        default=r"./", type=str,
29        help="Path of source code",
30    )
31    parser.add_argument(
32        "-rp", "--root_path",
33        default=r"./", type=str,
34        help="Path of root",
35    )
36    parser.add_argument(
37        "-t", "--test",
38        default=1, type=int,
39        help="whether the target contains test type. default 1 , choices: 0 or 1 ",
40    )
41    args = parser.parse_args()
42    return args
43
44
45def _judge_type(element, deps_list: list):
46    if isinstance(element, dict):
47        for k, v in element.items():
48            _judge_type(v, deps_list)
49    elif isinstance(element, list):
50        for v in element:
51            _judge_type(v, deps_list)
52    elif isinstance(element, str):
53        deps_list.append(element)
54
55
56def _inner_kits_name(inner_kits_list, deps_list):
57    if inner_kits_list:
58        for k in inner_kits_list:
59            deps_list.append(k['name'])
60
61
62def _output_build_gn(deps_list, output_path, _test_check):
63    file_name = os.path.join(output_path, 'BUILD.gn')
64    flags = os.O_WRONLY | os.O_CREAT
65    modes = stat.S_IWUSR | stat.S_IRUSR
66    with os.fdopen(os.open(file_name, flags, modes), 'w') as f:
67        f.write('import("//build/ohos_var.gni")\n')
68        f.write('\n')
69        f.write('group("default") {\n')
70        if _test_check:
71            f.write('    testonly = true\n')
72        f.write('    deps = [\n')
73        for i in deps_list:
74            f.write(f"        \"{i}\",\n")
75        f.write('    ]\n')
76        f.write('}\n')
77
78
79def _get_bundle_path(source_code_path):
80    bundle_paths = dict()
81    for root, dirs, files in os.walk(source_code_path):
82        for file in files:
83            if file.endswith("bundle.json"):
84                bundle_paths.update({os.path.join(root, file): root})
85    return bundle_paths
86
87
88def _get_src_part_name(src_bundle_paths):
89    _name = ''
90    _path = ''
91    _bundle_path = ''
92    for src_bundle_path, v_path in src_bundle_paths.items():
93        src_bundle_json = utils.get_json(src_bundle_path)
94        part_name = ''
95        try:
96            part_name = src_bundle_json['component']['name']
97        except KeyError:
98            print(f'--get bundle json component name error--')
99        if part_name.endswith('_lite'):
100            pass
101        else:
102            _name = part_name
103            _bundle_path = src_bundle_path
104            _path = v_path
105    return _bundle_path, _path
106
107
108def main():
109    args = _get_args()
110    source_code_path = args.input_path
111    _test_check = args.test
112    if _test_check:
113        _target_list = ['inner_kits', 'inner_api', 'test']
114    else:
115        _target_list = ['inner_kits', 'inner_api']
116    deps_list = list()
117    bundle_paths = _get_bundle_path(source_code_path)
118    _bundle_path, dir_path = _get_src_part_name(bundle_paths)
119    bundle_json = utils.get_json(_bundle_path)
120    build_data = dict()
121    try:
122        build_data = bundle_json["component"]["build"]
123    except KeyError:
124        print(f'--get bundle json component build dict error--')
125    for ele in build_data.keys():
126        if ele not in ['inner_kits', 'test', 'inner_api']:
127            _judge_type(build_data[ele], deps_list)
128        elif ele in ['inner_kits', 'inner_api']:
129            inner_kits_list = build_data[ele]
130            _inner_kits_name(inner_kits_list, deps_list)
131        elif _test_check and ele == 'test':
132            inner_kits_list = build_data[ele]
133            for k in inner_kits_list:
134                deps_list.append(k)
135
136    output_path = os.path.join(args.root_path, 'out')
137    _output_build_gn(deps_list, output_path, _test_check)
138
139
140if __name__ == '__main__':
141    main()
142