• 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 json
21import importlib
22import re
23import shutil
24
25from hb.helper.no_instance import NoInstance
26from exceptions.ohos_exception import OHOSException
27
28
29class IoUtil(metaclass=NoInstance):
30
31    @staticmethod
32    def read_json_file(input_file: str) -> dict:
33        if not os.path.isfile(input_file):
34            raise OHOSException(f'{input_file} not found', '0008')
35        try:
36            with open(input_file, 'rb') as input_f:
37                data = json.load(input_f)
38                return data
39        except json.JSONDecodeError as e:
40            print(f'Error reading JSON file {input_file}')
41            raise e
42
43    @staticmethod
44    def dump_json_file(dump_file: str, json_data: dict or list):
45        with open(dump_file, 'wt', encoding='utf-8') as json_file:
46            json.dump(json_data, json_file, ensure_ascii=False, indent=2)
47
48    @staticmethod
49    def read_file(file_path: str):
50        if not os.path.exists(file_path):
51            raise OHOSException(
52                "file '{}' doesn't exist.".format(file_path), '0009')
53        data = None
54        with open(file_path, 'r') as input_f:
55            data = input_f.read()
56        return data
57
58    @staticmethod
59    def read_yaml_file(input_file: str):
60        if not os.path.isfile(input_file):
61            raise OHOSException(f'{input_file} not found', '0010')
62
63        yaml = importlib.import_module('yaml')
64        with open(input_file, 'rt', encoding='utf-8') as yaml_file:
65            try:
66                return yaml.safe_load(yaml_file)
67            except yaml.YAMLError as exc:
68                if hasattr(exc, 'problem_mark'):
69                    mark = exc.problem_mark
70                    raise OHOSException(f'{input_file} load failed, error line:'
71                                        f' {mark.line + 1}:{mark.column + 1}', '0011')
72                else:
73                    raise OHOSException(f'{input_file} load failed', '0011')
74
75    @staticmethod
76    def copy_file(src: str, dst: str):
77        return shutil.copy(src, dst)
78