• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3# Copyright (C) 2025 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 subprocess
17import zipfile
18import hashlib
19import os
20
21
22def install_dependencies(requirements_file):
23    try:
24        subprocess.check_call(["pip", "install", "-r", requirements_file])
25        print(f"install requirements.txt success")
26    except subprocess.CalledProcessError as e:
27        print(f"install dependence fail: {str(e)}")
28
29
30def check_exist_file():
31    file_list = []
32    file_list.append("AACommand07.hap")
33    file_list.append("libA_v10001.hsp")
34    file_list.append("libB_v10001.hsp")
35    url = "https://gitee.com/TaowerfulMAX/h2dij432sfa423o_debugfortest/releases/download/0.0.1-debug/package_0.0.1.zip"
36    expected_md5 = "ace0655b5f8dfb181544c92ae90f7bfc"
37    from testModule.utils import GP
38    for file in file_list:
39        if not os.path.exists(os.path.join(GP.local_path, file)):
40            if download_and_extract_zip(url, os.path.join(GP.local_path), expected_md5):
41                print(f"{file} File Download Success")
42                continue
43            else:
44                print(f"{file} File Download Failed")
45            print(f"No {file} File!")
46            print(f"请自行访问以下链接,下载package.zip中的安装包文件解压到当前脚本resource目录中,"
47                  "操作完成该步骤后重新执行prepare.py脚本。")
48            print("Please download from the url below and unzip package.zip to resource directory,"
49                  "please rerun after operation.")
50            print(f"url: {url}")
51            exit(1)
52
53
54def download_file(url, timeout=(10, 30)):
55    try:
56        import requests
57    except ModuleNotFoundError:
58        print("Please install requests module, command: [pip install requests]")
59        exit(1)
60    try:
61        response = requests.get(url, timeout=timeout)
62        response.raise_for_status()  # 将触发HTTPError,如果状态不是200
63        return True, response.content
64    except requests.exceptions.Timeout:
65        return False, "请求超时"
66    except requests.exceptions.HTTPError as err:
67        return False, f"HTTP错误:{err}"
68    except requests.exceptions.RequestException as e:
69        return False, f"请求异常:{e}"
70
71
72def save_to_file(content, filename):
73    with open(filename, 'wb') as f:
74        f.write(content)
75
76
77def extract_zip(filename, extract_to='.'):
78    with zipfile.ZipFile(filename, 'r') as zip_ref:
79        zip_ref.extractall(extract_to)
80
81
82def calculate_md5(filename):
83    hash_md5 = hashlib.md5()
84    try:
85        with open(filename, 'rb') as f:
86            for chunk in iter(lambda: f.read(4096), b""):
87                hash_md5.update(chunk)
88        return hash_md5.hexdigest()
89    except PermissionError:
90        return "PermissionError"
91    except FileNotFoundError:
92        return "FileNotFoundError"
93
94
95def download_and_extract_zip(url, extract_to='.', expected_md5=None):
96    # 下载ZIP文件
97    is_success, content = download_file(url)
98    if not is_success:
99        print(f"download_file failed: {content}")
100        return False
101    # 获取ZIP文件名
102    zip_filename = url.split('/')[-1]
103
104    # 写入本地文件
105    save_to_file(content, zip_filename)
106
107    # 如果提供了预期的MD5值,则进行校验
108    if expected_md5:
109        file_md5 = calculate_md5(zip_filename)
110        if file_md5 != expected_md5:
111            raise Exception(f"MD5校验失败:预期的MD5为{expected_md5},实际为{file_md5}")
112        else:
113            print("MD5校验成功")
114
115    # 解压ZIP文件
116    extract_zip(zip_filename, extract_to)
117
118    # 可选:删除ZIP文件
119    os.remove(zip_filename)
120    print(f"文件已解压到:{extract_to}")
121    return True
122
123
124def prepare():
125    install_dependencies("requirements.txt")
126    from testModule.utils import GP, gen_package_dir, update_source, prepare_source
127    test_path = os.path.join(os.getcwd(), "testModule")
128    if not os.path.exists(test_path):
129        print("testModule not exist")
130        return
131    GP.init()
132    prepare_source()
133    update_source()
134    check_exist_file()
135    gen_package_dir()
136
137
138if __name__ == "__main__":
139    prepare()