config.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Configuration class :py:class:`Config` with deep-update, schema validation
  3. and deprecated names.
  4. The :py:class:`Config` class implements a configuration that is based on
  5. structured dictionaries. The configuration schema is defined in a dictionary
  6. structure and the configuration data is given in a dictionary structure.
  7. """
  8. from __future__ import annotations
  9. from typing import Any
  10. import copy
  11. import typing
  12. import logging
  13. import pathlib
  14. from ..compat import tomllib
  15. __all__ = ['Config', 'UNSET', 'SchemaIssue']
  16. log = logging.getLogger(__name__)
  17. class FALSE:
  18. """Class of ``False`` singleton"""
  19. # pylint: disable=multiple-statements
  20. def __init__(self, msg):
  21. self.msg = msg
  22. def __bool__(self):
  23. return False
  24. def __str__(self):
  25. return self.msg
  26. __repr__ = __str__
  27. UNSET = FALSE('<UNSET>')
  28. class SchemaIssue(ValueError):
  29. """Exception to store and/or raise a message from a schema issue."""
  30. def __init__(self, level: typing.Literal['warn', 'invalid'], msg: str):
  31. self.level = level
  32. super().__init__(msg)
  33. def __str__(self):
  34. return f"[cfg schema {self.level}] {self.args[0]}"
  35. class Config:
  36. """Base class used for configuration"""
  37. UNSET = UNSET
  38. @classmethod
  39. def from_toml(cls, schema_file: pathlib.Path, cfg_file: pathlib.Path, deprecated: dict) -> Config:
  40. # init schema
  41. log.debug("load schema file: %s", schema_file)
  42. cfg = cls(cfg_schema=toml_load(schema_file), deprecated=deprecated)
  43. if not cfg_file.exists():
  44. log.warning("missing config file: %s", cfg_file)
  45. return cfg
  46. # load configuration
  47. log.debug("load config file: %s", cfg_file)
  48. upd_cfg = toml_load(cfg_file)
  49. is_valid, issue_list = cfg.validate(upd_cfg)
  50. for msg in issue_list:
  51. log.error(str(msg))
  52. if not is_valid:
  53. raise TypeError(f"schema of {cfg_file} is invalid!")
  54. cfg.update(upd_cfg)
  55. return cfg
  56. def __init__(self, cfg_schema: typing.Dict, deprecated: typing.Dict[str, str]):
  57. """Constructor of class Config.
  58. :param cfg_schema: Schema of the configuration
  59. :param deprecated: dictionary that maps deprecated configuration names to a messages
  60. These values are needed for validation, see :py:obj:`validate`.
  61. """
  62. self.cfg_schema = cfg_schema
  63. self.deprecated = deprecated
  64. self.cfg = copy.deepcopy(cfg_schema)
  65. def __getitem__(self, key: str) -> Any:
  66. return self.get(key)
  67. def validate(self, cfg: dict):
  68. """Validation of dictionary ``cfg`` on :py:obj:`Config.SCHEMA`.
  69. Validation is done by :py:obj:`validate`."""
  70. return validate(self.cfg_schema, cfg, self.deprecated)
  71. def update(self, upd_cfg: dict):
  72. """Update this configuration by ``upd_cfg``."""
  73. dict_deepupdate(self.cfg, upd_cfg)
  74. def default(self, name: str):
  75. """Returns default value of field ``name`` in ``self.cfg_schema``."""
  76. return value(name, self.cfg_schema)
  77. def get(self, name: str, default: Any = UNSET, replace: bool = True) -> Any:
  78. """Returns the value to which ``name`` points in the configuration.
  79. If there is no such ``name`` in the config and the ``default`` is
  80. :py:obj:`UNSET`, a :py:obj:`KeyError` is raised.
  81. """
  82. parent = self._get_parent_dict(name)
  83. val = parent.get(name.split('.')[-1], UNSET)
  84. if val is UNSET:
  85. if default is UNSET:
  86. raise KeyError(name)
  87. val = default
  88. if replace and isinstance(val, str):
  89. val = val % self
  90. return val
  91. def set(self, name: str, val):
  92. """Set the value to which ``name`` points in the configuration.
  93. If there is no such ``name`` in the config, a :py:obj:`KeyError` is
  94. raised.
  95. """
  96. parent = self._get_parent_dict(name)
  97. parent[name.split('.')[-1]] = val
  98. def _get_parent_dict(self, name):
  99. parent_name = '.'.join(name.split('.')[:-1])
  100. if parent_name:
  101. parent = value(parent_name, self.cfg)
  102. else:
  103. parent = self.cfg
  104. if (parent is UNSET) or (not isinstance(parent, dict)):
  105. raise KeyError(parent_name)
  106. return parent
  107. def path(self, name: str, default=UNSET):
  108. """Get a :py:class:`pathlib.Path` object from a config string."""
  109. val = self.get(name, default)
  110. if val is UNSET:
  111. if default is UNSET:
  112. raise KeyError(name)
  113. return default
  114. return pathlib.Path(str(val))
  115. def pyobj(self, name, default=UNSET):
  116. """Get python object referred by full qualiffied name (FQN) in the config
  117. string."""
  118. fqn = self.get(name, default)
  119. if fqn is UNSET:
  120. if default is UNSET:
  121. raise KeyError(name)
  122. return default
  123. (modulename, name) = str(fqn).rsplit('.', 1)
  124. m = __import__(modulename, {}, {}, [name], 0)
  125. return getattr(m, name)
  126. def toml_load(file_name):
  127. try:
  128. with open(file_name, "rb") as f:
  129. return tomllib.load(f)
  130. except tomllib.TOMLDecodeError as exc:
  131. msg = str(exc).replace('\t', '').replace('\n', ' ')
  132. log.error("%s: %s", file_name, msg)
  133. raise
  134. # working with dictionaries
  135. def value(name: str, data_dict: dict):
  136. """Returns the value to which ``name`` points in the ``dat_dict``.
  137. .. code: python
  138. >>> data_dict = {
  139. "foo": {"bar": 1 },
  140. "bar": {"foo": 2 },
  141. "foobar": [1, 2, 3],
  142. }
  143. >>> value('foobar', data_dict)
  144. [1, 2, 3]
  145. >>> value('foo.bar', data_dict)
  146. 1
  147. >>> value('foo.bar.xxx', data_dict)
  148. <UNSET>
  149. """
  150. ret_val = data_dict
  151. for part in name.split('.'):
  152. if isinstance(ret_val, dict):
  153. ret_val = ret_val.get(part, UNSET)
  154. if ret_val is UNSET:
  155. break
  156. return ret_val
  157. def validate(
  158. schema_dict: typing.Dict, data_dict: typing.Dict, deprecated: typing.Dict[str, str]
  159. ) -> typing.Tuple[bool, list]:
  160. """Deep validation of dictionary in ``data_dict`` against dictionary in
  161. ``schema_dict``. Argument deprecated is a dictionary that maps deprecated
  162. configuration names to a messages::
  163. deprecated = {
  164. "foo.bar" : "config 'foo.bar' is deprecated, use 'bar.foo'",
  165. "..." : "..."
  166. }
  167. The function returns a python tuple ``(is_valid, issue_list)``:
  168. ``is_valid``:
  169. A bool value indicating ``data_dict`` is valid or not.
  170. ``issue_list``:
  171. A list of messages (:py:obj:`SchemaIssue`) from the validation::
  172. [schema warn] data_dict: deprecated 'fontlib.foo': <DEPRECATED['foo.bar']>
  173. [schema invalid] data_dict: key unknown 'fontlib.foo'
  174. [schema invalid] data_dict: type mismatch 'fontlib.foo': expected ..., is ...
  175. If ``schema_dict`` or ``data_dict`` is not a dictionary type a
  176. :py:obj:`SchemaIssue` is raised.
  177. """
  178. names = []
  179. is_valid = True
  180. issue_list = []
  181. if not isinstance(schema_dict, dict):
  182. raise SchemaIssue('invalid', "schema_dict is not a dict type")
  183. if not isinstance(data_dict, dict):
  184. raise SchemaIssue('invalid', f"data_dict issue{'.'.join(names)} is not a dict type")
  185. is_valid, issue_list = _validate(names, issue_list, schema_dict, data_dict, deprecated)
  186. return is_valid, issue_list
  187. def _validate(
  188. names: typing.List,
  189. issue_list: typing.List,
  190. schema_dict: typing.Dict,
  191. data_dict: typing.Dict,
  192. deprecated: typing.Dict[str, str],
  193. ) -> typing.Tuple[bool, typing.List]:
  194. is_valid = True
  195. for key, data_value in data_dict.items():
  196. names.append(key)
  197. name = '.'.join(names)
  198. deprecated_msg = deprecated.get(name)
  199. # print("XXX %s: key %s // data_value: %s" % (name, key, data_value))
  200. if deprecated_msg:
  201. issue_list.append(SchemaIssue('warn', f"data_dict '{name}': deprecated - {deprecated_msg}"))
  202. schema_value = value(name, schema_dict)
  203. # print("YYY %s: key %s // schema_value: %s" % (name, key, schema_value))
  204. if schema_value is UNSET:
  205. if not deprecated_msg:
  206. issue_list.append(SchemaIssue('invalid', f"data_dict '{name}': key unknown in schema_dict"))
  207. is_valid = False
  208. elif type(schema_value) != type(data_value): # pylint: disable=unidiomatic-typecheck
  209. issue_list.append(
  210. SchemaIssue(
  211. 'invalid',
  212. (f"data_dict: type mismatch '{name}':" f" expected {type(schema_value)}, is: {type(data_value)}"),
  213. )
  214. )
  215. is_valid = False
  216. elif isinstance(data_value, dict):
  217. _valid, _ = _validate(names, issue_list, schema_dict, data_value, deprecated)
  218. is_valid = is_valid and _valid
  219. names.pop()
  220. return is_valid, issue_list
  221. def dict_deepupdate(base_dict: dict, upd_dict: dict, names=None):
  222. """Deep-update of dictionary in ``base_dict`` by dictionary in ``upd_dict``.
  223. For each ``upd_key`` & ``upd_val`` pair in ``upd_dict``:
  224. 0. If types of ``base_dict[upd_key]`` and ``upd_val`` do not match raise a
  225. :py:obj:`TypeError`.
  226. 1. If ``base_dict[upd_key]`` is a dict: recursively deep-update it by ``upd_val``.
  227. 2. If ``base_dict[upd_key]`` not exist: set ``base_dict[upd_key]`` from a
  228. (deep-) copy of ``upd_val``.
  229. 3. If ``upd_val`` is a list, extend list in ``base_dict[upd_key]`` by the
  230. list in ``upd_val``.
  231. 4. If ``upd_val`` is a set, update set in ``base_dict[upd_key]`` by set in
  232. ``upd_val``.
  233. """
  234. # pylint: disable=too-many-branches
  235. if not isinstance(base_dict, dict):
  236. raise TypeError("argument 'base_dict' is not a ditionary type")
  237. if not isinstance(upd_dict, dict):
  238. raise TypeError("argument 'upd_dict' is not a ditionary type")
  239. if names is None:
  240. names = []
  241. for upd_key, upd_val in upd_dict.items():
  242. # For each upd_key & upd_val pair in upd_dict:
  243. if isinstance(upd_val, dict):
  244. if upd_key in base_dict:
  245. # if base_dict[upd_key] exists, recursively deep-update it
  246. if not isinstance(base_dict[upd_key], dict):
  247. raise TypeError(f"type mismatch {'.'.join(names)}: is not a dict type in base_dict")
  248. dict_deepupdate(
  249. base_dict[upd_key],
  250. upd_val,
  251. names
  252. + [
  253. upd_key,
  254. ],
  255. )
  256. else:
  257. # if base_dict[upd_key] not exist, set base_dict[upd_key] from deepcopy of upd_val
  258. base_dict[upd_key] = copy.deepcopy(upd_val)
  259. elif isinstance(upd_val, list):
  260. if upd_key in base_dict:
  261. # if base_dict[upd_key] exists, base_dict[up_key] is extended by
  262. # the list from upd_val
  263. if not isinstance(base_dict[upd_key], list):
  264. raise TypeError(f"type mismatch {'.'.join(names)}: is not a list type in base_dict")
  265. base_dict[upd_key].extend(upd_val)
  266. else:
  267. # if base_dict[upd_key] doesn't exists, set base_dict[key] from a deepcopy of the
  268. # list in upd_val.
  269. base_dict[upd_key] = copy.deepcopy(upd_val)
  270. elif isinstance(upd_val, set):
  271. if upd_key in base_dict:
  272. # if base_dict[upd_key] exists, base_dict[up_key] is updated by the set in upd_val
  273. if not isinstance(base_dict[upd_key], set):
  274. raise TypeError(f"type mismatch {'.'.join(names)}: is not a set type in base_dict")
  275. base_dict[upd_key].update(upd_val.copy())
  276. else:
  277. # if base_dict[upd_key] doesn't exists, set base_dict[upd_key] from a copy of the
  278. # set in upd_val
  279. base_dict[upd_key] = upd_val.copy()
  280. else:
  281. # for any other type of upd_val replace or add base_dict[upd_key] by a copy
  282. # of upd_val
  283. base_dict[upd_key] = copy.copy(upd_val)