• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3"""
4Copyright (c) 2020-2021 Huawei Device Co., Ltd.
5Licensed under the Apache License, Version 2.0 (the "License");
6you may not use this file except in compliance with the License.
7You may obtain a copy of the License at
8
9  http://www.apache.org/licenses/LICENSE-2.0
10
11Unless required by applicable law or agreed to in writing, software
12distributed under the License is distributed on an "AS IS" BASIS,
13WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14See the License for the specific language governing permissions and
15limitations under the License.
16"""
17
18import os
19import fnmatch
20import sys
21import argparse
22import distutils.dir_util as dir_util
23import distutils.file_util as file_util
24import json
25import subprocess
26
27# all sub system list, must be lowercase.
28_SUB_SYSTEM_LIST = [
29    "kernel",
30    "hiviewdfx",
31    "communication",
32    "security",
33    "updater",
34    "sstsutils",
35    "utils",
36    "uikit",
37    "multimedia",
38    "hdf",
39    "appexecfwk",
40    "distributedschedule",
41    "startup",
42    "sensors",
43    "sample",
44    "iothardware",
45    "open_posix_testsuite",
46    "validator",
47    "driver"
48]
49_GRADLE_PARAMS = ["SIGN_USER_NAME", "SIGN_PWD", "SIGN_MATERIAL_PATH",
50                 "SIGN_PROFILE", "SIGN_CERT_FILE"]
51
52_DEFAULT_USER_NAME = "user"
53_DEFAULT_PWD = "decrypt_pwd"
54
55
56def main():
57    parser = argparse.ArgumentParser()
58    parser.add_argument('--method_name', help='', required=True)
59    parser.add_argument('--arguments', help='',
60                        required=True)  # format key=value#key=value
61    args = parser.parse_args()
62    this_module = sys.modules[__name__]
63    method = getattr(this_module, args.method_name)
64    arguments = {}
65    for argument in args.arguments.split("#"):
66        key_value = argument.strip().split("=")
67        if len(key_value) != 2:
68            raise ValueError("Wrong format : '%s' % argument")
69        arguments.setdefault(key_value[0].strip(), key_value[1].strip())
70    method(**arguments)
71    return 0
72
73
74def read_file(input_file):
75    if not os.path.exists(input_file):
76        return ""
77
78    with open(input_file, 'r') as input_f:
79        content = input_f.read().strip()
80        return content
81
82
83def write_file(output_file, content, append):
84    file_dir = os.path.dirname(os.path.abspath(output_file))
85    if not os.path.exists(file_dir):
86        os.makedirs(file_dir)
87    mode = 'a+' if append else 'w'
88    with open(output_file, mode) as output_f:
89        output_f.write("%s\n" % content)
90
91
92def copy_file(output, sources="", source_dirs="", to_dir=True):
93    """
94    copy source files or source dir to output.
95    if sources is not empty, the output can be file(will be created
96    automatically)
97    or directory(must be exist).
98    :param output: If source_dirs is not empty, output must be directory.
99    :param sources: source files is separated by dot
100    :param source_dirs: source directory is separated by dot
101    :param to_dir: output is directory or not
102    :return:
103    """
104    if not sources and not source_dirs:
105        raise Exception(
106            "sources or source_dirs parameter must be specified one")
107    _output = output.strip()
108    _sources = sources.strip()
109    _source_dirs = source_dirs.strip()
110    _parent_output = os.path.dirname(_output)
111    try:
112        if to_dir and not os.path.exists(_output):
113            os.makedirs(_output)
114        if not to_dir and not os.path.exists(_parent_output):
115            os.makedirs(_parent_output)
116    except OSError:
117        if not os.path.isdir(_output):
118            raise
119    if _sources:
120        _copy_files(_sources.split(","), _output)
121
122    if _source_dirs:
123        _copy_dir(_source_dirs.split(","), _output)
124
125    return 0
126
127
128def _copy_files(sources, output):
129    for source_file in sources:
130        source_file = source_file.strip()
131        if os.path.isfile(source_file):
132            file_util.copy_file(source_file, output)
133
134
135def _copy_dir(sources, output):
136    for source_file in sources:
137        source_file = source_file.strip()
138        if os.path.isdir(source_file):
139            dir_util.copy_tree(source_file, output)
140
141
142def gen_suite_out(suite_output_prefix, suite_names, out_suffix):
143    outputs = []
144    _suite_output_prefix = suite_output_prefix.strip()
145    _dirname_suffix = out_suffix.strip().rstrip(os.sep)
146    for suite in suite_names.split(","):
147        path = "%s%s/%s" % (
148            _suite_output_prefix, suite.strip(), _dirname_suffix)
149        outputs.append(path)
150        print(path)
151    return outputs
152
153
154def get_subsystem_name(path):
155    subsystem_name = ""
156    for subsystem in _SUB_SYSTEM_LIST:
157        subsystem_path = "/%s/" % (subsystem)
158        _path = path.lower()
159        if subsystem_path in _path:
160            subsystem_name = subsystem
161            break
162        subsystem_path = "/%s/_lite" % (subsystem)
163        if subsystem_path in _path:
164            subsystem_name = subsystem
165            break
166    sys.stdout.write(subsystem_name)
167    return subsystem_name
168
169
170def get_modulename_by_buildtarget(module_list_file, build_target):
171    if not os.path.exists(module_list_file):
172        return ""
173    module_info_data = {}
174    with open(module_list_file, "r") as module_file:
175        module_info_data = json.load(module_file)
176    for module in module_info_data:
177        if module_info_data[module]["build_target_name"] == build_target:
178            sys.stdout.write(module)
179            return module
180    return ""
181
182
183def glob(path, filename_pattern):
184    files = []
185    for dir_path, _, files in os.walk(path):
186        for filename in fnmatch.filter(files, filename_pattern):
187            files.append(os.path.join(dir_path, filename))
188    return files
189
190
191def cmd_popen(cmd):
192    proc = subprocess.Popen(cmd)
193    proc.wait()
194    ret_code = proc.returncode
195    if ret_code != 0:
196        raise Exception("{} failed, return code is {}".format(cmd, ret_code))
197
198
199def build_js_hap(**kwargs):
200    if not check_env():
201        return
202    if "project_path" not in kwargs or "out_put_dir" not in kwargs:
203        return
204    project_path = kwargs.get("project_path")
205    gradle_dir = os.path.join(project_path, "gradle")
206    os.chdir(gradle_dir)
207    build_clean = ["gradle", "clean"]
208    cmd_popen(build_clean)
209    if "SIGN_USER_NAME" not in kwargs:
210        pass
211
212    gradle_parm_cmd = get_gradle_cmd(**kwargs)
213    # build sign debug hap
214    build_hap_cmd = ["gradle"]
215    build_hap_cmd.extend(gradle_parm_cmd)
216    build_hap_cmd.append("entry:aD")
217    cmd_popen(build_hap_cmd)
218
219    # build sign ohos test hap
220    build_test_hap_cmd = ["gradle"]
221    build_test_hap_cmd.extend(gradle_parm_cmd)
222    build_test_hap_cmd.append("entry:aDOT")
223    cmd_popen(build_test_hap_cmd)
224
225    gradle_output_dir = os.path.join(gradle_dir, "entry", "build", "outputs")
226    if not os.path.exists(gradle_output_dir):
227        return
228    out_put_dir = kwargs.get("out_put_dir")
229    if not os.path.exists(out_put_dir):
230        os.makedirs(out_put_dir)
231    hap_name = kwargs.get("hap_name")
232    for root, _, files in os.walk(gradle_output_dir):
233        for file in files:
234            if file.endswith(".hap") and "unsigned" not in file:
235                if "debugOhosTest" in root:
236                    target_file = "{}_OhosTest.hap".format(hap_name)
237                else:
238                    target_file = "{}.hap".format(hap_name)
239                file_util.copy_file(os.path.join(root, file),
240                                    os.path.join(out_put_dir.rstrip(','),
241                                                 target_file))
242
243
244def get_gradle_cmd(**kwargs):
245    cmd = []
246    if kwargs:
247        kwargs.setdefault("SIGN_USER_NAME", _DEFAULT_USER_NAME)
248        kwargs.setdefault("SIGN_PWD", _DEFAULT_PWD)
249    for param in _GRADLE_PARAMS:
250        if param in kwargs:
251            cmd.append("-P{}={}".format(param, kwargs.get(param)))
252    return cmd
253
254
255def check_env():
256    """
257    check all the env for js hap build
258    return: return true if all env ready, otherwise return false
259    """
260    env_list = ['OHOS_SDK_HOME']
261    for env in env_list:
262        if not os.environ.get(env):
263            print("the env {} not set, skip build!".format(env))
264            return False
265    else:
266        return True
267
268
269if __name__ == '__main__':
270    sys.exit(main())
271