|
| 1 | +from schema import Schema, SchemaError |
| 2 | +from typing import Any |
| 3 | +from os import path |
| 4 | +import json |
| 5 | +import yaml |
| 6 | +import os |
| 7 | +import re |
| 8 | + |
| 9 | + |
| 10 | +def json_parser(file_buff): |
| 11 | + try: |
| 12 | + return json.loads(file_buff) |
| 13 | + except json.JSONDecodeError as e: |
| 14 | + raise ConfigFileDecodeError(e) |
| 15 | + |
| 16 | + |
| 17 | +def yaml_parser(file_buff): |
| 18 | + try: |
| 19 | + return yaml.load(file_buff, yaml.FullLoader) |
| 20 | + except yaml.YAMLError as e: |
| 21 | + raise ConfigFileDecodeError(e) |
| 22 | + |
| 23 | + |
| 24 | +DEFAULT_CONFIG_FILES = ('config.json', 'config.yaml', 'config.yml') |
| 25 | +ENTITY_NAME_PATTERN = '^[\w\d_]+$' |
| 26 | +SUPPORTED_EXTENSIONS = { |
| 27 | + 'json': json_parser, |
| 28 | + 'yaml': yaml_parser, |
| 29 | + 'yml': yaml_parser |
| 30 | +} |
| 31 | + |
| 32 | + |
| 33 | +class ConfigValue: |
| 34 | + |
| 35 | + def __getitem__(self, item): |
| 36 | + return self.__dict__[item] |
| 37 | + |
| 38 | + def __iter__(self): |
| 39 | + return self.__dict__.keys().__iter__() |
| 40 | + |
| 41 | + |
| 42 | +class Config: |
| 43 | + __instance = None |
| 44 | + |
| 45 | + def __new__(cls, *args, **kwargs): |
| 46 | + raise RuntimeError('A instance of config is not allowed, use Config.get_config() instead') |
| 47 | + |
| 48 | + @classmethod |
| 49 | + def get_config(cls, schema: dict = None, config_dir: str = 'config', file_name: Any = DEFAULT_CONFIG_FILES): |
| 50 | + |
| 51 | + if cls.__instance is None or schema is not None: |
| 52 | + cls.__create_new_instance(schema, config_dir, file_name) |
| 53 | + return cls.__instance |
| 54 | + |
| 55 | + @classmethod |
| 56 | + def __create_new_instance(cls, schema, config_dir, file_name): |
| 57 | + cls.__check_schema(schema) |
| 58 | + file_path = cls.__get_file_path(config_dir, file_name) |
| 59 | + parser = cls.__get_file_parser(file_path) |
| 60 | + file_buff = cls.__get_file_buff(file_path) |
| 61 | + |
| 62 | + try: |
| 63 | + config = Schema(schema).validate(parser(file_buff)) |
| 64 | + cls.__instance = cls.__dict_2_obj(config) |
| 65 | + except SchemaError as e: |
| 66 | + raise ConfigFileModelError(str(e)) |
| 67 | + |
| 68 | + @classmethod |
| 69 | + def __get_file_parser(cls, file_path): |
| 70 | + try: |
| 71 | + extension = file_path.split('.')[-1] |
| 72 | + return SUPPORTED_EXTENSIONS[extension] |
| 73 | + except KeyError: |
| 74 | + raise ConfigFileExtensionNotSupportedError(f'Supported extensions: {list(SUPPORTED_EXTENSIONS.keys())}') |
| 75 | + |
| 76 | + @classmethod |
| 77 | + def __get_file_path(cls, config_dir, file_name): |
| 78 | + file_path = f'{os.getcwd()}/{config_dir}/' |
| 79 | + if type(file_name) is str: |
| 80 | + file_name = [file_name] |
| 81 | + |
| 82 | + for f_name in file_name: |
| 83 | + if path.isfile(file_path + f_name): |
| 84 | + return file_path + f_name |
| 85 | + |
| 86 | + raise ConfigFileNotFoundError(f'Config file {file_path}{file_name} was not found') |
| 87 | + |
| 88 | + @classmethod |
| 89 | + def __check_schema(cls, schema): |
| 90 | + if schema is None: |
| 91 | + raise ConfigError('The schema config can not be None') |
| 92 | + if type(schema) is not dict: |
| 93 | + raise ConfigError('The first config\'s schema element should be a Map') |
| 94 | + |
| 95 | + @classmethod |
| 96 | + def __get_file_buff(cls, path_file: str): |
| 97 | + try: |
| 98 | + with open(path_file, 'r') as f: |
| 99 | + return f.read() |
| 100 | + except Exception as e: |
| 101 | + raise ConfigFileOpenReadError(str(e)) |
| 102 | + |
| 103 | + @classmethod |
| 104 | + def __dict_2_obj(cls, data: Any): |
| 105 | + _type = type(data) |
| 106 | + |
| 107 | + if _type is dict: |
| 108 | + obj = ConfigValue() |
| 109 | + for key, value in data.items(): |
| 110 | + if re.search(ENTITY_NAME_PATTERN, key) is None: |
| 111 | + raise ConfigEntitiesWithWrongNameError( |
| 112 | + f'The key {key} is invalid. The entity keys only may have words, number and underscores.') |
| 113 | + setattr(obj, key, cls.__dict_2_obj(value)) |
| 114 | + return obj |
| 115 | + if _type in (list, set, tuple): |
| 116 | + return list(map(lambda v: cls.__dict_2_obj(v), data)) |
| 117 | + else: |
| 118 | + return data |
| 119 | + |
| 120 | + |
| 121 | +class ConfigError(Exception): |
| 122 | + pass |
| 123 | + |
| 124 | + |
| 125 | +class ConfigFileModelError(ConfigError): |
| 126 | + pass |
| 127 | + |
| 128 | + |
| 129 | +class ConfigFileDecodeError(ConfigError): |
| 130 | + pass |
| 131 | + |
| 132 | + |
| 133 | +class ConfigSchemaModelError(ConfigError): |
| 134 | + pass |
| 135 | + |
| 136 | + |
| 137 | +class ConfigFileOpenReadError(ConfigError): |
| 138 | + pass |
| 139 | + |
| 140 | + |
| 141 | +class ConfigFileNotFoundError(ConfigError): |
| 142 | + pass |
| 143 | + |
| 144 | + |
| 145 | +class ConfigFileExtensionNotSupportedError(ConfigError): |
| 146 | + pass |
| 147 | + |
| 148 | + |
| 149 | +class ConfigEntitiesWithWrongNameError(ConfigError): |
| 150 | + pass |
0 commit comments