configTools.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. """
  2. Code of the config system; not related to fontTools or fonts in particular.
  3. The options that are specific to fontTools are in :mod:`fontTools.config`.
  4. To create your own config system, you need to create an instance of
  5. :class:`Options`, and a subclass of :class:`AbstractConfig` with its
  6. ``options`` class variable set to your instance of Options.
  7. """
  8. from __future__ import annotations
  9. import logging
  10. from dataclasses import dataclass
  11. from typing import (
  12. Any,
  13. Callable,
  14. ClassVar,
  15. Dict,
  16. Iterable,
  17. Mapping,
  18. MutableMapping,
  19. Optional,
  20. Set,
  21. Union,
  22. )
  23. log = logging.getLogger(__name__)
  24. __all__ = [
  25. "AbstractConfig",
  26. "ConfigAlreadyRegisteredError",
  27. "ConfigError",
  28. "ConfigUnknownOptionError",
  29. "ConfigValueParsingError",
  30. "ConfigValueValidationError",
  31. "Option",
  32. "Options",
  33. ]
  34. class ConfigError(Exception):
  35. """Base exception for the config module."""
  36. class ConfigAlreadyRegisteredError(ConfigError):
  37. """Raised when a module tries to register a configuration option that
  38. already exists.
  39. Should not be raised too much really, only when developing new fontTools
  40. modules.
  41. """
  42. def __init__(self, name):
  43. super().__init__(f"Config option {name} is already registered.")
  44. class ConfigValueParsingError(ConfigError):
  45. """Raised when a configuration value cannot be parsed."""
  46. def __init__(self, name, value):
  47. super().__init__(
  48. f"Config option {name}: value cannot be parsed (given {repr(value)})"
  49. )
  50. class ConfigValueValidationError(ConfigError):
  51. """Raised when a configuration value cannot be validated."""
  52. def __init__(self, name, value):
  53. super().__init__(
  54. f"Config option {name}: value is invalid (given {repr(value)})"
  55. )
  56. class ConfigUnknownOptionError(ConfigError):
  57. """Raised when a configuration option is unknown."""
  58. def __init__(self, option_or_name):
  59. name = (
  60. f"'{option_or_name.name}' (id={id(option_or_name)})>"
  61. if isinstance(option_or_name, Option)
  62. else f"'{option_or_name}'"
  63. )
  64. super().__init__(f"Config option {name} is unknown")
  65. # eq=False because Options are unique, not fungible objects
  66. @dataclass(frozen=True, eq=False)
  67. class Option:
  68. name: str
  69. """Unique name identifying the option (e.g. package.module:MY_OPTION)."""
  70. help: str
  71. """Help text for this option."""
  72. default: Any
  73. """Default value for this option."""
  74. parse: Callable[[str], Any]
  75. """Turn input (e.g. string) into proper type. Only when reading from file."""
  76. validate: Optional[Callable[[Any], bool]] = None
  77. """Return true if the given value is an acceptable value."""
  78. @staticmethod
  79. def parse_optional_bool(v: str) -> Optional[bool]:
  80. s = str(v).lower()
  81. if s in {"0", "no", "false"}:
  82. return False
  83. if s in {"1", "yes", "true"}:
  84. return True
  85. if s in {"auto", "none"}:
  86. return None
  87. raise ValueError("invalid optional bool: {v!r}")
  88. @staticmethod
  89. def validate_optional_bool(v: Any) -> bool:
  90. return v is None or isinstance(v, bool)
  91. class Options(Mapping):
  92. """Registry of available options for a given config system.
  93. Define new options using the :meth:`register()` method.
  94. Access existing options using the Mapping interface.
  95. """
  96. __options: Dict[str, Option]
  97. def __init__(self, other: "Options" = None) -> None:
  98. self.__options = {}
  99. if other is not None:
  100. for option in other.values():
  101. self.register_option(option)
  102. def register(
  103. self,
  104. name: str,
  105. help: str,
  106. default: Any,
  107. parse: Callable[[str], Any],
  108. validate: Optional[Callable[[Any], bool]] = None,
  109. ) -> Option:
  110. """Create and register a new option."""
  111. return self.register_option(Option(name, help, default, parse, validate))
  112. def register_option(self, option: Option) -> Option:
  113. """Register a new option."""
  114. name = option.name
  115. if name in self.__options:
  116. raise ConfigAlreadyRegisteredError(name)
  117. self.__options[name] = option
  118. return option
  119. def is_registered(self, option: Option) -> bool:
  120. """Return True if the same option object is already registered."""
  121. return self.__options.get(option.name) is option
  122. def __getitem__(self, key: str) -> Option:
  123. return self.__options.__getitem__(key)
  124. def __iter__(self) -> Iterator[str]:
  125. return self.__options.__iter__()
  126. def __len__(self) -> int:
  127. return self.__options.__len__()
  128. def __repr__(self) -> str:
  129. return (
  130. f"{self.__class__.__name__}({{\n"
  131. + "".join(
  132. f" {k!r}: Option(default={v.default!r}, ...),\n"
  133. for k, v in self.__options.items()
  134. )
  135. + "})"
  136. )
  137. _USE_GLOBAL_DEFAULT = object()
  138. class AbstractConfig(MutableMapping):
  139. """
  140. Create a set of config values, optionally pre-filled with values from
  141. the given dictionary or pre-existing config object.
  142. The class implements the MutableMapping protocol keyed by option name (`str`).
  143. For convenience its methods accept either Option or str as the key parameter.
  144. .. seealso:: :meth:`set()`
  145. This config class is abstract because it needs its ``options`` class
  146. var to be set to an instance of :class:`Options` before it can be
  147. instanciated and used.
  148. .. code:: python
  149. class MyConfig(AbstractConfig):
  150. options = Options()
  151. MyConfig.register_option( "test:option_name", "This is an option", 0, int, lambda v: isinstance(v, int))
  152. cfg = MyConfig({"test:option_name": 10})
  153. """
  154. options: ClassVar[Options]
  155. @classmethod
  156. def register_option(
  157. cls,
  158. name: str,
  159. help: str,
  160. default: Any,
  161. parse: Callable[[str], Any],
  162. validate: Optional[Callable[[Any], bool]] = None,
  163. ) -> Option:
  164. """Register an available option in this config system."""
  165. return cls.options.register(
  166. name, help=help, default=default, parse=parse, validate=validate
  167. )
  168. _values: Dict[str, Any]
  169. def __init__(
  170. self,
  171. values: Union[AbstractConfig, Dict[Union[Option, str], Any]] = {},
  172. parse_values: bool = False,
  173. skip_unknown: bool = False,
  174. ):
  175. self._values = {}
  176. values_dict = values._values if isinstance(values, AbstractConfig) else values
  177. for name, value in values_dict.items():
  178. self.set(name, value, parse_values, skip_unknown)
  179. def _resolve_option(self, option_or_name: Union[Option, str]) -> Option:
  180. if isinstance(option_or_name, Option):
  181. option = option_or_name
  182. if not self.options.is_registered(option):
  183. raise ConfigUnknownOptionError(option)
  184. return option
  185. elif isinstance(option_or_name, str):
  186. name = option_or_name
  187. try:
  188. return self.options[name]
  189. except KeyError:
  190. raise ConfigUnknownOptionError(name)
  191. else:
  192. raise TypeError(
  193. "expected Option or str, found "
  194. f"{type(option_or_name).__name__}: {option_or_name!r}"
  195. )
  196. def set(
  197. self,
  198. option_or_name: Union[Option, str],
  199. value: Any,
  200. parse_values: bool = False,
  201. skip_unknown: bool = False,
  202. ):
  203. """Set the value of an option.
  204. Args:
  205. * `option_or_name`: an `Option` object or its name (`str`).
  206. * `value`: the value to be assigned to given option.
  207. * `parse_values`: parse the configuration value from a string into
  208. its proper type, as per its `Option` object. The default
  209. behavior is to raise `ConfigValueValidationError` when the value
  210. is not of the right type. Useful when reading options from a
  211. file type that doesn't support as many types as Python.
  212. * `skip_unknown`: skip unknown configuration options. The default
  213. behaviour is to raise `ConfigUnknownOptionError`. Useful when
  214. reading options from a configuration file that has extra entries
  215. (e.g. for a later version of fontTools)
  216. """
  217. try:
  218. option = self._resolve_option(option_or_name)
  219. except ConfigUnknownOptionError as e:
  220. if skip_unknown:
  221. log.debug(str(e))
  222. return
  223. raise
  224. # Can be useful if the values come from a source that doesn't have
  225. # strict typing (.ini file? Terminal input?)
  226. if parse_values:
  227. try:
  228. value = option.parse(value)
  229. except Exception as e:
  230. raise ConfigValueParsingError(option.name, value) from e
  231. if option.validate is not None and not option.validate(value):
  232. raise ConfigValueValidationError(option.name, value)
  233. self._values[option.name] = value
  234. def get(
  235. self, option_or_name: Union[Option, str], default: Any = _USE_GLOBAL_DEFAULT
  236. ) -> Any:
  237. """
  238. Get the value of an option. The value which is returned is the first
  239. provided among:
  240. 1. a user-provided value in the options's ``self._values`` dict
  241. 2. a caller-provided default value to this method call
  242. 3. the global default for the option provided in ``fontTools.config``
  243. This is to provide the ability to migrate progressively from config
  244. options passed as arguments to fontTools APIs to config options read
  245. from the current TTFont, e.g.
  246. .. code:: python
  247. def fontToolsAPI(font, some_option):
  248. value = font.cfg.get("someLib.module:SOME_OPTION", some_option)
  249. # use value
  250. That way, the function will work the same for users of the API that
  251. still pass the option to the function call, but will favour the new
  252. config mechanism if the given font specifies a value for that option.
  253. """
  254. option = self._resolve_option(option_or_name)
  255. if option.name in self._values:
  256. return self._values[option.name]
  257. if default is not _USE_GLOBAL_DEFAULT:
  258. return default
  259. return option.default
  260. def copy(self):
  261. return self.__class__(self._values)
  262. def __getitem__(self, option_or_name: Union[Option, str]) -> Any:
  263. return self.get(option_or_name)
  264. def __setitem__(self, option_or_name: Union[Option, str], value: Any) -> None:
  265. return self.set(option_or_name, value)
  266. def __delitem__(self, option_or_name: Union[Option, str]) -> None:
  267. option = self._resolve_option(option_or_name)
  268. del self._values[option.name]
  269. def __iter__(self) -> Iterable[str]:
  270. return self._values.__iter__()
  271. def __len__(self) -> int:
  272. return len(self._values)
  273. def __repr__(self) -> str:
  274. return f"{self.__class__.__name__}({repr(self._values)})"