dist.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  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 InvalidVersion, 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(
  259. self._validate_version(self.metadata.version)
  260. )
  261. self._finalize_requires()
  262. def _validate_metadata(self):
  263. required = {"name"}
  264. provided = {
  265. key
  266. for key in vars(self.metadata)
  267. if getattr(self.metadata, key, None) is not None
  268. }
  269. missing = required - provided
  270. if missing:
  271. msg = f"Required package metadata is missing: {missing}"
  272. raise DistutilsSetupError(msg)
  273. def _set_metadata_defaults(self, attrs):
  274. """
  275. Fill-in missing metadata fields not supported by distutils.
  276. Some fields may have been set by other tools (e.g. pbr).
  277. Those fields (vars(self.metadata)) take precedence to
  278. supplied attrs.
  279. """
  280. for option, default in self._DISTUTILS_UNSUPPORTED_METADATA.items():
  281. vars(self.metadata).setdefault(option, attrs.get(option, default()))
  282. @staticmethod
  283. def _normalize_version(version):
  284. from . import sic
  285. if isinstance(version, sic) or version is None:
  286. return version
  287. normalized = str(Version(version))
  288. if version != normalized:
  289. InformationOnly.emit(f"Normalizing '{version}' to '{normalized}'")
  290. return normalized
  291. return version
  292. @staticmethod
  293. def _validate_version(version):
  294. if isinstance(version, numbers.Number):
  295. # Some people apparently take "version number" too literally :)
  296. version = str(version)
  297. if version is not None:
  298. try:
  299. Version(version)
  300. except (InvalidVersion, TypeError):
  301. from . import sic
  302. SetuptoolsDeprecationWarning.emit(
  303. f"Invalid version: {version!r}.",
  304. """
  305. The version specified is not a valid version according to PEP 440.
  306. This may not work as expected with newer versions of
  307. setuptools, pip, and PyPI.
  308. """,
  309. see_url="https://peps.python.org/pep-0440/",
  310. due_date=(2023, 9, 26),
  311. # Warning initially introduced in 26 Sept 2014
  312. # pypa/packaging already removed legacy versions.
  313. )
  314. return sic(version)
  315. return version
  316. def _finalize_requires(self):
  317. """
  318. Set `metadata.python_requires` and fix environment markers
  319. in `install_requires` and `extras_require`.
  320. """
  321. if getattr(self, 'python_requires', None):
  322. self.metadata.python_requires = self.python_requires
  323. self._normalize_requires()
  324. self.metadata.install_requires = self.install_requires
  325. self.metadata.extras_require = self.extras_require
  326. if self.extras_require:
  327. for extra in self.extras_require.keys():
  328. # Setuptools allows a weird "<name>:<env markers> syntax for extras
  329. extra = extra.split(':')[0]
  330. if extra:
  331. self.metadata.provides_extras.add(extra)
  332. def _normalize_requires(self):
  333. """Make sure requirement-related attributes exist and are normalized"""
  334. install_requires = getattr(self, "install_requires", None) or []
  335. extras_require = getattr(self, "extras_require", None) or {}
  336. self.install_requires = list(map(str, _reqs.parse(install_requires)))
  337. self.extras_require = {
  338. k: list(map(str, _reqs.parse(v or []))) for k, v in extras_require.items()
  339. }
  340. def _finalize_license_files(self):
  341. """Compute names of all license files which should be included."""
  342. license_files: Optional[List[str]] = self.metadata.license_files
  343. patterns: List[str] = license_files if license_files else []
  344. license_file: Optional[str] = self.metadata.license_file
  345. if license_file and license_file not in patterns:
  346. patterns.append(license_file)
  347. if license_files is None and license_file is None:
  348. # Default patterns match the ones wheel uses
  349. # See https://wheel.readthedocs.io/en/stable/user_guide.html
  350. # -> 'Including license files in the generated wheel file'
  351. patterns = ('LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*')
  352. self.metadata.license_files = list(
  353. unique_everseen(self._expand_patterns(patterns))
  354. )
  355. @staticmethod
  356. def _expand_patterns(patterns):
  357. """
  358. >>> list(Distribution._expand_patterns(['LICENSE']))
  359. ['LICENSE']
  360. >>> list(Distribution._expand_patterns(['setup.cfg', 'LIC*']))
  361. ['setup.cfg', 'LICENSE']
  362. """
  363. return (
  364. path
  365. for pattern in patterns
  366. for path in sorted(iglob(pattern))
  367. if not path.endswith('~') and os.path.isfile(path)
  368. )
  369. # FIXME: 'Distribution._parse_config_files' is too complex (14)
  370. def _parse_config_files(self, filenames=None): # noqa: C901
  371. """
  372. Adapted from distutils.dist.Distribution.parse_config_files,
  373. this method provides the same functionality in subtly-improved
  374. ways.
  375. """
  376. from configparser import ConfigParser
  377. # Ignore install directory options if we have a venv
  378. ignore_options = (
  379. []
  380. if sys.prefix == sys.base_prefix
  381. else [
  382. 'install-base',
  383. 'install-platbase',
  384. 'install-lib',
  385. 'install-platlib',
  386. 'install-purelib',
  387. 'install-headers',
  388. 'install-scripts',
  389. 'install-data',
  390. 'prefix',
  391. 'exec-prefix',
  392. 'home',
  393. 'user',
  394. 'root',
  395. ]
  396. )
  397. ignore_options = frozenset(ignore_options)
  398. if filenames is None:
  399. filenames = self.find_config_files()
  400. if DEBUG:
  401. self.announce("Distribution.parse_config_files():")
  402. parser = ConfigParser()
  403. parser.optionxform = str
  404. for filename in filenames:
  405. with io.open(filename, encoding='utf-8') as reader:
  406. if DEBUG:
  407. self.announce(" reading {filename}".format(**locals()))
  408. parser.read_file(reader)
  409. for section in parser.sections():
  410. options = parser.options(section)
  411. opt_dict = self.get_option_dict(section)
  412. for opt in options:
  413. if opt == '__name__' or opt in ignore_options:
  414. continue
  415. val = parser.get(section, opt)
  416. opt = self.warn_dash_deprecation(opt, section)
  417. opt = self.make_option_lowercase(opt, section)
  418. opt_dict[opt] = (filename, val)
  419. # Make the ConfigParser forget everything (so we retain
  420. # the original filenames that options come from)
  421. parser.__init__()
  422. if 'global' not in self.command_options:
  423. return
  424. # If there was a "global" section in the config file, use it
  425. # to set Distribution options.
  426. for opt, (src, val) in self.command_options['global'].items():
  427. alias = self.negative_opt.get(opt)
  428. if alias:
  429. val = not strtobool(val)
  430. elif opt in ('verbose', 'dry_run'): # ugh!
  431. val = strtobool(val)
  432. try:
  433. setattr(self, alias or opt, val)
  434. except ValueError as e:
  435. raise DistutilsOptionError(e) from e
  436. def warn_dash_deprecation(self, opt, section):
  437. if section in (
  438. 'options.extras_require',
  439. 'options.data_files',
  440. ):
  441. return opt
  442. underscore_opt = opt.replace('-', '_')
  443. commands = list(
  444. itertools.chain(
  445. distutils.command.__all__,
  446. self._setuptools_commands(),
  447. )
  448. )
  449. if (
  450. not section.startswith('options')
  451. and section != 'metadata'
  452. and section not in commands
  453. ):
  454. return underscore_opt
  455. if '-' in opt:
  456. SetuptoolsDeprecationWarning.emit(
  457. "Invalid dash-separated options",
  458. f"""
  459. Usage of dash-separated {opt!r} will not be supported in future
  460. versions. Please use the underscore name {underscore_opt!r} instead.
  461. """,
  462. see_docs="userguide/declarative_config.html",
  463. due_date=(2023, 9, 26),
  464. # Warning initially introduced in 3 Mar 2021
  465. )
  466. return underscore_opt
  467. def _setuptools_commands(self):
  468. try:
  469. return metadata.distribution('setuptools').entry_points.names
  470. except metadata.PackageNotFoundError:
  471. # during bootstrapping, distribution doesn't exist
  472. return []
  473. def make_option_lowercase(self, opt, section):
  474. if section != 'metadata' or opt.islower():
  475. return opt
  476. lowercase_opt = opt.lower()
  477. SetuptoolsDeprecationWarning.emit(
  478. "Invalid uppercase configuration",
  479. f"""
  480. Usage of uppercase key {opt!r} in {section!r} will not be supported in
  481. future versions. Please use lowercase {lowercase_opt!r} instead.
  482. """,
  483. see_docs="userguide/declarative_config.html",
  484. due_date=(2023, 9, 26),
  485. # Warning initially introduced in 6 Mar 2021
  486. )
  487. return lowercase_opt
  488. # FIXME: 'Distribution._set_command_options' is too complex (14)
  489. def _set_command_options(self, command_obj, option_dict=None): # noqa: C901
  490. """
  491. Set the options for 'command_obj' from 'option_dict'. Basically
  492. this means copying elements of a dictionary ('option_dict') to
  493. attributes of an instance ('command').
  494. 'command_obj' must be a Command instance. If 'option_dict' is not
  495. supplied, uses the standard option dictionary for this command
  496. (from 'self.command_options').
  497. (Adopted from distutils.dist.Distribution._set_command_options)
  498. """
  499. command_name = command_obj.get_command_name()
  500. if option_dict is None:
  501. option_dict = self.get_option_dict(command_name)
  502. if DEBUG:
  503. self.announce(" setting options for '%s' command:" % command_name)
  504. for option, (source, value) in option_dict.items():
  505. if DEBUG:
  506. self.announce(" %s = %s (from %s)" % (option, value, source))
  507. try:
  508. bool_opts = [translate_longopt(o) for o in command_obj.boolean_options]
  509. except AttributeError:
  510. bool_opts = []
  511. try:
  512. neg_opt = command_obj.negative_opt
  513. except AttributeError:
  514. neg_opt = {}
  515. try:
  516. is_string = isinstance(value, str)
  517. if option in neg_opt and is_string:
  518. setattr(command_obj, neg_opt[option], not strtobool(value))
  519. elif option in bool_opts and is_string:
  520. setattr(command_obj, option, strtobool(value))
  521. elif hasattr(command_obj, option):
  522. setattr(command_obj, option, value)
  523. else:
  524. raise DistutilsOptionError(
  525. "error in %s: command '%s' has no such option '%s'"
  526. % (source, command_name, option)
  527. )
  528. except ValueError as e:
  529. raise DistutilsOptionError(e) from e
  530. def _get_project_config_files(self, filenames):
  531. """Add default file and split between INI and TOML"""
  532. tomlfiles = []
  533. standard_project_metadata = Path(self.src_root or os.curdir, "pyproject.toml")
  534. if filenames is not None:
  535. parts = partition(lambda f: Path(f).suffix == ".toml", filenames)
  536. filenames = list(parts[0]) # 1st element => predicate is False
  537. tomlfiles = list(parts[1]) # 2nd element => predicate is True
  538. elif standard_project_metadata.exists():
  539. tomlfiles = [standard_project_metadata]
  540. return filenames, tomlfiles
  541. def parse_config_files(self, filenames=None, ignore_option_errors=False):
  542. """Parses configuration files from various levels
  543. and loads configuration.
  544. """
  545. inifiles, tomlfiles = self._get_project_config_files(filenames)
  546. self._parse_config_files(filenames=inifiles)
  547. setupcfg.parse_configuration(
  548. self, self.command_options, ignore_option_errors=ignore_option_errors
  549. )
  550. for filename in tomlfiles:
  551. pyprojecttoml.apply_configuration(self, filename, ignore_option_errors)
  552. self._finalize_requires()
  553. self._finalize_license_files()
  554. def fetch_build_eggs(self, requires):
  555. """Resolve pre-setup requirements"""
  556. from .installer import _fetch_build_eggs
  557. return _fetch_build_eggs(self, requires)
  558. def finalize_options(self):
  559. """
  560. Allow plugins to apply arbitrary operations to the
  561. distribution. Each hook may optionally define a 'order'
  562. to influence the order of execution. Smaller numbers
  563. go first and the default is 0.
  564. """
  565. group = 'setuptools.finalize_distribution_options'
  566. def by_order(hook):
  567. return getattr(hook, 'order', 0)
  568. defined = metadata.entry_points(group=group)
  569. filtered = itertools.filterfalse(self._removed, defined)
  570. loaded = map(lambda e: e.load(), filtered)
  571. for ep in sorted(loaded, key=by_order):
  572. ep(self)
  573. @staticmethod
  574. def _removed(ep):
  575. """
  576. When removing an entry point, if metadata is loaded
  577. from an older version of Setuptools, that removed
  578. entry point will attempt to be loaded and will fail.
  579. See #2765 for more details.
  580. """
  581. removed = {
  582. # removed 2021-09-05
  583. '2to3_doctests',
  584. }
  585. return ep.name in removed
  586. def _finalize_setup_keywords(self):
  587. for ep in metadata.entry_points(group='distutils.setup_keywords'):
  588. value = getattr(self, ep.name, None)
  589. if value is not None:
  590. ep.load()(self, ep.name, value)
  591. def get_egg_cache_dir(self):
  592. from . import windows_support
  593. egg_cache_dir = os.path.join(os.curdir, '.eggs')
  594. if not os.path.exists(egg_cache_dir):
  595. os.mkdir(egg_cache_dir)
  596. windows_support.hide_file(egg_cache_dir)
  597. readme_txt_filename = os.path.join(egg_cache_dir, 'README.txt')
  598. with open(readme_txt_filename, 'w') as f:
  599. f.write(
  600. 'This directory contains eggs that were downloaded '
  601. 'by setuptools to build, test, and run plug-ins.\n\n'
  602. )
  603. f.write(
  604. 'This directory caches those eggs to prevent '
  605. 'repeated downloads.\n\n'
  606. )
  607. f.write('However, it is safe to delete this directory.\n\n')
  608. return egg_cache_dir
  609. def fetch_build_egg(self, req):
  610. """Fetch an egg needed for building"""
  611. from .installer import fetch_build_egg
  612. return fetch_build_egg(self, req)
  613. def get_command_class(self, command):
  614. """Pluggable version of get_command_class()"""
  615. if command in self.cmdclass:
  616. return self.cmdclass[command]
  617. eps = metadata.entry_points(group='distutils.commands', name=command)
  618. for ep in eps:
  619. self.cmdclass[command] = cmdclass = ep.load()
  620. return cmdclass
  621. else:
  622. return _Distribution.get_command_class(self, command)
  623. def print_commands(self):
  624. for ep in metadata.entry_points(group='distutils.commands'):
  625. if ep.name not in self.cmdclass:
  626. cmdclass = ep.load()
  627. self.cmdclass[ep.name] = cmdclass
  628. return _Distribution.print_commands(self)
  629. def get_command_list(self):
  630. for ep in metadata.entry_points(group='distutils.commands'):
  631. if ep.name not in self.cmdclass:
  632. cmdclass = ep.load()
  633. self.cmdclass[ep.name] = cmdclass
  634. return _Distribution.get_command_list(self)
  635. def include(self, **attrs):
  636. """Add items to distribution that are named in keyword arguments
  637. For example, 'dist.include(py_modules=["x"])' would add 'x' to
  638. the distribution's 'py_modules' attribute, if it was not already
  639. there.
  640. Currently, this method only supports inclusion for attributes that are
  641. lists or tuples. If you need to add support for adding to other
  642. attributes in this or a subclass, you can add an '_include_X' method,
  643. where 'X' is the name of the attribute. The method will be called with
  644. the value passed to 'include()'. So, 'dist.include(foo={"bar":"baz"})'
  645. will try to call 'dist._include_foo({"bar":"baz"})', which can then
  646. handle whatever special inclusion logic is needed.
  647. """
  648. for k, v in attrs.items():
  649. include = getattr(self, '_include_' + k, None)
  650. if include:
  651. include(v)
  652. else:
  653. self._include_misc(k, v)
  654. def exclude_package(self, package):
  655. """Remove packages, modules, and extensions in named package"""
  656. pfx = package + '.'
  657. if self.packages:
  658. self.packages = [
  659. p for p in self.packages if p != package and not p.startswith(pfx)
  660. ]
  661. if self.py_modules:
  662. self.py_modules = [
  663. p for p in self.py_modules if p != package and not p.startswith(pfx)
  664. ]
  665. if self.ext_modules:
  666. self.ext_modules = [
  667. p
  668. for p in self.ext_modules
  669. if p.name != package and not p.name.startswith(pfx)
  670. ]
  671. def has_contents_for(self, package):
  672. """Return true if 'exclude_package(package)' would do something"""
  673. pfx = package + '.'
  674. for p in self.iter_distribution_names():
  675. if p == package or p.startswith(pfx):
  676. return True
  677. def _exclude_misc(self, name, value):
  678. """Handle 'exclude()' for list/tuple attrs without a special handler"""
  679. if not isinstance(value, sequence):
  680. raise DistutilsSetupError(
  681. "%s: setting must be a list or tuple (%r)" % (name, value)
  682. )
  683. try:
  684. old = getattr(self, name)
  685. except AttributeError as e:
  686. raise DistutilsSetupError("%s: No such distribution setting" % name) from e
  687. if old is not None and not isinstance(old, sequence):
  688. raise DistutilsSetupError(
  689. name + ": this setting cannot be changed via include/exclude"
  690. )
  691. elif old:
  692. setattr(self, name, [item for item in old if item not in value])
  693. def _include_misc(self, name, value):
  694. """Handle 'include()' for list/tuple attrs without a special handler"""
  695. if not isinstance(value, sequence):
  696. raise DistutilsSetupError("%s: setting must be a list (%r)" % (name, value))
  697. try:
  698. old = getattr(self, name)
  699. except AttributeError as e:
  700. raise DistutilsSetupError("%s: No such distribution setting" % name) from e
  701. if old is None:
  702. setattr(self, name, value)
  703. elif not isinstance(old, sequence):
  704. raise DistutilsSetupError(
  705. name + ": this setting cannot be changed via include/exclude"
  706. )
  707. else:
  708. new = [item for item in value if item not in old]
  709. setattr(self, name, old + new)
  710. def exclude(self, **attrs):
  711. """Remove items from distribution that are named in keyword arguments
  712. For example, 'dist.exclude(py_modules=["x"])' would remove 'x' from
  713. the distribution's 'py_modules' attribute. Excluding packages uses
  714. the 'exclude_package()' method, so all of the package's contained
  715. packages, modules, and extensions are also excluded.
  716. Currently, this method only supports exclusion from attributes that are
  717. lists or tuples. If you need to add support for excluding from other
  718. attributes in this or a subclass, you can add an '_exclude_X' method,
  719. where 'X' is the name of the attribute. The method will be called with
  720. the value passed to 'exclude()'. So, 'dist.exclude(foo={"bar":"baz"})'
  721. will try to call 'dist._exclude_foo({"bar":"baz"})', which can then
  722. handle whatever special exclusion logic is needed.
  723. """
  724. for k, v in attrs.items():
  725. exclude = getattr(self, '_exclude_' + k, None)
  726. if exclude:
  727. exclude(v)
  728. else:
  729. self._exclude_misc(k, v)
  730. def _exclude_packages(self, packages):
  731. if not isinstance(packages, sequence):
  732. raise DistutilsSetupError(
  733. "packages: setting must be a list or tuple (%r)" % (packages,)
  734. )
  735. list(map(self.exclude_package, packages))
  736. def _parse_command_opts(self, parser, args):
  737. # Remove --with-X/--without-X options when processing command args
  738. self.global_options = self.__class__.global_options
  739. self.negative_opt = self.__class__.negative_opt
  740. # First, expand any aliases
  741. command = args[0]
  742. aliases = self.get_option_dict('aliases')
  743. while command in aliases:
  744. src, alias = aliases[command]
  745. del aliases[command] # ensure each alias can expand only once!
  746. import shlex
  747. args[:1] = shlex.split(alias, True)
  748. command = args[0]
  749. nargs = _Distribution._parse_command_opts(self, parser, args)
  750. # Handle commands that want to consume all remaining arguments
  751. cmd_class = self.get_command_class(command)
  752. if getattr(cmd_class, 'command_consumes_arguments', None):
  753. self.get_option_dict(command)['args'] = ("command line", nargs)
  754. if nargs is not None:
  755. return []
  756. return nargs
  757. def get_cmdline_options(self):
  758. """Return a '{cmd: {opt:val}}' map of all command-line options
  759. Option names are all long, but do not include the leading '--', and
  760. contain dashes rather than underscores. If the option doesn't take
  761. an argument (e.g. '--quiet'), the 'val' is 'None'.
  762. Note that options provided by config files are intentionally excluded.
  763. """
  764. d = {}
  765. for cmd, opts in self.command_options.items():
  766. for opt, (src, val) in opts.items():
  767. if src != "command line":
  768. continue
  769. opt = opt.replace('_', '-')
  770. if val == 0:
  771. cmdobj = self.get_command_obj(cmd)
  772. neg_opt = self.negative_opt.copy()
  773. neg_opt.update(getattr(cmdobj, 'negative_opt', {}))
  774. for neg, pos in neg_opt.items():
  775. if pos == opt:
  776. opt = neg
  777. val = None
  778. break
  779. else:
  780. raise AssertionError("Shouldn't be able to get here")
  781. elif val == 1:
  782. val = None
  783. d.setdefault(cmd, {})[opt] = val
  784. return d
  785. def iter_distribution_names(self):
  786. """Yield all packages, modules, and extension names in distribution"""
  787. for pkg in self.packages or ():
  788. yield pkg
  789. for module in self.py_modules or ():
  790. yield module
  791. for ext in self.ext_modules or ():
  792. if isinstance(ext, tuple):
  793. name, buildinfo = ext
  794. else:
  795. name = ext.name
  796. if name.endswith('module'):
  797. name = name[:-6]
  798. yield name
  799. def handle_display_options(self, option_order):
  800. """If there were any non-global "display-only" options
  801. (--help-commands or the metadata display options) on the command
  802. line, display the requested info and return true; else return
  803. false.
  804. """
  805. import sys
  806. if self.help_commands:
  807. return _Distribution.handle_display_options(self, option_order)
  808. # Stdout may be StringIO (e.g. in tests)
  809. if not isinstance(sys.stdout, io.TextIOWrapper):
  810. return _Distribution.handle_display_options(self, option_order)
  811. # Don't wrap stdout if utf-8 is already the encoding. Provides
  812. # workaround for #334.
  813. if sys.stdout.encoding.lower() in ('utf-8', 'utf8'):
  814. return _Distribution.handle_display_options(self, option_order)
  815. # Print metadata in UTF-8 no matter the platform
  816. encoding = sys.stdout.encoding
  817. sys.stdout.reconfigure(encoding='utf-8')
  818. try:
  819. return _Distribution.handle_display_options(self, option_order)
  820. finally:
  821. sys.stdout.reconfigure(encoding=encoding)
  822. def run_command(self, command):
  823. self.set_defaults()
  824. # Postpone defaults until all explicit configuration is considered
  825. # (setup() args, config files, command line and plugins)
  826. super().run_command(command)
  827. class DistDeprecationWarning(SetuptoolsDeprecationWarning):
  828. """Class for warning about deprecations in dist in
  829. setuptools. Not ignored by default, unlike DeprecationWarning."""