import os
import json
import importlib
import re
import shutil
from hb.helper.no_instance import NoInstance
from exceptions.ohos_exception import OHOSException
class IoUtil(metaclass=NoInstance):
@staticmethod
def read_json_file(input_file: str) -> dict:
if not os.path.isfile(input_file):
raise OHOSException(f'{input_file} not found', '0008')
try:
with open(input_file, 'rb') as input_f:
data = json.load(input_f)
return data
except json.JSONDecodeError as e:
print(f'Error reading JSON file {input_file}')
raise e
@staticmethod
def dump_json_file(dump_file: str, json_data: dict or list):
with open(dump_file, 'wt', encoding='utf-8') as json_file:
json.dump(json_data, json_file, ensure_ascii=False, indent=2)
@staticmethod
def read_file(file_path: str):
if not os.path.exists(file_path):
raise OHOSException(
"file '{}' doesn't exist.".format(file_path), '0009')
data = None
with open(file_path, 'r') as input_f:
data = input_f.read()
return data
@staticmethod
def read_yaml_file(input_file: str):
if not os.path.isfile(input_file):
raise OHOSException(f'{input_file} not found', '0010')
yaml = importlib.import_module('yaml')
with open(input_file, 'rt', encoding='utf-8') as yaml_file:
try:
return yaml.safe_load(yaml_file)
except yaml.YAMLError as exc:
if hasattr(exc, 'problem_mark'):
mark = exc.problem_mark
raise OHOSException(f'{input_file} load failed, error line:'
f' {mark.line + 1}:{mark.column + 1}', '0011')
else:
raise OHOSException(f'{input_file} load failed', '0011')
@staticmethod
def copy_file(src: str, dst: str):
return shutil.copy(src, dst)