• 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 helper.noInstance 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
36        with open(input_file, 'rb') as input_f:
37            data = json.load(input_f)
38            return data
39
40    @staticmethod
41    def dump_json_file(dump_file: str, json_data: dict or list):
42        with open(dump_file, 'wt', encoding='utf-8') as json_file:
43            json.dump(json_data, json_file, ensure_ascii=False, indent=2)
44
45    @staticmethod
46    def read_file(file_path: str):
47        if not os.path.exists(file_path):
48            raise OHOSException(
49                "file '{}' doesn't exist.".format(file_path), '0009')
50        data = None
51        with open(file_path, 'r') as input_f:
52            data = input_f.read()
53        return data
54
55    @staticmethod
56    def read_yaml_file(input_file: str):
57        if not os.path.isfile(input_file):
58            raise OHOSException(f'{input_file} not found', '0010')
59
60        yaml = importlib.import_module('yaml')
61        with open(input_file, 'rt', encoding='utf-8') as yaml_file:
62            try:
63                return yaml.safe_load(yaml_file)
64            except yaml.YAMLError as exc:
65                if hasattr(exc, 'problem_mark'):
66                    mark = exc.problem_mark
67                    raise OHOSException(f'{input_file} load failed, error line:'
68                                        f' {mark.line + 1}:{mark.column + 1}', '0011')
69                else:
70                    raise OHOSException(f'{input_file} load failed', '0011')
71
72    @staticmethod
73    def copy_file(src: str, dst: str):
74        return shutil.copy(src, dst)
75