2024-05-24 12:08:12 +08:00
|
|
|
import logging
|
2024-07-29 10:32:11 +08:00
|
|
|
from typing import Any
|
2024-05-24 12:08:12 +08:00
|
|
|
|
|
|
|
import yaml
|
|
|
|
from yaml import YAMLError
|
|
|
|
|
2024-06-12 19:27:01 +08:00
|
|
|
logger = logging.getLogger(__name__)
|
2024-05-24 12:08:12 +08:00
|
|
|
|
2024-07-29 10:32:11 +08:00
|
|
|
|
|
|
|
def load_yaml_file(file_path: str, ignore_error: bool = True, default_value: Any = {}) -> Any:
|
2024-05-24 12:08:12 +08:00
|
|
|
"""
|
2024-07-29 10:32:11 +08:00
|
|
|
Safe loading a YAML file
|
2024-05-24 12:08:12 +08:00
|
|
|
:param file_path: the path of the YAML file
|
|
|
|
:param ignore_error:
|
2024-07-29 13:40:18 +08:00
|
|
|
if True, return default_value if error occurs and the error will be logged in debug level
|
2024-05-24 12:08:12 +08:00
|
|
|
if False, raise error if error occurs
|
2024-07-29 10:32:11 +08:00
|
|
|
:param default_value: the value returned when errors ignored
|
|
|
|
:return: an object of the YAML content
|
2024-05-24 12:08:12 +08:00
|
|
|
"""
|
|
|
|
try:
|
2024-09-10 17:00:20 +08:00
|
|
|
with open(file_path, encoding="utf-8") as yaml_file:
|
2024-05-24 12:08:12 +08:00
|
|
|
try:
|
2024-07-29 13:40:18 +08:00
|
|
|
yaml_content = yaml.safe_load(yaml_file)
|
2024-09-12 15:50:49 +08:00
|
|
|
return yaml_content or default_value
|
2024-05-24 12:08:12 +08:00
|
|
|
except Exception as e:
|
2024-09-10 17:00:20 +08:00
|
|
|
raise YAMLError(f"Failed to load YAML file {file_path}: {e}")
|
2024-05-24 12:08:12 +08:00
|
|
|
except Exception as e:
|
|
|
|
if ignore_error:
|
2024-07-29 10:32:11 +08:00
|
|
|
return default_value
|
2024-05-24 12:08:12 +08:00
|
|
|
else:
|
|
|
|
raise e
|