1#!/usr/bin/env python3 2# -*- coding: utf-8 -*- 3 4# 5# Copyright (c) 2023 Huawei Device Co., Ltd. 6# Licensed under the Apache License, Version 2.0 (the "License"); 7# you may not use this file except in compliance with the License. 8# You may obtain a copy of the License at 9# 10# http://www.apache.org/licenses/LICENSE-2.0 11# 12# Unless required by applicable law or agreed to in writing, software 13# distributed under the License is distributed on an "AS IS" BASIS, 14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15# See the License for the specific language governing permissions and 16# limitations under the License. 17# 18 19import os 20import re 21import subprocess 22 23from datetime import datetime 24 25from util.log_util import LogUtil 26from helper.noInstance import NoInstance 27from exceptions.ohos_exception import OHOSException 28from containers.status import throw_exception 29 30 31class SystemUtil(metaclass=NoInstance): 32 33 @staticmethod 34 def exec_command(cmd: list, log_path='out/build.log', exec_env=None, log_mode='normal', **kwargs): 35 useful_info_pattern = re.compile(r'\[\d+/\d+\].+') 36 is_log_filter = kwargs.pop('log_filter', False) 37 if log_mode == 'silent': 38 is_log_filter = True 39 if '' in cmd: 40 cmd.remove('') 41 if not os.path.exists(os.path.dirname(log_path)): 42 os.makedirs(os.path.dirname(log_path), exist_ok=True) 43 with open(log_path, 'at', encoding='utf-8') as log_file: 44 process = subprocess.Popen(cmd, 45 stdout=subprocess.PIPE, 46 stderr=subprocess.STDOUT, 47 encoding='utf-8', 48 errors='ignore', 49 env=exec_env, 50 **kwargs) 51 for line in iter(process.stdout.readline, ''): 52 log_file.write(line) 53 if is_log_filter: 54 info = re.findall(useful_info_pattern, line) 55 if len(info): 56 LogUtil.hb_info(info[0], mode=log_mode) 57 else: 58 LogUtil.hb_info(line) 59 60 process.wait() 61 ret_code = process.returncode 62 63 if ret_code != 0: 64 LogUtil.get_failed_log(log_path) 65 66 @staticmethod 67 def get_current_time(time_type: str='default'): 68 if time_type == 'timestamp': 69 return int(datetime.utcnow().timestamp() * 1000) 70 if time_type == 'datetime': 71 return datetime.now().strftime('%Y-%m-%d %H:%M:%S') 72 return datetime.now().replace(microsecond=0) 73 74 75class ExecEnviron: 76 def __init__(self): 77 self._env = None 78 79 @property 80 def allenv(self): 81 return self._env 82 83 @property 84 def allkeys(self): 85 if self._env is None: 86 return [] 87 return list(self._env.keys()) 88 89 def initenv(self): 90 self._env = os.environ.copy() 91 92 def allow(self, allowed_vars: list): 93 if self._env is not None: 94 allowed_env = {k: v for k, v in self._env.items() if k in allowed_vars} 95 self._env = allowed_env 96