|
| 1 | +import collections |
| 2 | +import configparser |
| 3 | +import distutils.util |
| 4 | +import logging |
| 5 | +import os |
| 6 | + |
| 7 | +import expandvars |
| 8 | + |
| 9 | +from . import exceptions |
| 10 | + |
| 11 | +LOGGER = logging.getLogger(__name__) |
| 12 | + |
| 13 | +_UNSET = object() |
| 14 | + |
| 15 | + |
| 16 | +class Config: |
| 17 | + class ConfigInterpolation(configparser.BasicInterpolation): |
| 18 | + |
| 19 | + def before_get(self, parser, section, option, value, defaults): |
| 20 | + return expandvars.expandvars(value) |
| 21 | + |
| 22 | + instances = list() |
| 23 | + parser = configparser.ConfigParser(interpolation=ConfigInterpolation()) |
| 24 | + directory = None |
| 25 | + file_names = None |
| 26 | + |
| 27 | + def __init__(self, data_type, section, option=None, fallback=_UNSET): |
| 28 | + self.__class__.instances.append(self) |
| 29 | + self._data_type = data_type |
| 30 | + self._is_none = False |
| 31 | + self._section = section |
| 32 | + self._option = option |
| 33 | + self._fallback = fallback |
| 34 | + self._gen_value = _UNSET |
| 35 | + |
| 36 | + @staticmethod |
| 37 | + def init(directory, *file_names, ignore_error=False): |
| 38 | + # Set the directory of the configuration files to use |
| 39 | + Config.directory = directory |
| 40 | + # Load the configuration files |
| 41 | + Config.load(*file_names, ignore_error=ignore_error) |
| 42 | + |
| 43 | + @staticmethod |
| 44 | + def path(target=""): |
| 45 | + yield os.path.join(Config.directory, target) |
| 46 | + |
| 47 | + @staticmethod |
| 48 | + def dir(target=""): |
| 49 | + return os.path.join(Config.directory, target) |
| 50 | + |
| 51 | + @staticmethod |
| 52 | + def load(*file_names, encoding=None, ignore_error=False): |
| 53 | + # If configuration should only be reloaded |
| 54 | + if not file_names: file_names = Config.file_names |
| 55 | + # Set file names |
| 56 | + Config.file_names = file_names |
| 57 | + # Build the real path of each configuration file |
| 58 | + config_file_paths = [os.path.join(Config.directory, file_name) for file_name in file_names] |
| 59 | + # Check if the file exists |
| 60 | + valid_file_paths = [] |
| 61 | + for config_file_path in config_file_paths: |
| 62 | + if not os.path.isfile(config_file_path): |
| 63 | + if not ignore_error: |
| 64 | + raise exceptions.ConfigFileDoesNotExists(config_file_path) |
| 65 | + else: |
| 66 | + valid_file_paths.append(config_file_path) |
| 67 | + # Parse and read the configurations |
| 68 | + Config.parser.read(valid_file_paths, encoding) |
| 69 | + |
| 70 | + def get(self, option=None, **kwargs): |
| 71 | + if self._is_none: |
| 72 | + return None |
| 73 | + option = self._option if option is None else option |
| 74 | + if self._fallback is _UNSET: |
| 75 | + value = Config.parser.get(self._section, option) |
| 76 | + else: |
| 77 | + value = Config.parser.get(self._section, option, fallback=self._fallback) |
| 78 | + if value == '': |
| 79 | + value = self._fallback |
| 80 | + # Check the value |
| 81 | + if value is None: |
| 82 | + return None |
| 83 | + if isinstance(value, collections.Generator): |
| 84 | + if self._gen_value is _UNSET: |
| 85 | + self._gen_value = next(value) |
| 86 | + return self._gen_value |
| 87 | + # Check data type |
| 88 | + if isinstance(self._data_type, type): |
| 89 | + if self._data_type == bool: |
| 90 | + if isinstance(value, bool): |
| 91 | + return value |
| 92 | + elif isinstance(value, str): |
| 93 | + return bool(distutils.util.strtobool(value)) |
| 94 | + elif self._data_type == str and kwargs: |
| 95 | + value = str(value).format(**kwargs) |
| 96 | + elif isinstance(self._data_type, tuple) and isinstance(value, str): |
| 97 | + collection, data_type = self._data_type |
| 98 | + if collection == list: |
| 99 | + return [data_type(v) for v in value.split(",")] |
| 100 | + # Return the casted value |
| 101 | + return self._data_type(value) |
| 102 | + |
| 103 | + def set(self, value): |
| 104 | + if value is not None: |
| 105 | + if not isinstance(value, self._data_type): |
| 106 | + raise exceptions.ValueTypeNotAllowed(self._option, type(self._data_type).__name__) |
| 107 | + self._is_none = False |
| 108 | + value = self._data_type(value) |
| 109 | + else: |
| 110 | + self._is_none = True |
| 111 | + return |
| 112 | + if self._section not in Config.parser.sections(): |
| 113 | + Config.parser.add_section(self._section) |
| 114 | + try: |
| 115 | + Config.parser.set(self._section, self._option, str(value)) |
| 116 | + except Exception as e: |
| 117 | + raise exceptions.SetValueError(value, str(e)) |
| 118 | + |
| 119 | + @staticmethod |
| 120 | + def update(data): |
| 121 | + for section, data in data.items(): |
| 122 | + if section not in Config.parser.sections(): |
| 123 | + Config.parser.add_section(section) |
| 124 | + for option, value in data: |
| 125 | + Config.parser.set(section, option, value) |
| 126 | + |
| 127 | + @staticmethod |
| 128 | + def save(filename): |
| 129 | + with open(Config.dir(filename), 'w') as f: |
| 130 | + Config.parser.write(f) |
| 131 | + |
| 132 | + @staticmethod |
| 133 | + def data(): |
| 134 | + return {s: Config.parser.items(s) for s in Config.parser.sections()} |
0 commit comments