dist.py 36 KB

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