1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3# Copyright (c) 2021 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 sys
18import os
19import shutil
20import zipfile
21
22sys.path.append(
23    os.path.dirname(os.path.dirname(os.path.dirname(
24        os.path.abspath(__file__)))))
25from scripts.util import build_utils  # noqa: E402
26from scripts.util.file_utils import read_json_file  # noqa: E402
27
28
29def get_source_from_module_info_file(module_info_file: str):
30    data = read_json_file(module_info_file)
31    if data is None:
32        raise Exception("read file '{}' failed.".format(module_info_file))
33    source = data.get('source')
34    notice = data.get('notice')
35    return source, notice
36
37
38def do_copy_and_stamp(copy_infos: dict, options, depfile_deps: list):
39    notice_tuples = []
40    for cp_info in copy_infos:
41        source = cp_info.get('source')
42        dest = cp_info.get('dest')
43        notice = cp_info.get('notice')
44        install_dir = cp_info.get('install_dir')
45        if os.path.isdir(source):
46            if os.listdir(source):
47                files = build_utils.get_all_files(source)
48                if files:
49                    shutil.copytree(source, dest, dirs_exist_ok=True)
50                    depfile_deps.update(build_utils.get_all_files(source))
51                else:
52                    # Skip empty directories.
53                    depfile_deps.add(source)
54        else:
55            dest_dir = os.path.dirname(dest)
56            os.makedirs(dest_dir, exist_ok=True)
57            shutil.copy2(source, dest)
58            depfile_deps.add(source)
59        if notice and os.path.exists(notice):
60            depfile_deps.add(notice)
61            if notice.endswith('.zip'):
62                suffix = ".zip"
63            else:
64                suffix = ".txt"
65            if os.path.isdir(source):
66                notice_dest = os.path.join('{}{}'.format(install_dir, suffix))
67            else:
68                notice_dest = os.path.join(
69                    install_dir, '{}{}'.format(os.path.basename(source),
70                                               suffix))
71            notice_tuples.append((notice_dest, notice))
72    if (options.enable_archive_sdk):
73        build_utils.zip_dir(options.sdk_output_archive,
74                            options.archive_dir,
75                            compress_fn=lambda _: zipfile.ZIP_DEFLATED,
76                            zip_prefix_path=options.zip_prefix_path)
77        with zipfile.ZipFile(options.notice_output_archive, 'w') as outfile:
78            for zip_path, fs_path in notice_tuples:
79                build_utils.add_to_zip_hermetic(outfile, zip_path, src_path=fs_path)
80    build_utils.write_depfile(options.depfile,
81                              options.sdk_output_archive,
82                              depfile_deps,
83                              add_pydeps=False)
84
85
86def main():
87    parser = argparse.ArgumentParser()
88    build_utils.add_depfile_option(parser)
89
90    parser.add_argument('--sdk-modules-desc-file', required=True)
91    parser.add_argument('--sdk-archive-paths-file', required=True)
92    parser.add_argument('--dest-dir', required=True)
93    parser.add_argument('--archive-dir', required=True)
94    parser.add_argument('--zip-prefix-path', default=None)
95    parser.add_argument('--notice-output-archive', required=True)
96    parser.add_argument('--sdk-output-archive', required=True)
97    parser.add_argument('--enable-archive-sdk', help='archive sdk')
98
99    options = parser.parse_args()
100
101    sdk_modules_desc_file = options.sdk_modules_desc_file
102    sdk_out_dir = options.dest_dir
103    sdk_archive_paths_file = options.sdk_archive_paths_file
104
105    sdk_modules = read_json_file(sdk_modules_desc_file)
106    if sdk_modules is None:
107        sdk_modules = []
108
109    archive_paths = read_json_file(sdk_archive_paths_file)
110    if archive_paths is None:
111        archive_paths = []
112
113    depfile_deps = set(
114        [options.sdk_modules_desc_file, options.sdk_archive_paths_file])
115    copy_infos = []
116    for module in sdk_modules:
117        cp_info = {}
118        sdk_label = module.get('label')
119        module_info_file = module.get('module_info_file')
120        source, notice = get_source_from_module_info_file(module_info_file)
121        cp_info['source'] = source
122        cp_info['notice'] = notice
123        depfile_deps.add(module_info_file)
124
125        for item in archive_paths:
126            if sdk_label == item.get('label'):
127                dest = os.path.join(sdk_out_dir, item.get('install_dir'),
128                                    os.path.basename(source))
129                break
130        cp_info['dest'] = dest
131        cp_info['install_dir'] = item.get('install_dir')
132        copy_infos.append(cp_info)
133
134    do_copy_and_stamp(copy_infos, options, depfile_deps)
135
136
137if __name__ == '__main__':
138    sys.exit(main())
139