25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 

1005 satır
38 KiB

  1. from __future__ import annotations
  2. import io
  3. import itertools
  4. import numbers
  5. import os
  6. import re
  7. import sys
  8. from collections.abc import Iterable, MutableMapping, Sequence
  9. from glob import iglob
  10. from pathlib import Path
  11. from typing import TYPE_CHECKING, Any, Union
  12. from more_itertools import partition, unique_everseen
  13. from packaging.markers import InvalidMarker, Marker
  14. from packaging.specifiers import InvalidSpecifier, SpecifierSet
  15. from packaging.version import Version
  16. from . import (
  17. _entry_points,
  18. _reqs,
  19. _static,
  20. command as _, # noqa: F401 # imported for side-effects
  21. )
  22. from ._importlib import metadata
  23. from ._path import StrPath
  24. from ._reqs import _StrOrIter
  25. from .config import pyprojecttoml, setupcfg
  26. from .discovery import ConfigDiscovery
  27. from .monkey import get_unpatched
  28. from .warnings import InformationOnly, SetuptoolsDeprecationWarning
  29. import distutils.cmd
  30. import distutils.command
  31. import distutils.core
  32. import distutils.dist
  33. import distutils.log
  34. from distutils.debug import DEBUG
  35. from distutils.errors import DistutilsOptionError, DistutilsSetupError
  36. from distutils.fancy_getopt import translate_longopt
  37. from distutils.util import strtobool
  38. if TYPE_CHECKING:
  39. from typing_extensions import TypeAlias
  40. from pkg_resources import Distribution as _pkg_resources_Distribution
  41. __all__ = ['Distribution']
  42. _sequence = tuple, list
  43. """
  44. :meta private:
  45. Supported iterable types that are known to be:
  46. - ordered (which `set` isn't)
  47. - not match a str (which `Sequence[str]` does)
  48. - not imply a nested type (like `dict`)
  49. for use with `isinstance`.
  50. """
  51. _Sequence: TypeAlias = Union[tuple[str, ...], list[str]]
  52. # This is how stringifying _Sequence would look in Python 3.10
  53. _sequence_type_repr = "tuple[str, ...] | list[str]"
  54. _OrderedStrSequence: TypeAlias = Union[str, dict[str, Any], Sequence[str]]
  55. """
  56. :meta private:
  57. Avoid single-use iterable. Disallow sets.
  58. A poor approximation of an OrderedSequence (dict doesn't match a Sequence).
  59. """
  60. def __getattr__(name: str) -> Any: # pragma: no cover
  61. if name == "sequence":
  62. SetuptoolsDeprecationWarning.emit(
  63. "`setuptools.dist.sequence` is an internal implementation detail.",
  64. "Please define your own `sequence = tuple, list` instead.",
  65. due_date=(2025, 8, 28), # Originally added on 2024-08-27
  66. )
  67. return _sequence
  68. raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
  69. def check_importable(dist, attr, value):
  70. try:
  71. ep = metadata.EntryPoint(value=value, name=None, group=None)
  72. assert not ep.extras
  73. except (TypeError, ValueError, AttributeError, AssertionError) as e:
  74. raise DistutilsSetupError(
  75. f"{attr!r} must be importable 'module:attrs' string (got {value!r})"
  76. ) from e
  77. def assert_string_list(dist, attr: str, value: _Sequence) -> None:
  78. """Verify that value is a string list"""
  79. try:
  80. # verify that value is a list or tuple to exclude unordered
  81. # or single-use iterables
  82. assert isinstance(value, _sequence)
  83. # verify that elements of value are strings
  84. assert ''.join(value) != value
  85. except (TypeError, ValueError, AttributeError, AssertionError) as e:
  86. raise DistutilsSetupError(
  87. f"{attr!r} must be of type <{_sequence_type_repr}> (got {value!r})"
  88. ) from e
  89. def check_nsp(dist, attr, value):
  90. """Verify that namespace packages are valid"""
  91. ns_packages = value
  92. assert_string_list(dist, attr, ns_packages)
  93. for nsp in ns_packages:
  94. if not dist.has_contents_for(nsp):
  95. raise DistutilsSetupError(
  96. f"Distribution contains no modules or packages for namespace package {nsp!r}"
  97. )
  98. parent, _sep, _child = nsp.rpartition('.')
  99. if parent and parent not in ns_packages:
  100. distutils.log.warn(
  101. "WARNING: %r is declared as a package namespace, but %r"
  102. " is not: please correct this in setup.py",
  103. nsp,
  104. parent,
  105. )
  106. SetuptoolsDeprecationWarning.emit(
  107. "The namespace_packages parameter is deprecated.",
  108. "Please replace its usage with implicit namespaces (PEP 420).",
  109. see_docs="references/keywords.html#keyword-namespace-packages",
  110. # TODO: define due_date, it may break old packages that are no longer
  111. # maintained (e.g. sphinxcontrib extensions) when installed from source.
  112. # Warning officially introduced in May 2022, however the deprecation
  113. # was mentioned much earlier in the docs (May 2020, see #2149).
  114. )
  115. def check_extras(dist, attr, value):
  116. """Verify that extras_require mapping is valid"""
  117. try:
  118. list(itertools.starmap(_check_extra, value.items()))
  119. except (TypeError, ValueError, AttributeError) as e:
  120. raise DistutilsSetupError(
  121. "'extras_require' must be a dictionary whose values are "
  122. "strings or lists of strings containing valid project/version "
  123. "requirement specifiers."
  124. ) from e
  125. def _check_extra(extra, reqs):
  126. _name, _sep, marker = extra.partition(':')
  127. try:
  128. _check_marker(marker)
  129. except InvalidMarker:
  130. msg = f"Invalid environment marker: {marker} ({extra!r})"
  131. raise DistutilsSetupError(msg) from None
  132. list(_reqs.parse(reqs))
  133. def _check_marker(marker):
  134. if not marker:
  135. return
  136. m = Marker(marker)
  137. m.evaluate()
  138. def assert_bool(dist, attr, value):
  139. """Verify that value is True, False, 0, or 1"""
  140. if bool(value) != value:
  141. raise DistutilsSetupError(f"{attr!r} must be a boolean value (got {value!r})")
  142. def invalid_unless_false(dist, attr, value):
  143. if not value:
  144. DistDeprecationWarning.emit(f"{attr} is ignored.")
  145. # TODO: should there be a `due_date` here?
  146. return
  147. raise DistutilsSetupError(f"{attr} is invalid.")
  148. def check_requirements(dist, attr: str, value: _OrderedStrSequence) -> None:
  149. """Verify that install_requires is a valid requirements list"""
  150. try:
  151. list(_reqs.parse(value))
  152. if isinstance(value, set):
  153. raise TypeError("Unordered types are not allowed")
  154. except (TypeError, ValueError) as error:
  155. msg = (
  156. f"{attr!r} must be a string or iterable of strings "
  157. f"containing valid project/version requirement specifiers; {error}"
  158. )
  159. raise DistutilsSetupError(msg) from error
  160. def check_specifier(dist, attr, value):
  161. """Verify that value is a valid version specifier"""
  162. try:
  163. SpecifierSet(value)
  164. except (InvalidSpecifier, AttributeError) as error:
  165. msg = f"{attr!r} must be a string containing valid version specifiers; {error}"
  166. raise DistutilsSetupError(msg) from error
  167. def check_entry_points(dist, attr, value):
  168. """Verify that entry_points map is parseable"""
  169. try:
  170. _entry_points.load(value)
  171. except Exception as e:
  172. raise DistutilsSetupError(e) from e
  173. def check_package_data(dist, attr, value):
  174. """Verify that value is a dictionary of package names to glob lists"""
  175. if not isinstance(value, dict):
  176. raise DistutilsSetupError(
  177. f"{attr!r} must be a dictionary mapping package names to lists of "
  178. "string wildcard patterns"
  179. )
  180. for k, v in value.items():
  181. if not isinstance(k, str):
  182. raise DistutilsSetupError(
  183. f"keys of {attr!r} dict must be strings (got {k!r})"
  184. )
  185. assert_string_list(dist, f'values of {attr!r} dict', v)
  186. def check_packages(dist, attr, value):
  187. for pkgname in value:
  188. if not re.match(r'\w+(\.\w+)*', pkgname):
  189. distutils.log.warn(
  190. "WARNING: %r not a valid package name; please use only "
  191. ".-separated package names in setup.py",
  192. pkgname,
  193. )
  194. if TYPE_CHECKING:
  195. # Work around a mypy issue where type[T] can't be used as a base: https://github.com/python/mypy/issues/10962
  196. from distutils.core import Distribution as _Distribution
  197. else:
  198. _Distribution = get_unpatched(distutils.core.Distribution)
  199. class Distribution(_Distribution):
  200. """Distribution with support for tests and package data
  201. This is an enhanced version of 'distutils.dist.Distribution' that
  202. effectively adds the following new optional keyword arguments to 'setup()':
  203. 'install_requires' -- a string or sequence of strings specifying project
  204. versions that the distribution requires when installed, in the format
  205. used by 'pkg_resources.require()'. They will be installed
  206. automatically when the package is installed. If you wish to use
  207. packages that are not available in PyPI, or want to give your users an
  208. alternate download location, you can add a 'find_links' option to the
  209. '[easy_install]' section of your project's 'setup.cfg' file, and then
  210. setuptools will scan the listed web pages for links that satisfy the
  211. requirements.
  212. 'extras_require' -- a dictionary mapping names of optional "extras" to the
  213. additional requirement(s) that using those extras incurs. For example,
  214. this::
  215. extras_require = dict(reST = ["docutils>=0.3", "reSTedit"])
  216. indicates that the distribution can optionally provide an extra
  217. capability called "reST", but it can only be used if docutils and
  218. reSTedit are installed. If the user installs your package using
  219. EasyInstall and requests one of your extras, the corresponding
  220. additional requirements will be installed if needed.
  221. 'package_data' -- a dictionary mapping package names to lists of filenames
  222. or globs to use to find data files contained in the named packages.
  223. If the dictionary has filenames or globs listed under '""' (the empty
  224. string), those names will be searched for in every package, in addition
  225. to any names for the specific package. Data files found using these
  226. names/globs will be installed along with the package, in the same
  227. location as the package. Note that globs are allowed to reference
  228. the contents of non-package subdirectories, as long as you use '/' as
  229. a path separator. (Globs are automatically converted to
  230. platform-specific paths at runtime.)
  231. In addition to these new keywords, this class also has several new methods
  232. for manipulating the distribution's contents. For example, the 'include()'
  233. and 'exclude()' methods can be thought of as in-place add and subtract
  234. commands that add or remove packages, modules, extensions, and so on from
  235. the distribution.
  236. """
  237. _DISTUTILS_UNSUPPORTED_METADATA = {
  238. 'long_description_content_type': lambda: None,
  239. 'project_urls': dict,
  240. 'provides_extras': dict, # behaves like an ordered set
  241. 'license_file': lambda: None,
  242. 'license_files': lambda: None,
  243. 'install_requires': list,
  244. 'extras_require': dict,
  245. }
  246. # Used by build_py, editable_wheel and install_lib commands for legacy namespaces
  247. namespace_packages: list[str] #: :meta private: DEPRECATED
  248. # Any: Dynamic assignment results in Incompatible types in assignment
  249. def __init__(self, attrs: MutableMapping[str, Any] | None = None) -> None:
  250. have_package_data = hasattr(self, "package_data")
  251. if not have_package_data:
  252. self.package_data: dict[str, list[str]] = {}
  253. attrs = attrs or {}
  254. self.dist_files: list[tuple[str, str, str]] = []
  255. self.include_package_data: bool | None = None
  256. self.exclude_package_data: dict[str, list[str]] | None = None
  257. # Filter-out setuptools' specific options.
  258. self.src_root: str | None = attrs.pop("src_root", None)
  259. self.dependency_links: list[str] = attrs.pop('dependency_links', [])
  260. self.setup_requires: list[str] = attrs.pop('setup_requires', [])
  261. for ep in metadata.entry_points(group='distutils.setup_keywords'):
  262. vars(self).setdefault(ep.name, None)
  263. metadata_only = set(self._DISTUTILS_UNSUPPORTED_METADATA)
  264. metadata_only -= {"install_requires", "extras_require"}
  265. dist_attrs = {k: v for k, v in attrs.items() if k not in metadata_only}
  266. _Distribution.__init__(self, dist_attrs)
  267. # Private API (setuptools-use only, not restricted to Distribution)
  268. # Stores files that are referenced by the configuration and need to be in the
  269. # sdist (e.g. `version = file: VERSION.txt`)
  270. self._referenced_files = set[str]()
  271. self.set_defaults = ConfigDiscovery(self)
  272. self._set_metadata_defaults(attrs)
  273. self.metadata.version = self._normalize_version(self.metadata.version)
  274. self._finalize_requires()
  275. def _validate_metadata(self):
  276. required = {"name"}
  277. provided = {
  278. key
  279. for key in vars(self.metadata)
  280. if getattr(self.metadata, key, None) is not None
  281. }
  282. missing = required - provided
  283. if missing:
  284. msg = f"Required package metadata is missing: {missing}"
  285. raise DistutilsSetupError(msg)
  286. def _set_metadata_defaults(self, attrs):
  287. """
  288. Fill-in missing metadata fields not supported by distutils.
  289. Some fields may have been set by other tools (e.g. pbr).
  290. Those fields (vars(self.metadata)) take precedence to
  291. supplied attrs.
  292. """
  293. for option, default in self._DISTUTILS_UNSUPPORTED_METADATA.items():
  294. vars(self.metadata).setdefault(option, attrs.get(option, default()))
  295. @staticmethod
  296. def _normalize_version(version):
  297. from . import sic
  298. if isinstance(version, numbers.Number):
  299. # Some people apparently take "version number" too literally :)
  300. version = str(version)
  301. elif isinstance(version, sic) or version is None:
  302. return version
  303. normalized = str(Version(version))
  304. if version != normalized:
  305. InformationOnly.emit(f"Normalizing '{version}' to '{normalized}'")
  306. return normalized
  307. return version
  308. def _finalize_requires(self):
  309. """
  310. Set `metadata.python_requires` and fix environment markers
  311. in `install_requires` and `extras_require`.
  312. """
  313. if getattr(self, 'python_requires', None):
  314. self.metadata.python_requires = self.python_requires
  315. self._normalize_requires()
  316. self.metadata.install_requires = self.install_requires
  317. self.metadata.extras_require = self.extras_require
  318. if self.extras_require:
  319. for extra in self.extras_require.keys():
  320. # Setuptools allows a weird "<name>:<env markers> syntax for extras
  321. extra = extra.split(':')[0]
  322. if extra:
  323. self.metadata.provides_extras.setdefault(extra)
  324. def _normalize_requires(self):
  325. """Make sure requirement-related attributes exist and are normalized"""
  326. install_requires = getattr(self, "install_requires", None) or []
  327. extras_require = getattr(self, "extras_require", None) or {}
  328. # Preserve the "static"-ness of values parsed from config files
  329. list_ = _static.List if _static.is_static(install_requires) else list
  330. self.install_requires = list_(map(str, _reqs.parse(install_requires)))
  331. dict_ = _static.Dict if _static.is_static(extras_require) else dict
  332. self.extras_require = dict_(
  333. (k, list(map(str, _reqs.parse(v or [])))) for k, v in extras_require.items()
  334. )
  335. def _finalize_license_files(self) -> None:
  336. """Compute names of all license files which should be included."""
  337. license_files: list[str] | None = self.metadata.license_files
  338. patterns = license_files or []
  339. license_file: str | None = self.metadata.license_file
  340. if license_file and license_file not in patterns:
  341. patterns.append(license_file)
  342. if license_files is None and license_file is None:
  343. # Default patterns match the ones wheel uses
  344. # See https://wheel.readthedocs.io/en/stable/user_guide.html
  345. # -> 'Including license files in the generated wheel file'
  346. patterns = ['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']
  347. self.metadata.license_files = list(
  348. unique_everseen(self._expand_patterns(patterns))
  349. )
  350. @staticmethod
  351. def _expand_patterns(patterns):
  352. """
  353. >>> list(Distribution._expand_patterns(['LICENSE']))
  354. ['LICENSE']
  355. >>> list(Distribution._expand_patterns(['pyproject.toml', 'LIC*']))
  356. ['pyproject.toml', 'LICENSE']
  357. """
  358. return (
  359. path
  360. for pattern in patterns
  361. for path in sorted(iglob(pattern))
  362. if not path.endswith('~') and os.path.isfile(path)
  363. )
  364. # FIXME: 'Distribution._parse_config_files' is too complex (14)
  365. def _parse_config_files(self, filenames=None): # noqa: C901
  366. """
  367. Adapted from distutils.dist.Distribution.parse_config_files,
  368. this method provides the same functionality in subtly-improved
  369. ways.
  370. """
  371. from configparser import ConfigParser
  372. # Ignore install directory options if we have a venv
  373. ignore_options = (
  374. []
  375. if sys.prefix == sys.base_prefix
  376. else [
  377. 'install-base',
  378. 'install-platbase',
  379. 'install-lib',
  380. 'install-platlib',
  381. 'install-purelib',
  382. 'install-headers',
  383. 'install-scripts',
  384. 'install-data',
  385. 'prefix',
  386. 'exec-prefix',
  387. 'home',
  388. 'user',
  389. 'root',
  390. ]
  391. )
  392. ignore_options = frozenset(ignore_options)
  393. if filenames is None:
  394. filenames = self.find_config_files()
  395. if DEBUG:
  396. self.announce("Distribution.parse_config_files():")
  397. parser = ConfigParser()
  398. parser.optionxform = str
  399. for filename in filenames:
  400. with open(filename, encoding='utf-8') as reader:
  401. if DEBUG:
  402. self.announce(" reading {filename}".format(**locals()))
  403. parser.read_file(reader)
  404. for section in parser.sections():
  405. options = parser.options(section)
  406. opt_dict = self.get_option_dict(section)
  407. for opt in options:
  408. if opt == '__name__' or opt in ignore_options:
  409. continue
  410. val = parser.get(section, opt)
  411. opt = self.warn_dash_deprecation(opt, section)
  412. opt = self.make_option_lowercase(opt, section)
  413. opt_dict[opt] = (filename, val)
  414. # Make the ConfigParser forget everything (so we retain
  415. # the original filenames that options come from)
  416. parser.__init__()
  417. if 'global' not in self.command_options:
  418. return
  419. # If there was a "global" section in the config file, use it
  420. # to set Distribution options.
  421. for opt, (src, val) in self.command_options['global'].items():
  422. alias = self.negative_opt.get(opt)
  423. if alias:
  424. val = not strtobool(val)
  425. elif opt in ('verbose', 'dry_run'): # ugh!
  426. val = strtobool(val)
  427. try:
  428. setattr(self, alias or opt, val)
  429. except ValueError as e:
  430. raise DistutilsOptionError(e) from e
  431. def warn_dash_deprecation(self, opt: str, section: str) -> str:
  432. if section in (
  433. 'options.extras_require',
  434. 'options.data_files',
  435. ):
  436. return opt
  437. underscore_opt = opt.replace('-', '_')
  438. commands = list(
  439. itertools.chain(
  440. distutils.command.__all__,
  441. self._setuptools_commands(),
  442. )
  443. )
  444. if (
  445. not section.startswith('options')
  446. and section != 'metadata'
  447. and section not in commands
  448. ):
  449. return underscore_opt
  450. if '-' in opt:
  451. SetuptoolsDeprecationWarning.emit(
  452. "Invalid dash-separated options",
  453. f"""
  454. Usage of dash-separated {opt!r} will not be supported in future
  455. versions. Please use the underscore name {underscore_opt!r} instead.
  456. """,
  457. see_docs="userguide/declarative_config.html",
  458. due_date=(2025, 3, 3),
  459. # Warning initially introduced in 3 Mar 2021
  460. )
  461. return underscore_opt
  462. def _setuptools_commands(self):
  463. try:
  464. entry_points = metadata.distribution('setuptools').entry_points
  465. return {ep.name for ep in entry_points} # Avoid newer API for compatibility
  466. except metadata.PackageNotFoundError:
  467. # during bootstrapping, distribution doesn't exist
  468. return []
  469. def make_option_lowercase(self, opt: str, section: str) -> str:
  470. if section != 'metadata' or opt.islower():
  471. return opt
  472. lowercase_opt = opt.lower()
  473. SetuptoolsDeprecationWarning.emit(
  474. "Invalid uppercase configuration",
  475. f"""
  476. Usage of uppercase key {opt!r} in {section!r} will not be supported in
  477. future versions. Please use lowercase {lowercase_opt!r} instead.
  478. """,
  479. see_docs="userguide/declarative_config.html",
  480. due_date=(2025, 3, 3),
  481. # Warning initially introduced in 6 Mar 2021
  482. )
  483. return lowercase_opt
  484. # FIXME: 'Distribution._set_command_options' is too complex (14)
  485. def _set_command_options(self, command_obj, option_dict=None): # noqa: C901
  486. """
  487. Set the options for 'command_obj' from 'option_dict'. Basically
  488. this means copying elements of a dictionary ('option_dict') to
  489. attributes of an instance ('command').
  490. 'command_obj' must be a Command instance. If 'option_dict' is not
  491. supplied, uses the standard option dictionary for this command
  492. (from 'self.command_options').
  493. (Adopted from distutils.dist.Distribution._set_command_options)
  494. """
  495. command_name = command_obj.get_command_name()
  496. if option_dict is None:
  497. option_dict = self.get_option_dict(command_name)
  498. if DEBUG:
  499. self.announce(f" setting options for '{command_name}' command:")
  500. for option, (source, value) in option_dict.items():
  501. if DEBUG:
  502. self.announce(f" {option} = {value} (from {source})")
  503. try:
  504. bool_opts = [translate_longopt(o) for o in command_obj.boolean_options]
  505. except AttributeError:
  506. bool_opts = []
  507. try:
  508. neg_opt = command_obj.negative_opt
  509. except AttributeError:
  510. neg_opt = {}
  511. try:
  512. is_string = isinstance(value, str)
  513. if option in neg_opt and is_string:
  514. setattr(command_obj, neg_opt[option], not strtobool(value))
  515. elif option in bool_opts and is_string:
  516. setattr(command_obj, option, strtobool(value))
  517. elif hasattr(command_obj, option):
  518. setattr(command_obj, option, value)
  519. else:
  520. raise DistutilsOptionError(
  521. f"error in {source}: command '{command_name}' has no such option '{option}'"
  522. )
  523. except ValueError as e:
  524. raise DistutilsOptionError(e) from e
  525. def _get_project_config_files(self, filenames: Iterable[StrPath] | None):
  526. """Add default file and split between INI and TOML"""
  527. tomlfiles = []
  528. standard_project_metadata = Path(self.src_root or os.curdir, "pyproject.toml")
  529. if filenames is not None:
  530. parts = partition(lambda f: Path(f).suffix == ".toml", filenames)
  531. filenames = list(parts[0]) # 1st element => predicate is False
  532. tomlfiles = list(parts[1]) # 2nd element => predicate is True
  533. elif standard_project_metadata.exists():
  534. tomlfiles = [standard_project_metadata]
  535. return filenames, tomlfiles
  536. def parse_config_files(
  537. self,
  538. filenames: Iterable[StrPath] | None = None,
  539. ignore_option_errors: bool = False,
  540. ) -> None:
  541. """Parses configuration files from various levels
  542. and loads configuration.
  543. """
  544. inifiles, tomlfiles = self._get_project_config_files(filenames)
  545. self._parse_config_files(filenames=inifiles)
  546. setupcfg.parse_configuration(
  547. self, self.command_options, ignore_option_errors=ignore_option_errors
  548. )
  549. for filename in tomlfiles:
  550. pyprojecttoml.apply_configuration(self, filename, ignore_option_errors)
  551. self._finalize_requires()
  552. self._finalize_license_files()
  553. def fetch_build_eggs(
  554. self, requires: _StrOrIter
  555. ) -> list[_pkg_resources_Distribution]:
  556. """Resolve pre-setup requirements"""
  557. from .installer import _fetch_build_eggs
  558. return _fetch_build_eggs(self, requires)
  559. def finalize_options(self) -> None:
  560. """
  561. Allow plugins to apply arbitrary operations to the
  562. distribution. Each hook may optionally define a 'order'
  563. to influence the order of execution. Smaller numbers
  564. go first and the default is 0.
  565. """
  566. group = 'setuptools.finalize_distribution_options'
  567. def by_order(hook):
  568. return getattr(hook, 'order', 0)
  569. defined = metadata.entry_points(group=group)
  570. filtered = itertools.filterfalse(self._removed, defined)
  571. loaded = map(lambda e: e.load(), filtered)
  572. for ep in sorted(loaded, key=by_order):
  573. ep(self)
  574. @staticmethod
  575. def _removed(ep):
  576. """
  577. When removing an entry point, if metadata is loaded
  578. from an older version of Setuptools, that removed
  579. entry point will attempt to be loaded and will fail.
  580. See #2765 for more details.
  581. """
  582. removed = {
  583. # removed 2021-09-05
  584. '2to3_doctests',
  585. }
  586. return ep.name in removed
  587. def _finalize_setup_keywords(self):
  588. for ep in metadata.entry_points(group='distutils.setup_keywords'):
  589. value = getattr(self, ep.name, None)
  590. if value is not None:
  591. ep.load()(self, ep.name, value)
  592. def get_egg_cache_dir(self):
  593. from . import windows_support
  594. egg_cache_dir = os.path.join(os.curdir, '.eggs')
  595. if not os.path.exists(egg_cache_dir):
  596. os.mkdir(egg_cache_dir)
  597. windows_support.hide_file(egg_cache_dir)
  598. readme_txt_filename = os.path.join(egg_cache_dir, 'README.txt')
  599. with open(readme_txt_filename, 'w', encoding="utf-8") as f:
  600. f.write(
  601. 'This directory contains eggs that were downloaded '
  602. 'by setuptools to build, test, and run plug-ins.\n\n'
  603. )
  604. f.write(
  605. 'This directory caches those eggs to prevent '
  606. 'repeated downloads.\n\n'
  607. )
  608. f.write('However, it is safe to delete this directory.\n\n')
  609. return egg_cache_dir
  610. def fetch_build_egg(self, req):
  611. """Fetch an egg needed for building"""
  612. from .installer import fetch_build_egg
  613. return fetch_build_egg(self, req)
  614. def get_command_class(self, command: str) -> type[distutils.cmd.Command]: # type: ignore[override] # Not doing complex overrides yet
  615. """Pluggable version of get_command_class()"""
  616. if command in self.cmdclass:
  617. return self.cmdclass[command]
  618. # Special case bdist_wheel so it's never loaded from "wheel"
  619. if command == 'bdist_wheel':
  620. from .command.bdist_wheel import bdist_wheel
  621. return bdist_wheel
  622. eps = metadata.entry_points(group='distutils.commands', name=command)
  623. for ep in eps:
  624. self.cmdclass[command] = cmdclass = ep.load()
  625. return cmdclass
  626. else:
  627. return _Distribution.get_command_class(self, command)
  628. def print_commands(self):
  629. for ep in metadata.entry_points(group='distutils.commands'):
  630. if ep.name not in self.cmdclass:
  631. cmdclass = ep.load()
  632. self.cmdclass[ep.name] = cmdclass
  633. return _Distribution.print_commands(self)
  634. def get_command_list(self):
  635. for ep in metadata.entry_points(group='distutils.commands'):
  636. if ep.name not in self.cmdclass:
  637. cmdclass = ep.load()
  638. self.cmdclass[ep.name] = cmdclass
  639. return _Distribution.get_command_list(self)
  640. def include(self, **attrs) -> None:
  641. """Add items to distribution that are named in keyword arguments
  642. For example, 'dist.include(py_modules=["x"])' would add 'x' to
  643. the distribution's 'py_modules' attribute, if it was not already
  644. there.
  645. Currently, this method only supports inclusion for attributes that are
  646. lists or tuples. If you need to add support for adding to other
  647. attributes in this or a subclass, you can add an '_include_X' method,
  648. where 'X' is the name of the attribute. The method will be called with
  649. the value passed to 'include()'. So, 'dist.include(foo={"bar":"baz"})'
  650. will try to call 'dist._include_foo({"bar":"baz"})', which can then
  651. handle whatever special inclusion logic is needed.
  652. """
  653. for k, v in attrs.items():
  654. include = getattr(self, '_include_' + k, None)
  655. if include:
  656. include(v)
  657. else:
  658. self._include_misc(k, v)
  659. def exclude_package(self, package: str) -> None:
  660. """Remove packages, modules, and extensions in named package"""
  661. pfx = package + '.'
  662. if self.packages:
  663. self.packages = [
  664. p for p in self.packages if p != package and not p.startswith(pfx)
  665. ]
  666. if self.py_modules:
  667. self.py_modules = [
  668. p for p in self.py_modules if p != package and not p.startswith(pfx)
  669. ]
  670. if self.ext_modules:
  671. self.ext_modules = [
  672. p
  673. for p in self.ext_modules
  674. if p.name != package and not p.name.startswith(pfx)
  675. ]
  676. def has_contents_for(self, package: str) -> bool:
  677. """Return true if 'exclude_package(package)' would do something"""
  678. pfx = package + '.'
  679. for p in self.iter_distribution_names():
  680. if p == package or p.startswith(pfx):
  681. return True
  682. return False
  683. def _exclude_misc(self, name: str, value: _Sequence) -> None:
  684. """Handle 'exclude()' for list/tuple attrs without a special handler"""
  685. if not isinstance(value, _sequence):
  686. raise DistutilsSetupError(
  687. f"{name}: setting must be of type <{_sequence_type_repr}> (got {value!r})"
  688. )
  689. try:
  690. old = getattr(self, name)
  691. except AttributeError as e:
  692. raise DistutilsSetupError(f"{name}: No such distribution setting") from e
  693. if old is not None and not isinstance(old, _sequence):
  694. raise DistutilsSetupError(
  695. name + ": this setting cannot be changed via include/exclude"
  696. )
  697. elif old:
  698. setattr(self, name, [item for item in old if item not in value])
  699. def _include_misc(self, name: str, value: _Sequence) -> None:
  700. """Handle 'include()' for list/tuple attrs without a special handler"""
  701. if not isinstance(value, _sequence):
  702. raise DistutilsSetupError(
  703. f"{name}: setting must be of type <{_sequence_type_repr}> (got {value!r})"
  704. )
  705. try:
  706. old = getattr(self, name)
  707. except AttributeError as e:
  708. raise DistutilsSetupError(f"{name}: No such distribution setting") from e
  709. if old is None:
  710. setattr(self, name, value)
  711. elif not isinstance(old, _sequence):
  712. raise DistutilsSetupError(
  713. name + ": this setting cannot be changed via include/exclude"
  714. )
  715. else:
  716. new = [item for item in value if item not in old]
  717. setattr(self, name, list(old) + new)
  718. def exclude(self, **attrs) -> None:
  719. """Remove items from distribution that are named in keyword arguments
  720. For example, 'dist.exclude(py_modules=["x"])' would remove 'x' from
  721. the distribution's 'py_modules' attribute. Excluding packages uses
  722. the 'exclude_package()' method, so all of the package's contained
  723. packages, modules, and extensions are also excluded.
  724. Currently, this method only supports exclusion from attributes that are
  725. lists or tuples. If you need to add support for excluding from other
  726. attributes in this or a subclass, you can add an '_exclude_X' method,
  727. where 'X' is the name of the attribute. The method will be called with
  728. the value passed to 'exclude()'. So, 'dist.exclude(foo={"bar":"baz"})'
  729. will try to call 'dist._exclude_foo({"bar":"baz"})', which can then
  730. handle whatever special exclusion logic is needed.
  731. """
  732. for k, v in attrs.items():
  733. exclude = getattr(self, '_exclude_' + k, None)
  734. if exclude:
  735. exclude(v)
  736. else:
  737. self._exclude_misc(k, v)
  738. def _exclude_packages(self, packages: _Sequence) -> None:
  739. if not isinstance(packages, _sequence):
  740. raise DistutilsSetupError(
  741. f"packages: setting must be of type <{_sequence_type_repr}> (got {packages!r})"
  742. )
  743. list(map(self.exclude_package, packages))
  744. def _parse_command_opts(self, parser, args):
  745. # Remove --with-X/--without-X options when processing command args
  746. self.global_options = self.__class__.global_options
  747. self.negative_opt = self.__class__.negative_opt
  748. # First, expand any aliases
  749. command = args[0]
  750. aliases = self.get_option_dict('aliases')
  751. while command in aliases:
  752. _src, alias = aliases[command]
  753. del aliases[command] # ensure each alias can expand only once!
  754. import shlex
  755. args[:1] = shlex.split(alias, True)
  756. command = args[0]
  757. nargs = _Distribution._parse_command_opts(self, parser, args)
  758. # Handle commands that want to consume all remaining arguments
  759. cmd_class = self.get_command_class(command)
  760. if getattr(cmd_class, 'command_consumes_arguments', None):
  761. self.get_option_dict(command)['args'] = ("command line", nargs)
  762. if nargs is not None:
  763. return []
  764. return nargs
  765. def get_cmdline_options(self) -> dict[str, dict[str, str | None]]:
  766. """Return a '{cmd: {opt:val}}' map of all command-line options
  767. Option names are all long, but do not include the leading '--', and
  768. contain dashes rather than underscores. If the option doesn't take
  769. an argument (e.g. '--quiet'), the 'val' is 'None'.
  770. Note that options provided by config files are intentionally excluded.
  771. """
  772. d: dict[str, dict[str, str | None]] = {}
  773. for cmd, opts in self.command_options.items():
  774. val: str | None
  775. for opt, (src, val) in opts.items():
  776. if src != "command line":
  777. continue
  778. opt = opt.replace('_', '-')
  779. if val == 0:
  780. cmdobj = self.get_command_obj(cmd)
  781. neg_opt = self.negative_opt.copy()
  782. neg_opt.update(getattr(cmdobj, 'negative_opt', {}))
  783. for neg, pos in neg_opt.items():
  784. if pos == opt:
  785. opt = neg
  786. val = None
  787. break
  788. else:
  789. raise AssertionError("Shouldn't be able to get here")
  790. elif val == 1:
  791. val = None
  792. d.setdefault(cmd, {})[opt] = val
  793. return d
  794. def iter_distribution_names(self):
  795. """Yield all packages, modules, and extension names in distribution"""
  796. yield from self.packages or ()
  797. yield from self.py_modules or ()
  798. for ext in self.ext_modules or ():
  799. if isinstance(ext, tuple):
  800. name, _buildinfo = ext
  801. else:
  802. name = ext.name
  803. if name.endswith('module'):
  804. name = name[:-6]
  805. yield name
  806. def handle_display_options(self, option_order):
  807. """If there were any non-global "display-only" options
  808. (--help-commands or the metadata display options) on the command
  809. line, display the requested info and return true; else return
  810. false.
  811. """
  812. import sys
  813. if self.help_commands:
  814. return _Distribution.handle_display_options(self, option_order)
  815. # Stdout may be StringIO (e.g. in tests)
  816. if not isinstance(sys.stdout, io.TextIOWrapper):
  817. return _Distribution.handle_display_options(self, option_order)
  818. # Don't wrap stdout if utf-8 is already the encoding. Provides
  819. # workaround for #334.
  820. if sys.stdout.encoding.lower() in ('utf-8', 'utf8'):
  821. return _Distribution.handle_display_options(self, option_order)
  822. # Print metadata in UTF-8 no matter the platform
  823. encoding = sys.stdout.encoding
  824. sys.stdout.reconfigure(encoding='utf-8')
  825. try:
  826. return _Distribution.handle_display_options(self, option_order)
  827. finally:
  828. sys.stdout.reconfigure(encoding=encoding)
  829. def run_command(self, command) -> None:
  830. self.set_defaults()
  831. # Postpone defaults until all explicit configuration is considered
  832. # (setup() args, config files, command line and plugins)
  833. super().run_command(command)
  834. class DistDeprecationWarning(SetuptoolsDeprecationWarning):
  835. """Class for warning about deprecations in dist in
  836. setuptools. Not ignored by default, unlike DeprecationWarning."""