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 sys 9 10from . import config 11from . import util_list 12from . import util_object 13from . import util_print 14 15# ref https://toml.io/en/ 16 17 18def _read_ini_file(path_to_ini): 19 """Read TOML data from a file.""" 20 success = False 21 try: 22 with open(path_to_ini, "rb") as f: 23 data = tomllib.load(f) 24 success = True 25 return data 26 except FileNotFoundError as fileNotFound: 27 util_print.print_error( 28 f"The configuration file {path_to_ini} is missing - {str(fileNotFound)}" 29 ) 30 # NO log available yet 31 except tomllib.TOMLDecodeError as tomlError: 32 util_print.print_error( 33 f"Please check the configuration file {path_to_ini} - {str(tomlError)}" 34 ) 35 # NO log available yet 36 finally: 37 if not success: 38 sys.exit(101) 39 40 41def read_config_ini_file(path_to_file): 42 """Read TOML data from a file and write it to a config object.""" 43 data = _read_ini_file(path_to_file) 44 _write_data_to_config(data, config, path_to_file) 45 46 47def _write_data_to_config(data, config_object, filename): 48 """Write data from TOML file to the global config object.""" 49 config_attributes = util_object.get_attributes(config_object) 50 data_attributes = data.keys() 51 52 unexpected_data = util_list.except_for(data_attributes, config_attributes) 53 if len(unexpected_data) > 0: 54 raise ValueError( 55 f"{filename} has unexpected items: [{' '.join(unexpected_data)}] - please review." 56 ) 57 58 for data_attribute in data_attributes: 59 util_object.set_attribute_value( 60 config_object, data_attribute, data[data_attribute] 61 )
def
read_config_ini_file(path_to_file):
42def read_config_ini_file(path_to_file): 43 """Read TOML data from a file and write it to a config object.""" 44 data = _read_ini_file(path_to_file) 45 _write_data_to_config(data, config, path_to_file)
Read TOML data from a file and write it to a config object.