configTools.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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[
  172. AbstractConfig, Dict[Union[Option, str], Any], Mapping[str, Any]
  173. ] = {},
  174. parse_values: bool = False,
  175. skip_unknown: bool = False,
  176. ):
  177. self._values = {}
  178. values_dict = values._values if isinstance(values, AbstractConfig) else values
  179. for name, value in values_dict.items():
  180. self.set(name, value, parse_values, skip_unknown)
  181. def _resolve_option(self, option_or_name: Union[Option, str]) -> Option:
  182. if isinstance(option_or_name, Option):
  183. option = option_or_name
  184. if not self.options.is_registered(option):
  185. raise ConfigUnknownOptionError(option)
  186. return option
  187. elif isinstance(option_or_name, str):
  188. name = option_or_name
  189. try:
  190. return self.options[name]
  191. except KeyError:
  192. raise ConfigUnknownOptionError(name)
  193. else:
  194. raise TypeError(
  195. "expected Option or str, found "
  196. f"{type(option_or_name).__name__}: {option_or_name!r}"
  197. )
  198. def set(
  199. self,
  200. option_or_name: Union[Option, str],
  201. value: Any,
  202. parse_values: bool = False,
  203. skip_unknown: bool = False,
  204. ):
  205. """Set the value of an option.
  206. Args:
  207. * `option_or_name`: an `Option` object or its name (`str`).
  208. * `value`: the value to be assigned to given option.
  209. * `parse_values`: parse the configuration value from a string into
  210. its proper type, as per its `Option` object. The default
  211. behavior is to raise `ConfigValueValidationError` when the value
  212. is not of the right type. Useful when reading options from a
  213. file type that doesn't support as many types as Python.
  214. * `skip_unknown`: skip unknown configuration options. The default
  215. behaviour is to raise `ConfigUnknownOptionError`. Useful when
  216. reading options from a configuration file that has extra entries
  217. (e.g. for a later version of fontTools)
  218. """
  219. try:
  220. option = self._resolve_option(option_or_name)
  221. except ConfigUnknownOptionError as e:
  222. if skip_unknown:
  223. log.debug(str(e))
  224. return
  225. raise
  226. # Can be useful if the values come from a source that doesn't have
  227. # strict typing (.ini file? Terminal input?)
  228. if parse_values:
  229. try:
  230. value = option.parse(value)
  231. except Exception as e:
  232. raise ConfigValueParsingError(option.name, value) from e
  233. if option.validate is not None and not option.validate(value):
  234. raise ConfigValueValidationError(option.name, value)
  235. self._values[option.name] = value
  236. def get(
  237. self, option_or_name: Union[Option, str], default: Any = _USE_GLOBAL_DEFAULT
  238. ) -> Any:
  239. """
  240. Get the value of an option. The value which is returned is the first
  241. provided among:
  242. 1. a user-provided value in the options's ``self._values`` dict
  243. 2. a caller-provided default value to this method call
  244. 3. the global default for the option provided in ``fontTools.config``
  245. This is to provide the ability to migrate progressively from config
  246. options passed as arguments to fontTools APIs to config options read
  247. from the current TTFont, e.g.
  248. .. code:: python
  249. def fontToolsAPI(font, some_option):
  250. value = font.cfg.get("someLib.module:SOME_OPTION", some_option)
  251. # use value
  252. That way, the function will work the same for users of the API that
  253. still pass the option to the function call, but will favour the new
  254. config mechanism if the given font specifies a value for that option.
  255. """
  256. option = self._resolve_option(option_or_name)
  257. if option.name in self._values:
  258. return self._values[option.name]
  259. if default is not _USE_GLOBAL_DEFAULT:
  260. return default
  261. return option.default
  262. def copy(self):
  263. return self.__class__(self._values)
  264. def __getitem__(self, option_or_name: Union[Option, str]) -> Any:
  265. return self.get(option_or_name)
  266. def __setitem__(self, option_or_name: Union[Option, str], value: Any) -> None:
  267. return self.set(option_or_name, value)
  268. def __delitem__(self, option_or_name: Union[Option, str]) -> None:
  269. option = self._resolve_option(option_or_name)
  270. del self._values[option.name]
  271. def __iter__(self) -> Iterable[str]:
  272. return self._values.__iter__()
  273. def __len__(self) -> int:
  274. return len(self._values)
  275. def __repr__(self) -> str:
  276. return f"{self.__class__.__name__}({repr(self._values)})"