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