setupcfg.py 26 KB

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