"""Loader module for NGPASM.This module have a functional for reading config files."""fromenumimportEnumfrompathlibimportPathimportorjsonasjsonimporttomlimportyaml
[docs]defdetect_config_type_by_extension(extension:str)->ConfigType:""" Detect config type by file extension. Args: extension: File extension string Returns: ConfigType: Detected config type (defaults to JSON) """cleaned_extension=extension.lower().lstrip(".")ifcleaned_extension=="json":returnConfigType.JSONifcleaned_extensionin("yaml","yml"):returnConfigType.YAMLifcleaned_extension=="toml":returnConfigType.TOMLreturnConfigType.JSON
[docs]defdetect_config_type_by_filename(filename:str)->ConfigType:""" Detect config type by filename. Args: filename: Full filename or path Returns: ConfigType: Detected config type """extension=Path(filename).suffix.lstrip(".")orfilenamereturndetect_config_type_by_extension(extension)
[docs]def__init__(self,config_file:str,configtype:ConfigType=None):""" Constructs new instance. Args: config_file: Path to configuration file configtype: Explicit config type (auto-detected if None) """self.config_file=Path(config_file)ifconfigtypeisNone:self.configtype=detect_config_type_by_filename(config_file)else:self.configtype=configtypeself.config=self._load_data_from_config()
def_load_data_from_config(self)->dict:""" Load configuration data from file. Returns: dict: loaded data as dictionary """data={}ifnotself.config_file.exists():returndataifself.configtype==ConfigType.YAML:withself.config_file.open()asf:data=yaml.safe_load(f)elifself.configtype==ConfigType.TOML:withself.config_file.open()asf:data=toml.load(f)elifself.configtype==ConfigType.JSON:withself.config_file.open("rb")asf:data=json.loads(f.read())returndataifisinstance(data,dict)else{}