chore: improve position map conversion and tolerate empty position yaml file (#6541)
parent
c8da4a1b7e
commit
20268708cc
@ -1,35 +1,31 @@
|
|||||||
import logging
|
import logging
|
||||||
import os
|
from typing import Any
|
||||||
|
|
||||||
import yaml
|
import yaml
|
||||||
from yaml import YAMLError
|
from yaml import YAMLError
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
def load_yaml_file(file_path: str, ignore_error: bool = False) -> dict:
|
|
||||||
|
def load_yaml_file(file_path: str, ignore_error: bool = True, default_value: Any = {}) -> Any:
|
||||||
"""
|
"""
|
||||||
Safe loading a YAML file to a dict
|
Safe loading a YAML file
|
||||||
:param file_path: the path of the YAML file
|
:param file_path: the path of the YAML file
|
||||||
:param ignore_error:
|
:param ignore_error:
|
||||||
if True, return empty dict if error occurs and the error will be logged in warning level
|
if True, return default_value if error occurs and the error will be logged in warning level
|
||||||
if False, raise error if error occurs
|
if False, raise error if error occurs
|
||||||
:return: a dict of the YAML content
|
:param default_value: the value returned when errors ignored
|
||||||
|
:return: an object of the YAML content
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
if not file_path or not os.path.exists(file_path):
|
with open(file_path, encoding='utf-8') as yaml_file:
|
||||||
raise FileNotFoundError(f'Failed to load YAML file {file_path}: file not found')
|
|
||||||
|
|
||||||
with open(file_path, encoding='utf-8') as file:
|
|
||||||
try:
|
try:
|
||||||
return yaml.safe_load(file)
|
return yaml.safe_load(yaml_file)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise YAMLError(f'Failed to load YAML file {file_path}: {e}')
|
raise YAMLError(f'Failed to load YAML file {file_path}: {e}')
|
||||||
except FileNotFoundError as e:
|
|
||||||
logger.debug(f'Failed to load YAML file {file_path}: {e}')
|
|
||||||
return {}
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
if ignore_error:
|
if ignore_error:
|
||||||
logger.warning(f'Failed to load YAML file {file_path}: {e}')
|
logger.warning(f'Failed to load YAML file {file_path}: {e}')
|
||||||
return {}
|
return default_value
|
||||||
else:
|
else:
|
||||||
raise e
|
raise e
|
||||||
|
|||||||
Loading…
Reference in New Issue