config.py 12 KB

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