config.py 12 KB

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