cornsnake.util_toml
Reading TOML (ini) files and updating the global config in memory (from config.py).
1""" 2Reading TOML (ini) files and updating the global config in memory (from config.py). 3 4[Documentation](http://docs.mrseanryan.cornsnake.s3-website-eu-west-1.amazonaws.com/cornsnake/util_toml.html) 5""" 6 7import tomllib 8import typing 9 10from . import config 11from . import util_dict 12from . import util_list 13from . import util_object 14 15# ref https://toml.io/en/ 16 17 18def _read_ini_file(path_to_ini: str) -> dict[str, typing.Any]: 19 """Read TOML data from a file.""" 20 try: 21 with open(path_to_ini, "rb") as f: 22 data = tomllib.load(f) 23 return data 24 except FileNotFoundError as fileNotFound: 25 raise RuntimeError( 26 f"The configuration file {path_to_ini} is missing - {str(fileNotFound)}" 27 ) 28 # NO log available yet 29 except tomllib.TOMLDecodeError as tomlError: 30 raise RuntimeError( 31 f"Please check the configuration file {path_to_ini} - {str(tomlError)}" 32 ) 33 # NO log available yet 34 35 36def read_config_ini_file(path_to_file: str, config_object: typing.Any = config) -> None: 37 """Read TOML data from a file and write it to a config object.""" 38 data = _read_ini_file(path_to_file) 39 _write_data_to_config(data, config_object, path_to_file) 40 41 42def _write_data_to_config( 43 data: dict[str, typing.Any], config_object: typing.Any, filename: str 44) -> None: 45 """Write data from TOML file to the global config object.""" 46 config_attributes = util_object.get_attributes(config_object) 47 data_attributes = util_dict.get_keys(data) 48 49 unexpected_data = util_list.excluding(data_attributes, config_attributes) 50 if len(unexpected_data) > 0: 51 raise ValueError( 52 f"{filename} has unexpected items: [{' '.join(unexpected_data)}] - please review." 53 ) 54 55 for data_attribute in data_attributes: 56 util_object.set_attribute_value( 57 config_object, data_attribute, data[data_attribute] 58 )
def
read_config_ini_file( path_to_file: str, config_object: Any = <module 'cornsnake.config' from 'C:\\sean\\src\\github\\mrseanryan\\cornsnake\\cornsnake\\config.py'>) -> None:
37def read_config_ini_file(path_to_file: str, config_object: typing.Any = config) -> None: 38 """Read TOML data from a file and write it to a config object.""" 39 data = _read_ini_file(path_to_file) 40 _write_data_to_config(data, config_object, path_to_file)
Read TOML data from a file and write it to a config object.