config.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # pylint: disable=missing-module-docstring
  3. from __future__ import annotations
  4. import pathlib
  5. import msgspec
  6. from .cache import FaviconCacheConfig
  7. from .proxy import FaviconProxyConfig
  8. CONFIG_SCHEMA: int = 1
  9. """Version of the configuration schema."""
  10. TOML_CACHE_CFG: dict[str, "FaviconConfig"] = {}
  11. """Cache config objects by TOML's filename."""
  12. DEFAULT_CFG_TOML_PATH = pathlib.Path(__file__).parent / "favicons.toml"
  13. class FaviconConfig(msgspec.Struct): # pylint: disable=too-few-public-methods
  14. """The class aggregates configurations of the favicon tools"""
  15. cfg_schema: int
  16. """Config's schema version. The specification of the version of the schema
  17. is mandatory, currently only version :py:obj:`CONFIG_SCHEMA` is supported.
  18. By specifying a version, it is possible to ensure downward compatibility in
  19. the event of future changes to the configuration schema"""
  20. cache: FaviconCacheConfig = msgspec.field(default_factory=FaviconCacheConfig)
  21. """Setup of the :py:obj:`.cache.FaviconCacheConfig`."""
  22. proxy: FaviconProxyConfig = msgspec.field(default_factory=FaviconProxyConfig)
  23. """Setup of the :py:obj:`.proxy.FaviconProxyConfig`."""
  24. @classmethod
  25. def from_toml_file(cls, cfg_file: pathlib.Path, use_cache: bool) -> "FaviconConfig":
  26. """Create a config object from a TOML file, the ``use_cache`` argument
  27. specifies whether a cache should be used.
  28. """
  29. cached = TOML_CACHE_CFG.get(str(cfg_file))
  30. if use_cache and cached:
  31. return cached
  32. with cfg_file.open("rb") as f:
  33. data = f.read()
  34. cfg = msgspec.toml.decode(data, type=_FaviconConfig)
  35. schema = cfg.favicons.cfg_schema
  36. if schema != CONFIG_SCHEMA:
  37. raise ValueError(
  38. f"config schema version {CONFIG_SCHEMA} is needed, version {schema} is given in {cfg_file}"
  39. )
  40. cfg = cfg.favicons
  41. if use_cache and cached:
  42. TOML_CACHE_CFG[str(cfg_file.resolve())] = cfg
  43. return cfg
  44. class _FaviconConfig(msgspec.Struct): # pylint: disable=too-few-public-methods
  45. # wrapper struct for root object "favicons."
  46. favicons: FaviconConfig