setupcfg.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. """
  2. Load setuptools configuration from ``setup.cfg`` files.
  3. **API will be made private in the future**
  4. """
  5. import os
  6. import warnings
  7. import functools
  8. from collections import defaultdict
  9. from functools import partial
  10. from functools import wraps
  11. from typing import (TYPE_CHECKING, Callable, Any, Dict, Generic, Iterable, List,
  12. Optional, Tuple, TypeVar, Union)
  13. from distutils.errors import DistutilsOptionError, DistutilsFileError
  14. from setuptools.extern.packaging.version import Version, InvalidVersion
  15. from setuptools.extern.packaging.specifiers import SpecifierSet
  16. from setuptools._deprecation_warning import SetuptoolsDeprecationWarning
  17. from . import expand
  18. if TYPE_CHECKING:
  19. from setuptools.dist import Distribution # noqa
  20. from distutils.dist import DistributionMetadata # noqa
  21. _Path = Union[str, os.PathLike]
  22. SingleCommandOptions = Dict["str", Tuple["str", Any]]
  23. """Dict that associate the name of the options of a particular command to a
  24. tuple. The first element of the tuple indicates the origin of the option value
  25. (e.g. the name of the configuration file where it was read from),
  26. while the second element of the tuple is the option value itself
  27. """
  28. AllCommandOptions = Dict["str", SingleCommandOptions] # cmd name => its options
  29. Target = TypeVar("Target", bound=Union["Distribution", "DistributionMetadata"])
  30. def read_configuration(
  31. filepath: _Path,
  32. find_others=False,
  33. ignore_option_errors=False
  34. ) -> dict:
  35. """Read given configuration file and returns options from it as a dict.
  36. :param str|unicode filepath: Path to configuration file
  37. to get options from.
  38. :param bool find_others: Whether to search for other configuration files
  39. which could be on in various places.
  40. :param bool ignore_option_errors: Whether to silently ignore
  41. options, values of which could not be resolved (e.g. due to exceptions
  42. in directives such as file:, attr:, etc.).
  43. If False exceptions are propagated as expected.
  44. :rtype: dict
  45. """
  46. from setuptools.dist import Distribution
  47. dist = Distribution()
  48. filenames = dist.find_config_files() if find_others else []
  49. handlers = _apply(dist, filepath, filenames, ignore_option_errors)
  50. return configuration_to_dict(handlers)
  51. def apply_configuration(dist: "Distribution", filepath: _Path) -> "Distribution":
  52. """Apply the configuration from a ``setup.cfg`` file into an existing
  53. distribution object.
  54. """
  55. _apply(dist, filepath)
  56. dist._finalize_requires()
  57. return dist
  58. def _apply(
  59. dist: "Distribution", filepath: _Path,
  60. other_files: Iterable[_Path] = (),
  61. ignore_option_errors: bool = False,
  62. ) -> Tuple["ConfigHandler", ...]:
  63. """Read configuration from ``filepath`` and applies to the ``dist`` object."""
  64. from setuptools.dist import _Distribution
  65. filepath = os.path.abspath(filepath)
  66. if not os.path.isfile(filepath):
  67. raise DistutilsFileError('Configuration file %s does not exist.' % filepath)
  68. current_directory = os.getcwd()
  69. os.chdir(os.path.dirname(filepath))
  70. filenames = [*other_files, filepath]
  71. try:
  72. _Distribution.parse_config_files(dist, filenames=filenames)
  73. handlers = parse_configuration(
  74. dist, dist.command_options, ignore_option_errors=ignore_option_errors
  75. )
  76. dist._finalize_license_files()
  77. finally:
  78. os.chdir(current_directory)
  79. return handlers
  80. def _get_option(target_obj: Target, key: str):
  81. """
  82. Given a target object and option key, get that option from
  83. the target object, either through a get_{key} method or
  84. from an attribute directly.
  85. """
  86. getter_name = 'get_{key}'.format(**locals())
  87. by_attribute = functools.partial(getattr, target_obj, key)
  88. getter = getattr(target_obj, getter_name, by_attribute)
  89. return getter()
  90. def configuration_to_dict(handlers: Tuple["ConfigHandler", ...]) -> dict:
  91. """Returns configuration data gathered by given handlers as a dict.
  92. :param list[ConfigHandler] handlers: Handlers list,
  93. usually from parse_configuration()
  94. :rtype: dict
  95. """
  96. config_dict: dict = defaultdict(dict)
  97. for handler in handlers:
  98. for option in handler.set_options:
  99. value = _get_option(handler.target_obj, option)
  100. config_dict[handler.section_prefix][option] = value
  101. return config_dict
  102. def parse_configuration(
  103. distribution: "Distribution",
  104. command_options: AllCommandOptions,
  105. ignore_option_errors=False
  106. ) -> Tuple["ConfigMetadataHandler", "ConfigOptionsHandler"]:
  107. """Performs additional parsing of configuration options
  108. for a distribution.
  109. Returns a list of used option handlers.
  110. :param Distribution distribution:
  111. :param dict command_options:
  112. :param bool ignore_option_errors: Whether to silently ignore
  113. options, values of which could not be resolved (e.g. due to exceptions
  114. in directives such as file:, attr:, etc.).
  115. If False exceptions are propagated as expected.
  116. :rtype: list
  117. """
  118. with expand.EnsurePackagesDiscovered(distribution) as ensure_discovered:
  119. options = ConfigOptionsHandler(
  120. distribution,
  121. command_options,
  122. ignore_option_errors,
  123. ensure_discovered,
  124. )
  125. options.parse()
  126. if not distribution.package_dir:
  127. distribution.package_dir = options.package_dir # Filled by `find_packages`
  128. meta = ConfigMetadataHandler(
  129. distribution.metadata,
  130. command_options,
  131. ignore_option_errors,
  132. ensure_discovered,
  133. distribution.package_dir,
  134. distribution.src_root,
  135. )
  136. meta.parse()
  137. return meta, options
  138. class ConfigHandler(Generic[Target]):
  139. """Handles metadata supplied in configuration files."""
  140. section_prefix: str
  141. """Prefix for config sections handled by this handler.
  142. Must be provided by class heirs.
  143. """
  144. aliases: Dict[str, str] = {}
  145. """Options aliases.
  146. For compatibility with various packages. E.g.: d2to1 and pbr.
  147. Note: `-` in keys is replaced with `_` by config parser.
  148. """
  149. def __init__(
  150. self,
  151. target_obj: Target,
  152. options: AllCommandOptions,
  153. ignore_option_errors,
  154. ensure_discovered: expand.EnsurePackagesDiscovered,
  155. ):
  156. sections: AllCommandOptions = {}
  157. section_prefix = self.section_prefix
  158. for section_name, section_options in options.items():
  159. if not section_name.startswith(section_prefix):
  160. continue
  161. section_name = section_name.replace(section_prefix, '').strip('.')
  162. sections[section_name] = section_options
  163. self.ignore_option_errors = ignore_option_errors
  164. self.target_obj = target_obj
  165. self.sections = sections
  166. self.set_options: List[str] = []
  167. self.ensure_discovered = ensure_discovered
  168. @property
  169. def parsers(self):
  170. """Metadata item name to parser function mapping."""
  171. raise NotImplementedError(
  172. '%s must provide .parsers property' % self.__class__.__name__
  173. )
  174. def __setitem__(self, option_name, value):
  175. unknown = tuple()
  176. target_obj = self.target_obj
  177. # Translate alias into real name.
  178. option_name = self.aliases.get(option_name, option_name)
  179. current_value = getattr(target_obj, option_name, unknown)
  180. if current_value is unknown:
  181. raise KeyError(option_name)
  182. if current_value:
  183. # Already inhabited. Skipping.
  184. return
  185. skip_option = False
  186. parser = self.parsers.get(option_name)
  187. if parser:
  188. try:
  189. value = parser(value)
  190. except Exception:
  191. skip_option = True
  192. if not self.ignore_option_errors:
  193. raise
  194. if skip_option:
  195. return
  196. setter = getattr(target_obj, 'set_%s' % option_name, None)
  197. if setter is None:
  198. setattr(target_obj, option_name, value)
  199. else:
  200. setter(value)
  201. self.set_options.append(option_name)
  202. @classmethod
  203. def _parse_list(cls, value, separator=','):
  204. """Represents value as a list.
  205. Value is split either by separator (defaults to comma) or by lines.
  206. :param value:
  207. :param separator: List items separator character.
  208. :rtype: list
  209. """
  210. if isinstance(value, list): # _get_parser_compound case
  211. return value
  212. if '\n' in value:
  213. value = value.splitlines()
  214. else:
  215. value = value.split(separator)
  216. return [chunk.strip() for chunk in value if chunk.strip()]
  217. @classmethod
  218. def _parse_dict(cls, value):
  219. """Represents value as a dict.
  220. :param value:
  221. :rtype: dict
  222. """
  223. separator = '='
  224. result = {}
  225. for line in cls._parse_list(value):
  226. key, sep, val = line.partition(separator)
  227. if sep != separator:
  228. raise DistutilsOptionError(
  229. 'Unable to parse option value to dict: %s' % value
  230. )
  231. result[key.strip()] = val.strip()
  232. return result
  233. @classmethod
  234. def _parse_bool(cls, value):
  235. """Represents value as boolean.
  236. :param value:
  237. :rtype: bool
  238. """
  239. value = value.lower()
  240. return value in ('1', 'true', 'yes')
  241. @classmethod
  242. def _exclude_files_parser(cls, key):
  243. """Returns a parser function to make sure field inputs
  244. are not files.
  245. Parses a value after getting the key so error messages are
  246. more informative.
  247. :param key:
  248. :rtype: callable
  249. """
  250. def parser(value):
  251. exclude_directive = 'file:'
  252. if value.startswith(exclude_directive):
  253. raise ValueError(
  254. 'Only strings are accepted for the {0} field, '
  255. 'files are not accepted'.format(key)
  256. )
  257. return value
  258. return parser
  259. @classmethod
  260. def _parse_file(cls, value, root_dir: _Path):
  261. """Represents value as a string, allowing including text
  262. from nearest files using `file:` directive.
  263. Directive is sandboxed and won't reach anything outside
  264. directory with setup.py.
  265. Examples:
  266. file: README.rst, CHANGELOG.md, src/file.txt
  267. :param str value:
  268. :rtype: str
  269. """
  270. include_directive = 'file:'
  271. if not isinstance(value, str):
  272. return value
  273. if not value.startswith(include_directive):
  274. return value
  275. spec = value[len(include_directive) :]
  276. filepaths = (path.strip() for path in spec.split(','))
  277. return expand.read_files(filepaths, root_dir)
  278. def _parse_attr(self, value, package_dir, root_dir: _Path):
  279. """Represents value as a module attribute.
  280. Examples:
  281. attr: package.attr
  282. attr: package.module.attr
  283. :param str value:
  284. :rtype: str
  285. """
  286. attr_directive = 'attr:'
  287. if not value.startswith(attr_directive):
  288. return value
  289. attr_desc = value.replace(attr_directive, '')
  290. # Make sure package_dir is populated correctly, so `attr:` directives can work
  291. package_dir.update(self.ensure_discovered.package_dir)
  292. return expand.read_attr(attr_desc, package_dir, root_dir)
  293. @classmethod
  294. def _get_parser_compound(cls, *parse_methods):
  295. """Returns parser function to represents value as a list.
  296. Parses a value applying given methods one after another.
  297. :param parse_methods:
  298. :rtype: callable
  299. """
  300. def parse(value):
  301. parsed = value
  302. for method in parse_methods:
  303. parsed = method(parsed)
  304. return parsed
  305. return parse
  306. @classmethod
  307. def _parse_section_to_dict(cls, section_options, values_parser=None):
  308. """Parses section options into a dictionary.
  309. Optionally applies a given parser to values.
  310. :param dict section_options:
  311. :param callable values_parser:
  312. :rtype: dict
  313. """
  314. value = {}
  315. values_parser = values_parser or (lambda val: val)
  316. for key, (_, val) in section_options.items():
  317. value[key] = values_parser(val)
  318. return value
  319. def parse_section(self, section_options):
  320. """Parses configuration file section.
  321. :param dict section_options:
  322. """
  323. for (name, (_, value)) in section_options.items():
  324. try:
  325. self[name] = value
  326. except KeyError:
  327. pass # Keep silent for a new option may appear anytime.
  328. def parse(self):
  329. """Parses configuration file items from one
  330. or more related sections.
  331. """
  332. for section_name, section_options in self.sections.items():
  333. method_postfix = ''
  334. if section_name: # [section.option] variant
  335. method_postfix = '_%s' % section_name
  336. section_parser_method: Optional[Callable] = getattr(
  337. self,
  338. # Dots in section names are translated into dunderscores.
  339. ('parse_section%s' % method_postfix).replace('.', '__'),
  340. None,
  341. )
  342. if section_parser_method is None:
  343. raise DistutilsOptionError(
  344. 'Unsupported distribution option section: [%s.%s]'
  345. % (self.section_prefix, section_name)
  346. )
  347. section_parser_method(section_options)
  348. def _deprecated_config_handler(self, func, msg, warning_class):
  349. """this function will wrap around parameters that are deprecated
  350. :param msg: deprecation message
  351. :param warning_class: class of warning exception to be raised
  352. :param func: function to be wrapped around
  353. """
  354. @wraps(func)
  355. def config_handler(*args, **kwargs):
  356. warnings.warn(msg, warning_class)
  357. return func(*args, **kwargs)
  358. return config_handler
  359. class ConfigMetadataHandler(ConfigHandler["DistributionMetadata"]):
  360. section_prefix = 'metadata'
  361. aliases = {
  362. 'home_page': 'url',
  363. 'summary': 'description',
  364. 'classifier': 'classifiers',
  365. 'platform': 'platforms',
  366. }
  367. strict_mode = False
  368. """We need to keep it loose, to be partially compatible with
  369. `pbr` and `d2to1` packages which also uses `metadata` section.
  370. """
  371. def __init__(
  372. self,
  373. target_obj: "DistributionMetadata",
  374. options: AllCommandOptions,
  375. ignore_option_errors: bool,
  376. ensure_discovered: expand.EnsurePackagesDiscovered,
  377. package_dir: Optional[dict] = None,
  378. root_dir: _Path = os.curdir
  379. ):
  380. super().__init__(target_obj, options, ignore_option_errors, ensure_discovered)
  381. self.package_dir = package_dir
  382. self.root_dir = root_dir
  383. @property
  384. def parsers(self):
  385. """Metadata item name to parser function mapping."""
  386. parse_list = self._parse_list
  387. parse_file = partial(self._parse_file, root_dir=self.root_dir)
  388. parse_dict = self._parse_dict
  389. exclude_files_parser = self._exclude_files_parser
  390. return {
  391. 'platforms': parse_list,
  392. 'keywords': parse_list,
  393. 'provides': parse_list,
  394. 'requires': self._deprecated_config_handler(
  395. parse_list,
  396. "The requires parameter is deprecated, please use "
  397. "install_requires for runtime dependencies.",
  398. SetuptoolsDeprecationWarning,
  399. ),
  400. 'obsoletes': parse_list,
  401. 'classifiers': self._get_parser_compound(parse_file, parse_list),
  402. 'license': exclude_files_parser('license'),
  403. 'license_file': self._deprecated_config_handler(
  404. exclude_files_parser('license_file'),
  405. "The license_file parameter is deprecated, "
  406. "use license_files instead.",
  407. SetuptoolsDeprecationWarning,
  408. ),
  409. 'license_files': parse_list,
  410. 'description': parse_file,
  411. 'long_description': parse_file,
  412. 'version': self._parse_version,
  413. 'project_urls': parse_dict,
  414. }
  415. def _parse_version(self, value):
  416. """Parses `version` option value.
  417. :param value:
  418. :rtype: str
  419. """
  420. version = self._parse_file(value, self.root_dir)
  421. if version != value:
  422. version = version.strip()
  423. # Be strict about versions loaded from file because it's easy to
  424. # accidentally include newlines and other unintended content
  425. try:
  426. Version(version)
  427. except InvalidVersion:
  428. tmpl = (
  429. 'Version loaded from {value} does not '
  430. 'comply with PEP 440: {version}'
  431. )
  432. raise DistutilsOptionError(tmpl.format(**locals()))
  433. return version
  434. return expand.version(self._parse_attr(value, self.package_dir, self.root_dir))
  435. class ConfigOptionsHandler(ConfigHandler["Distribution"]):
  436. section_prefix = 'options'
  437. def __init__(
  438. self,
  439. target_obj: "Distribution",
  440. options: AllCommandOptions,
  441. ignore_option_errors: bool,
  442. ensure_discovered: expand.EnsurePackagesDiscovered,
  443. ):
  444. super().__init__(target_obj, options, ignore_option_errors, ensure_discovered)
  445. self.root_dir = target_obj.src_root
  446. self.package_dir: Dict[str, str] = {} # To be filled by `find_packages`
  447. @classmethod
  448. def _parse_list_semicolon(cls, value):
  449. return cls._parse_list(value, separator=';')
  450. def _parse_file_in_root(self, value):
  451. return self._parse_file(value, root_dir=self.root_dir)
  452. def _parse_requirements_list(self, value):
  453. # Parse a requirements list, either by reading in a `file:`, or a list.
  454. parsed = self._parse_list_semicolon(self._parse_file_in_root(value))
  455. # Filter it to only include lines that are not comments. `parse_list`
  456. # will have stripped each line and filtered out empties.
  457. return [line for line in parsed if not line.startswith("#")]
  458. @property
  459. def parsers(self):
  460. """Metadata item name to parser function mapping."""
  461. parse_list = self._parse_list
  462. parse_bool = self._parse_bool
  463. parse_dict = self._parse_dict
  464. parse_cmdclass = self._parse_cmdclass
  465. return {
  466. 'zip_safe': parse_bool,
  467. 'include_package_data': parse_bool,
  468. 'package_dir': parse_dict,
  469. 'scripts': parse_list,
  470. 'eager_resources': parse_list,
  471. 'dependency_links': parse_list,
  472. 'namespace_packages': self._deprecated_config_handler(
  473. parse_list,
  474. "The namespace_packages parameter is deprecated, "
  475. "consider using implicit namespaces instead (PEP 420).",
  476. SetuptoolsDeprecationWarning,
  477. ),
  478. 'install_requires': self._parse_requirements_list,
  479. 'setup_requires': self._parse_list_semicolon,
  480. 'tests_require': self._parse_list_semicolon,
  481. 'packages': self._parse_packages,
  482. 'entry_points': self._parse_file_in_root,
  483. 'py_modules': parse_list,
  484. 'python_requires': SpecifierSet,
  485. 'cmdclass': parse_cmdclass,
  486. }
  487. def _parse_cmdclass(self, value):
  488. package_dir = self.ensure_discovered.package_dir
  489. return expand.cmdclass(self._parse_dict(value), package_dir, self.root_dir)
  490. def _parse_packages(self, value):
  491. """Parses `packages` option value.
  492. :param value:
  493. :rtype: list
  494. """
  495. find_directives = ['find:', 'find_namespace:']
  496. trimmed_value = value.strip()
  497. if trimmed_value not in find_directives:
  498. return self._parse_list(value)
  499. # Read function arguments from a dedicated section.
  500. find_kwargs = self.parse_section_packages__find(
  501. self.sections.get('packages.find', {})
  502. )
  503. find_kwargs.update(
  504. namespaces=(trimmed_value == find_directives[1]),
  505. root_dir=self.root_dir,
  506. fill_package_dir=self.package_dir,
  507. )
  508. return expand.find_packages(**find_kwargs)
  509. def parse_section_packages__find(self, section_options):
  510. """Parses `packages.find` configuration file section.
  511. To be used in conjunction with _parse_packages().
  512. :param dict section_options:
  513. """
  514. section_data = self._parse_section_to_dict(section_options, self._parse_list)
  515. valid_keys = ['where', 'include', 'exclude']
  516. find_kwargs = dict(
  517. [(k, v) for k, v in section_data.items() if k in valid_keys and v]
  518. )
  519. where = find_kwargs.get('where')
  520. if where is not None:
  521. find_kwargs['where'] = where[0] # cast list to single val
  522. return find_kwargs
  523. def parse_section_entry_points(self, section_options):
  524. """Parses `entry_points` configuration file section.
  525. :param dict section_options:
  526. """
  527. parsed = self._parse_section_to_dict(section_options, self._parse_list)
  528. self['entry_points'] = parsed
  529. def _parse_package_data(self, section_options):
  530. package_data = self._parse_section_to_dict(section_options, self._parse_list)
  531. return expand.canonic_package_data(package_data)
  532. def parse_section_package_data(self, section_options):
  533. """Parses `package_data` configuration file section.
  534. :param dict section_options:
  535. """
  536. self['package_data'] = self._parse_package_data(section_options)
  537. def parse_section_exclude_package_data(self, section_options):
  538. """Parses `exclude_package_data` configuration file section.
  539. :param dict section_options:
  540. """
  541. self['exclude_package_data'] = self._parse_package_data(section_options)
  542. def parse_section_extras_require(self, section_options):
  543. """Parses `extras_require` configuration file section.
  544. :param dict section_options:
  545. """
  546. parsed = self._parse_section_to_dict(
  547. section_options,
  548. self._parse_requirements_list,
  549. )
  550. self['extras_require'] = parsed
  551. def parse_section_data_files(self, section_options):
  552. """Parses `data_files` configuration file section.
  553. :param dict section_options:
  554. """
  555. parsed = self._parse_section_to_dict(section_options, self._parse_list)
  556. self['data_files'] = expand.canonic_data_files(parsed, self.root_dir)