• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 sys
21import re
22import subprocess
23
24from datetime import datetime
25
26from util.log_util import LogUtil
27from helper.noInstance import NoInstance
28from exceptions.ohos_exception import OHOSException
29from containers.status import throw_exception
30
31
32class SystemUtil(metaclass=NoInstance):
33
34    @staticmethod
35    def exec_command(cmd: list, log_path='out/build.log', exec_env=None, log_mode='normal', **kwargs):
36        useful_info_pattern = re.compile(r'\[\d+/\d+\].+')
37        is_log_filter = kwargs.pop('log_filter', False)
38        if log_mode == 'silent':
39            is_log_filter = True
40        if '' in cmd:
41            cmd.remove('')
42        if not os.path.exists(os.path.dirname(log_path)):
43            os.makedirs(os.path.dirname(log_path), exist_ok=True)
44        if sys.argv[1] == 'build' and len(sys.argv) == 5 and sys.argv[4] in ['-t', '-test']:
45            cmd.append(sys.argv[4])
46        with open(log_path, 'at', encoding='utf-8') as log_file:
47            LogUtil.hb_info("start run hpm command")
48            process = subprocess.Popen(cmd,
49                                       stdout=subprocess.PIPE,
50                                       stderr=subprocess.STDOUT,
51                                       encoding='utf-8',
52                                       env=exec_env,
53                                       **kwargs)
54            for line in iter(process.stdout.readline, ''):
55                log_file.write(line)
56                if is_log_filter:
57                    info = re.findall(useful_info_pattern, line)
58                    if len(info):
59                        LogUtil.hb_info(info[0], mode=log_mode)
60                else:
61                    LogUtil.hb_info(line)
62
63        process.wait()
64        LogUtil.hb_info("end hpm command")
65        ret_code = process.returncode
66
67        if ret_code != 0:
68            LogUtil.get_failed_log(log_path)
69
70    @staticmethod
71    def get_current_time(time_type: str='default'):
72        if time_type == 'timestamp':
73            return int(datetime.utcnow().timestamp() * 1000)
74        if time_type == 'datetime':
75            return datetime.now().strftime('%Y-%m-%d %H:%M:%S')
76        return datetime.now().replace(microsecond=0)
77
78
79class ExecEnviron:
80    def __init__(self):
81        self._env = None
82
83    @property
84    def allenv(self):
85        return self._env
86
87    @property
88    def allkeys(self):
89        if self._env is None:
90            return []
91        return list(self._env.keys())
92
93    def initenv(self):
94        self._env = os.environ.copy()
95
96    def allow(self, allowed_vars: list):
97        if self._env is not None:
98            allowed_env = {k: v for k, v in self._env.items() if k in allowed_vars}
99            self._env = allowed_env
100