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', **kwargs): 35 useful_info_pattern = re.compile(r'\[\d+/\d+\].+') 36 is_log_filter = kwargs.pop('log_filter', False) 37 if '' in cmd: 38 cmd.remove('') 39 if not os.path.exists(os.path.dirname(log_path)): 40 os.makedirs(os.path.dirname(log_path), exist_ok=True) 41 with open(log_path, 'at', encoding='utf-8') as log_file: 42 process = subprocess.Popen(cmd, 43 stdout=subprocess.PIPE, 44 stderr=subprocess.STDOUT, 45 encoding='utf-8', 46 errors='ignore', 47 **kwargs) 48 for line in iter(process.stdout.readline, ''): 49 if is_log_filter: 50 info = re.findall(useful_info_pattern, line) 51 if len(info): 52 LogUtil.hb_info(info[0]) 53 else: 54 LogUtil.hb_info(line) 55 log_file.write(line) 56 57 process.wait() 58 ret_code = process.returncode 59 60 if ret_code != 0: 61 if is_log_filter: 62 LogUtil.get_failed_log(log_path) 63 raise OHOSException( 64 'Please check build log in {}'.format(log_path)) 65 66 @staticmethod 67 def get_current_time(time_type='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