dist.py 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  1. # -*- coding: utf-8 -*-
  2. __all__ = ['Distribution']
  3. import io
  4. import sys
  5. import re
  6. import os
  7. import warnings
  8. import numbers
  9. import distutils.log
  10. import distutils.core
  11. import distutils.cmd
  12. import distutils.dist
  13. import distutils.command
  14. from distutils.util import strtobool
  15. from distutils.debug import DEBUG
  16. from distutils.fancy_getopt import translate_longopt
  17. from glob import iglob
  18. import itertools
  19. import textwrap
  20. from typing import List, Optional, TYPE_CHECKING
  21. from pathlib import Path
  22. from collections import defaultdict
  23. from email import message_from_file
  24. from distutils.errors import DistutilsOptionError, DistutilsSetupError
  25. from distutils.util import rfc822_escape
  26. from setuptools.extern import packaging
  27. from setuptools.extern import ordered_set
  28. from setuptools.extern.more_itertools import unique_everseen, partition
  29. from setuptools.extern import nspektr
  30. from ._importlib import metadata
  31. from . import SetuptoolsDeprecationWarning
  32. import setuptools
  33. import setuptools.command
  34. from setuptools import windows_support
  35. from setuptools.monkey import get_unpatched
  36. from setuptools.config import setupcfg, pyprojecttoml
  37. from setuptools.discovery import ConfigDiscovery
  38. import pkg_resources
  39. from setuptools.extern.packaging import version
  40. from . import _reqs
  41. from . import _entry_points
  42. if TYPE_CHECKING:
  43. from email.message import Message
  44. __import__('setuptools.extern.packaging.specifiers')
  45. __import__('setuptools.extern.packaging.version')
  46. def _get_unpatched(cls):
  47. warnings.warn("Do not call this function", DistDeprecationWarning)
  48. return get_unpatched(cls)
  49. def get_metadata_version(self):
  50. mv = getattr(self, 'metadata_version', None)
  51. if mv is None:
  52. mv = version.Version('2.1')
  53. self.metadata_version = mv
  54. return mv
  55. def rfc822_unescape(content: str) -> str:
  56. """Reverse RFC-822 escaping by removing leading whitespaces from content."""
  57. lines = content.splitlines()
  58. if len(lines) == 1:
  59. return lines[0].lstrip()
  60. return '\n'.join((lines[0].lstrip(), textwrap.dedent('\n'.join(lines[1:]))))
  61. def _read_field_from_msg(msg: "Message", field: str) -> Optional[str]:
  62. """Read Message header field."""
  63. value = msg[field]
  64. if value == 'UNKNOWN':
  65. return None
  66. return value
  67. def _read_field_unescaped_from_msg(msg: "Message", field: str) -> Optional[str]:
  68. """Read Message header field and apply rfc822_unescape."""
  69. value = _read_field_from_msg(msg, field)
  70. if value is None:
  71. return value
  72. return rfc822_unescape(value)
  73. def _read_list_from_msg(msg: "Message", field: str) -> Optional[List[str]]:
  74. """Read Message header field and return all results as list."""
  75. values = msg.get_all(field, None)
  76. if values == []:
  77. return None
  78. return values
  79. def _read_payload_from_msg(msg: "Message") -> Optional[str]:
  80. value = msg.get_payload().strip()
  81. if value == 'UNKNOWN':
  82. return None
  83. return value
  84. def read_pkg_file(self, file):
  85. """Reads the metadata values from a file object."""
  86. msg = message_from_file(file)
  87. self.metadata_version = version.Version(msg['metadata-version'])
  88. self.name = _read_field_from_msg(msg, 'name')
  89. self.version = _read_field_from_msg(msg, 'version')
  90. self.description = _read_field_from_msg(msg, 'summary')
  91. # we are filling author only.
  92. self.author = _read_field_from_msg(msg, 'author')
  93. self.maintainer = None
  94. self.author_email = _read_field_from_msg(msg, 'author-email')
  95. self.maintainer_email = None
  96. self.url = _read_field_from_msg(msg, 'home-page')
  97. self.download_url = _read_field_from_msg(msg, 'download-url')
  98. self.license = _read_field_unescaped_from_msg(msg, 'license')
  99. self.long_description = _read_field_unescaped_from_msg(msg, 'description')
  100. if (
  101. self.long_description is None and
  102. self.metadata_version >= version.Version('2.1')
  103. ):
  104. self.long_description = _read_payload_from_msg(msg)
  105. self.description = _read_field_from_msg(msg, 'summary')
  106. if 'keywords' in msg:
  107. self.keywords = _read_field_from_msg(msg, 'keywords').split(',')
  108. self.platforms = _read_list_from_msg(msg, 'platform')
  109. self.classifiers = _read_list_from_msg(msg, 'classifier')
  110. # PEP 314 - these fields only exist in 1.1
  111. if self.metadata_version == version.Version('1.1'):
  112. self.requires = _read_list_from_msg(msg, 'requires')
  113. self.provides = _read_list_from_msg(msg, 'provides')
  114. self.obsoletes = _read_list_from_msg(msg, 'obsoletes')
  115. else:
  116. self.requires = None
  117. self.provides = None
  118. self.obsoletes = None
  119. self.license_files = _read_list_from_msg(msg, 'license-file')
  120. def single_line(val):
  121. """
  122. Quick and dirty validation for Summary pypa/setuptools#1390.
  123. """
  124. if '\n' in val:
  125. # TODO: Replace with `raise ValueError("newlines not allowed")`
  126. # after reviewing #2893.
  127. warnings.warn("newlines not allowed and will break in the future")
  128. val = val.strip().split('\n')[0]
  129. return val
  130. # Based on Python 3.5 version
  131. def write_pkg_file(self, file): # noqa: C901 # is too complex (14) # FIXME
  132. """Write the PKG-INFO format data to a file object."""
  133. version = self.get_metadata_version()
  134. def write_field(key, value):
  135. file.write("%s: %s\n" % (key, value))
  136. write_field('Metadata-Version', str(version))
  137. write_field('Name', self.get_name())
  138. write_field('Version', self.get_version())
  139. write_field('Summary', single_line(self.get_description()))
  140. optional_fields = (
  141. ('Home-page', 'url'),
  142. ('Download-URL', 'download_url'),
  143. ('Author', 'author'),
  144. ('Author-email', 'author_email'),
  145. ('Maintainer', 'maintainer'),
  146. ('Maintainer-email', 'maintainer_email'),
  147. )
  148. for field, attr in optional_fields:
  149. attr_val = getattr(self, attr, None)
  150. if attr_val is not None:
  151. write_field(field, attr_val)
  152. license = rfc822_escape(self.get_license())
  153. write_field('License', license)
  154. for project_url in self.project_urls.items():
  155. write_field('Project-URL', '%s, %s' % project_url)
  156. keywords = ','.join(self.get_keywords())
  157. if keywords:
  158. write_field('Keywords', keywords)
  159. for platform in self.get_platforms():
  160. write_field('Platform', platform)
  161. self._write_list(file, 'Classifier', self.get_classifiers())
  162. # PEP 314
  163. self._write_list(file, 'Requires', self.get_requires())
  164. self._write_list(file, 'Provides', self.get_provides())
  165. self._write_list(file, 'Obsoletes', self.get_obsoletes())
  166. # Setuptools specific for PEP 345
  167. if hasattr(self, 'python_requires'):
  168. write_field('Requires-Python', self.python_requires)
  169. # PEP 566
  170. if self.long_description_content_type:
  171. write_field('Description-Content-Type', self.long_description_content_type)
  172. if self.provides_extras:
  173. for extra in self.provides_extras:
  174. write_field('Provides-Extra', extra)
  175. self._write_list(file, 'License-File', self.license_files or [])
  176. file.write("\n%s\n\n" % self.get_long_description())
  177. sequence = tuple, list
  178. def check_importable(dist, attr, value):
  179. try:
  180. ep = metadata.EntryPoint(value=value, name=None, group=None)
  181. assert not ep.extras
  182. except (TypeError, ValueError, AttributeError, AssertionError) as e:
  183. raise DistutilsSetupError(
  184. "%r must be importable 'module:attrs' string (got %r)" % (attr, value)
  185. ) from e
  186. def assert_string_list(dist, attr, value):
  187. """Verify that value is a string list"""
  188. try:
  189. # verify that value is a list or tuple to exclude unordered
  190. # or single-use iterables
  191. assert isinstance(value, (list, tuple))
  192. # verify that elements of value are strings
  193. assert ''.join(value) != value
  194. except (TypeError, ValueError, AttributeError, AssertionError) as e:
  195. raise DistutilsSetupError(
  196. "%r must be a list of strings (got %r)" % (attr, value)
  197. ) from e
  198. def check_nsp(dist, attr, value):
  199. """Verify that namespace packages are valid"""
  200. ns_packages = value
  201. assert_string_list(dist, attr, ns_packages)
  202. for nsp in ns_packages:
  203. if not dist.has_contents_for(nsp):
  204. raise DistutilsSetupError(
  205. "Distribution contains no modules or packages for "
  206. + "namespace package %r" % nsp
  207. )
  208. parent, sep, child = nsp.rpartition('.')
  209. if parent and parent not in ns_packages:
  210. distutils.log.warn(
  211. "WARNING: %r is declared as a package namespace, but %r"
  212. " is not: please correct this in setup.py",
  213. nsp,
  214. parent,
  215. )
  216. def check_extras(dist, attr, value):
  217. """Verify that extras_require mapping is valid"""
  218. try:
  219. list(itertools.starmap(_check_extra, value.items()))
  220. except (TypeError, ValueError, AttributeError) as e:
  221. raise DistutilsSetupError(
  222. "'extras_require' must be a dictionary whose values are "
  223. "strings or lists of strings containing valid project/version "
  224. "requirement specifiers."
  225. ) from e
  226. def _check_extra(extra, reqs):
  227. name, sep, marker = extra.partition(':')
  228. if marker and pkg_resources.invalid_marker(marker):
  229. raise DistutilsSetupError("Invalid environment marker: " + marker)
  230. list(_reqs.parse(reqs))
  231. def assert_bool(dist, attr, value):
  232. """Verify that value is True, False, 0, or 1"""
  233. if bool(value) != value:
  234. tmpl = "{attr!r} must be a boolean value (got {value!r})"
  235. raise DistutilsSetupError(tmpl.format(attr=attr, value=value))
  236. def invalid_unless_false(dist, attr, value):
  237. if not value:
  238. warnings.warn(f"{attr} is ignored.", DistDeprecationWarning)
  239. return
  240. raise DistutilsSetupError(f"{attr} is invalid.")
  241. def check_requirements(dist, attr, value):
  242. """Verify that install_requires is a valid requirements list"""
  243. try:
  244. list(_reqs.parse(value))
  245. if isinstance(value, (dict, set)):
  246. raise TypeError("Unordered types are not allowed")
  247. except (TypeError, ValueError) as error:
  248. tmpl = (
  249. "{attr!r} must be a string or list of strings "
  250. "containing valid project/version requirement specifiers; {error}"
  251. )
  252. raise DistutilsSetupError(tmpl.format(attr=attr, error=error)) from error
  253. def check_specifier(dist, attr, value):
  254. """Verify that value is a valid version specifier"""
  255. try:
  256. packaging.specifiers.SpecifierSet(value)
  257. except (packaging.specifiers.InvalidSpecifier, AttributeError) as error:
  258. tmpl = (
  259. "{attr!r} must be a string " "containing valid version specifiers; {error}"
  260. )
  261. raise DistutilsSetupError(tmpl.format(attr=attr, error=error)) from error
  262. def check_entry_points(dist, attr, value):
  263. """Verify that entry_points map is parseable"""
  264. try:
  265. _entry_points.load(value)
  266. except Exception as e:
  267. raise DistutilsSetupError(e) from e
  268. def check_test_suite(dist, attr, value):
  269. if not isinstance(value, str):
  270. raise DistutilsSetupError("test_suite must be a string")
  271. def check_package_data(dist, attr, value):
  272. """Verify that value is a dictionary of package names to glob lists"""
  273. if not isinstance(value, dict):
  274. raise DistutilsSetupError(
  275. "{!r} must be a dictionary mapping package names to lists of "
  276. "string wildcard patterns".format(attr)
  277. )
  278. for k, v in value.items():
  279. if not isinstance(k, str):
  280. raise DistutilsSetupError(
  281. "keys of {!r} dict must be strings (got {!r})".format(attr, k)
  282. )
  283. assert_string_list(dist, 'values of {!r} dict'.format(attr), v)
  284. def check_packages(dist, attr, value):
  285. for pkgname in value:
  286. if not re.match(r'\w+(\.\w+)*', pkgname):
  287. distutils.log.warn(
  288. "WARNING: %r not a valid package name; please use only "
  289. ".-separated package names in setup.py",
  290. pkgname,
  291. )
  292. _Distribution = get_unpatched(distutils.core.Distribution)
  293. class Distribution(_Distribution):
  294. """Distribution with support for tests and package data
  295. This is an enhanced version of 'distutils.dist.Distribution' that
  296. effectively adds the following new optional keyword arguments to 'setup()':
  297. 'install_requires' -- a string or sequence of strings specifying project
  298. versions that the distribution requires when installed, in the format
  299. used by 'pkg_resources.require()'. They will be installed
  300. automatically when the package is installed. If you wish to use
  301. packages that are not available in PyPI, or want to give your users an
  302. alternate download location, you can add a 'find_links' option to the
  303. '[easy_install]' section of your project's 'setup.cfg' file, and then
  304. setuptools will scan the listed web pages for links that satisfy the
  305. requirements.
  306. 'extras_require' -- a dictionary mapping names of optional "extras" to the
  307. additional requirement(s) that using those extras incurs. For example,
  308. this::
  309. extras_require = dict(reST = ["docutils>=0.3", "reSTedit"])
  310. indicates that the distribution can optionally provide an extra
  311. capability called "reST", but it can only be used if docutils and
  312. reSTedit are installed. If the user installs your package using
  313. EasyInstall and requests one of your extras, the corresponding
  314. additional requirements will be installed if needed.
  315. 'test_suite' -- the name of a test suite to run for the 'test' command.
  316. If the user runs 'python setup.py test', the package will be installed,
  317. and the named test suite will be run. The format is the same as
  318. would be used on a 'unittest.py' command line. That is, it is the
  319. dotted name of an object to import and call to generate a test suite.
  320. 'package_data' -- a dictionary mapping package names to lists of filenames
  321. or globs to use to find data files contained in the named packages.
  322. If the dictionary has filenames or globs listed under '""' (the empty
  323. string), those names will be searched for in every package, in addition
  324. to any names for the specific package. Data files found using these
  325. names/globs will be installed along with the package, in the same
  326. location as the package. Note that globs are allowed to reference
  327. the contents of non-package subdirectories, as long as you use '/' as
  328. a path separator. (Globs are automatically converted to
  329. platform-specific paths at runtime.)
  330. In addition to these new keywords, this class also has several new methods
  331. for manipulating the distribution's contents. For example, the 'include()'
  332. and 'exclude()' methods can be thought of as in-place add and subtract
  333. commands that add or remove packages, modules, extensions, and so on from
  334. the distribution.
  335. """
  336. _DISTUTILS_UNSUPPORTED_METADATA = {
  337. 'long_description_content_type': lambda: None,
  338. 'project_urls': dict,
  339. 'provides_extras': ordered_set.OrderedSet,
  340. 'license_file': lambda: None,
  341. 'license_files': lambda: None,
  342. }
  343. _patched_dist = None
  344. def patch_missing_pkg_info(self, attrs):
  345. # Fake up a replacement for the data that would normally come from
  346. # PKG-INFO, but which might not yet be built if this is a fresh
  347. # checkout.
  348. #
  349. if not attrs or 'name' not in attrs or 'version' not in attrs:
  350. return
  351. key = pkg_resources.safe_name(str(attrs['name'])).lower()
  352. dist = pkg_resources.working_set.by_key.get(key)
  353. if dist is not None and not dist.has_metadata('PKG-INFO'):
  354. dist._version = pkg_resources.safe_version(str(attrs['version']))
  355. self._patched_dist = dist
  356. def __init__(self, attrs=None):
  357. have_package_data = hasattr(self, "package_data")
  358. if not have_package_data:
  359. self.package_data = {}
  360. attrs = attrs or {}
  361. self.dist_files = []
  362. # Filter-out setuptools' specific options.
  363. self.src_root = attrs.pop("src_root", None)
  364. self.patch_missing_pkg_info(attrs)
  365. self.dependency_links = attrs.pop('dependency_links', [])
  366. self.setup_requires = attrs.pop('setup_requires', [])
  367. for ep in metadata.entry_points(group='distutils.setup_keywords'):
  368. vars(self).setdefault(ep.name, None)
  369. _Distribution.__init__(
  370. self,
  371. {
  372. k: v
  373. for k, v in attrs.items()
  374. if k not in self._DISTUTILS_UNSUPPORTED_METADATA
  375. },
  376. )
  377. # Save the original dependencies before they are processed into the egg format
  378. self._orig_extras_require = {}
  379. self._orig_install_requires = []
  380. self._tmp_extras_require = defaultdict(ordered_set.OrderedSet)
  381. self.set_defaults = ConfigDiscovery(self)
  382. self._set_metadata_defaults(attrs)
  383. self.metadata.version = self._normalize_version(
  384. self._validate_version(self.metadata.version)
  385. )
  386. self._finalize_requires()
  387. def _validate_metadata(self):
  388. required = {"name"}
  389. provided = {
  390. key
  391. for key in vars(self.metadata)
  392. if getattr(self.metadata, key, None) is not None
  393. }
  394. missing = required - provided
  395. if missing:
  396. msg = f"Required package metadata is missing: {missing}"
  397. raise DistutilsSetupError(msg)
  398. def _set_metadata_defaults(self, attrs):
  399. """
  400. Fill-in missing metadata fields not supported by distutils.
  401. Some fields may have been set by other tools (e.g. pbr).
  402. Those fields (vars(self.metadata)) take precedence to
  403. supplied attrs.
  404. """
  405. for option, default in self._DISTUTILS_UNSUPPORTED_METADATA.items():
  406. vars(self.metadata).setdefault(option, attrs.get(option, default()))
  407. @staticmethod
  408. def _normalize_version(version):
  409. if isinstance(version, setuptools.sic) or version is None:
  410. return version
  411. normalized = str(packaging.version.Version(version))
  412. if version != normalized:
  413. tmpl = "Normalizing '{version}' to '{normalized}'"
  414. warnings.warn(tmpl.format(**locals()))
  415. return normalized
  416. return version
  417. @staticmethod
  418. def _validate_version(version):
  419. if isinstance(version, numbers.Number):
  420. # Some people apparently take "version number" too literally :)
  421. version = str(version)
  422. if version is not None:
  423. try:
  424. packaging.version.Version(version)
  425. except (packaging.version.InvalidVersion, TypeError):
  426. warnings.warn(
  427. "The version specified (%r) is an invalid version, this "
  428. "may not work as expected with newer versions of "
  429. "setuptools, pip, and PyPI. Please see PEP 440 for more "
  430. "details." % version
  431. )
  432. return setuptools.sic(version)
  433. return version
  434. def _finalize_requires(self):
  435. """
  436. Set `metadata.python_requires` and fix environment markers
  437. in `install_requires` and `extras_require`.
  438. """
  439. if getattr(self, 'python_requires', None):
  440. self.metadata.python_requires = self.python_requires
  441. if getattr(self, 'extras_require', None):
  442. # Save original before it is messed by _convert_extras_requirements
  443. self._orig_extras_require = self._orig_extras_require or self.extras_require
  444. for extra in self.extras_require.keys():
  445. # Since this gets called multiple times at points where the
  446. # keys have become 'converted' extras, ensure that we are only
  447. # truly adding extras we haven't seen before here.
  448. extra = extra.split(':')[0]
  449. if extra:
  450. self.metadata.provides_extras.add(extra)
  451. if getattr(self, 'install_requires', None) and not self._orig_install_requires:
  452. # Save original before it is messed by _move_install_requirements_markers
  453. self._orig_install_requires = self.install_requires
  454. self._convert_extras_requirements()
  455. self._move_install_requirements_markers()
  456. def _convert_extras_requirements(self):
  457. """
  458. Convert requirements in `extras_require` of the form
  459. `"extra": ["barbazquux; {marker}"]` to
  460. `"extra:{marker}": ["barbazquux"]`.
  461. """
  462. spec_ext_reqs = getattr(self, 'extras_require', None) or {}
  463. tmp = defaultdict(ordered_set.OrderedSet)
  464. self._tmp_extras_require = getattr(self, '_tmp_extras_require', tmp)
  465. for section, v in spec_ext_reqs.items():
  466. # Do not strip empty sections.
  467. self._tmp_extras_require[section]
  468. for r in _reqs.parse(v):
  469. suffix = self._suffix_for(r)
  470. self._tmp_extras_require[section + suffix].append(r)
  471. @staticmethod
  472. def _suffix_for(req):
  473. """
  474. For a requirement, return the 'extras_require' suffix for
  475. that requirement.
  476. """
  477. return ':' + str(req.marker) if req.marker else ''
  478. def _move_install_requirements_markers(self):
  479. """
  480. Move requirements in `install_requires` that are using environment
  481. markers `extras_require`.
  482. """
  483. # divide the install_requires into two sets, simple ones still
  484. # handled by install_requires and more complex ones handled
  485. # by extras_require.
  486. def is_simple_req(req):
  487. return not req.marker
  488. spec_inst_reqs = getattr(self, 'install_requires', None) or ()
  489. inst_reqs = list(_reqs.parse(spec_inst_reqs))
  490. simple_reqs = filter(is_simple_req, inst_reqs)
  491. complex_reqs = itertools.filterfalse(is_simple_req, inst_reqs)
  492. self.install_requires = list(map(str, simple_reqs))
  493. for r in complex_reqs:
  494. self._tmp_extras_require[':' + str(r.marker)].append(r)
  495. self.extras_require = dict(
  496. # list(dict.fromkeys(...)) ensures a list of unique strings
  497. (k, list(dict.fromkeys(str(r) for r in map(self._clean_req, v))))
  498. for k, v in self._tmp_extras_require.items()
  499. )
  500. def _clean_req(self, req):
  501. """
  502. Given a Requirement, remove environment markers and return it.
  503. """
  504. req.marker = None
  505. return req
  506. def _finalize_license_files(self):
  507. """Compute names of all license files which should be included."""
  508. license_files: Optional[List[str]] = self.metadata.license_files
  509. patterns: List[str] = license_files if license_files else []
  510. license_file: Optional[str] = self.metadata.license_file
  511. if license_file and license_file not in patterns:
  512. patterns.append(license_file)
  513. if license_files is None and license_file is None:
  514. # Default patterns match the ones wheel uses
  515. # See https://wheel.readthedocs.io/en/stable/user_guide.html
  516. # -> 'Including license files in the generated wheel file'
  517. patterns = ('LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*')
  518. self.metadata.license_files = list(
  519. unique_everseen(self._expand_patterns(patterns))
  520. )
  521. @staticmethod
  522. def _expand_patterns(patterns):
  523. """
  524. >>> list(Distribution._expand_patterns(['LICENSE']))
  525. ['LICENSE']
  526. >>> list(Distribution._expand_patterns(['setup.cfg', 'LIC*']))
  527. ['setup.cfg', 'LICENSE']
  528. """
  529. return (
  530. path
  531. for pattern in patterns
  532. for path in sorted(iglob(pattern))
  533. if not path.endswith('~') and os.path.isfile(path)
  534. )
  535. # FIXME: 'Distribution._parse_config_files' is too complex (14)
  536. def _parse_config_files(self, filenames=None): # noqa: C901
  537. """
  538. Adapted from distutils.dist.Distribution.parse_config_files,
  539. this method provides the same functionality in subtly-improved
  540. ways.
  541. """
  542. from configparser import ConfigParser
  543. # Ignore install directory options if we have a venv
  544. ignore_options = (
  545. []
  546. if sys.prefix == sys.base_prefix
  547. else [
  548. 'install-base',
  549. 'install-platbase',
  550. 'install-lib',
  551. 'install-platlib',
  552. 'install-purelib',
  553. 'install-headers',
  554. 'install-scripts',
  555. 'install-data',
  556. 'prefix',
  557. 'exec-prefix',
  558. 'home',
  559. 'user',
  560. 'root',
  561. ]
  562. )
  563. ignore_options = frozenset(ignore_options)
  564. if filenames is None:
  565. filenames = self.find_config_files()
  566. if DEBUG:
  567. self.announce("Distribution.parse_config_files():")
  568. parser = ConfigParser()
  569. parser.optionxform = str
  570. for filename in filenames:
  571. with io.open(filename, encoding='utf-8') as reader:
  572. if DEBUG:
  573. self.announce(" reading {filename}".format(**locals()))
  574. parser.read_file(reader)
  575. for section in parser.sections():
  576. options = parser.options(section)
  577. opt_dict = self.get_option_dict(section)
  578. for opt in options:
  579. if opt == '__name__' or opt in ignore_options:
  580. continue
  581. val = parser.get(section, opt)
  582. opt = self.warn_dash_deprecation(opt, section)
  583. opt = self.make_option_lowercase(opt, section)
  584. opt_dict[opt] = (filename, val)
  585. # Make the ConfigParser forget everything (so we retain
  586. # the original filenames that options come from)
  587. parser.__init__()
  588. if 'global' not in self.command_options:
  589. return
  590. # If there was a "global" section in the config file, use it
  591. # to set Distribution options.
  592. for (opt, (src, val)) in self.command_options['global'].items():
  593. alias = self.negative_opt.get(opt)
  594. if alias:
  595. val = not strtobool(val)
  596. elif opt in ('verbose', 'dry_run'): # ugh!
  597. val = strtobool(val)
  598. try:
  599. setattr(self, alias or opt, val)
  600. except ValueError as e:
  601. raise DistutilsOptionError(e) from e
  602. def warn_dash_deprecation(self, opt, section):
  603. if section in (
  604. 'options.extras_require',
  605. 'options.data_files',
  606. ):
  607. return opt
  608. underscore_opt = opt.replace('-', '_')
  609. commands = list(itertools.chain(
  610. distutils.command.__all__,
  611. self._setuptools_commands(),
  612. ))
  613. if (
  614. not section.startswith('options')
  615. and section != 'metadata'
  616. and section not in commands
  617. ):
  618. return underscore_opt
  619. if '-' in opt:
  620. warnings.warn(
  621. "Usage of dash-separated '%s' will not be supported in future "
  622. "versions. Please use the underscore name '%s' instead"
  623. % (opt, underscore_opt)
  624. )
  625. return underscore_opt
  626. def _setuptools_commands(self):
  627. try:
  628. return metadata.distribution('setuptools').entry_points.names
  629. except metadata.PackageNotFoundError:
  630. # during bootstrapping, distribution doesn't exist
  631. return []
  632. def make_option_lowercase(self, opt, section):
  633. if section != 'metadata' or opt.islower():
  634. return opt
  635. lowercase_opt = opt.lower()
  636. warnings.warn(
  637. "Usage of uppercase key '%s' in '%s' will be deprecated in future "
  638. "versions. Please use lowercase '%s' instead"
  639. % (opt, section, lowercase_opt)
  640. )
  641. return lowercase_opt
  642. # FIXME: 'Distribution._set_command_options' is too complex (14)
  643. def _set_command_options(self, command_obj, option_dict=None): # noqa: C901
  644. """
  645. Set the options for 'command_obj' from 'option_dict'. Basically
  646. this means copying elements of a dictionary ('option_dict') to
  647. attributes of an instance ('command').
  648. 'command_obj' must be a Command instance. If 'option_dict' is not
  649. supplied, uses the standard option dictionary for this command
  650. (from 'self.command_options').
  651. (Adopted from distutils.dist.Distribution._set_command_options)
  652. """
  653. command_name = command_obj.get_command_name()
  654. if option_dict is None:
  655. option_dict = self.get_option_dict(command_name)
  656. if DEBUG:
  657. self.announce(" setting options for '%s' command:" % command_name)
  658. for (option, (source, value)) in option_dict.items():
  659. if DEBUG:
  660. self.announce(" %s = %s (from %s)" % (option, value, source))
  661. try:
  662. bool_opts = [translate_longopt(o) for o in command_obj.boolean_options]
  663. except AttributeError:
  664. bool_opts = []
  665. try:
  666. neg_opt = command_obj.negative_opt
  667. except AttributeError:
  668. neg_opt = {}
  669. try:
  670. is_string = isinstance(value, str)
  671. if option in neg_opt and is_string:
  672. setattr(command_obj, neg_opt[option], not strtobool(value))
  673. elif option in bool_opts and is_string:
  674. setattr(command_obj, option, strtobool(value))
  675. elif hasattr(command_obj, option):
  676. setattr(command_obj, option, value)
  677. else:
  678. raise DistutilsOptionError(
  679. "error in %s: command '%s' has no such option '%s'"
  680. % (source, command_name, option)
  681. )
  682. except ValueError as e:
  683. raise DistutilsOptionError(e) from e
  684. def _get_project_config_files(self, filenames):
  685. """Add default file and split between INI and TOML"""
  686. tomlfiles = []
  687. standard_project_metadata = Path(self.src_root or os.curdir, "pyproject.toml")
  688. if filenames is not None:
  689. parts = partition(lambda f: Path(f).suffix == ".toml", filenames)
  690. filenames = list(parts[0]) # 1st element => predicate is False
  691. tomlfiles = list(parts[1]) # 2nd element => predicate is True
  692. elif standard_project_metadata.exists():
  693. tomlfiles = [standard_project_metadata]
  694. return filenames, tomlfiles
  695. def parse_config_files(self, filenames=None, ignore_option_errors=False):
  696. """Parses configuration files from various levels
  697. and loads configuration.
  698. """
  699. inifiles, tomlfiles = self._get_project_config_files(filenames)
  700. self._parse_config_files(filenames=inifiles)
  701. setupcfg.parse_configuration(
  702. self, self.command_options, ignore_option_errors=ignore_option_errors
  703. )
  704. for filename in tomlfiles:
  705. pyprojecttoml.apply_configuration(self, filename, ignore_option_errors)
  706. self._finalize_requires()
  707. self._finalize_license_files()
  708. def fetch_build_eggs(self, requires):
  709. """Resolve pre-setup requirements"""
  710. resolved_dists = pkg_resources.working_set.resolve(
  711. _reqs.parse(requires),
  712. installer=self.fetch_build_egg,
  713. replace_conflicting=True,
  714. )
  715. for dist in resolved_dists:
  716. pkg_resources.working_set.add(dist, replace=True)
  717. return resolved_dists
  718. def finalize_options(self):
  719. """
  720. Allow plugins to apply arbitrary operations to the
  721. distribution. Each hook may optionally define a 'order'
  722. to influence the order of execution. Smaller numbers
  723. go first and the default is 0.
  724. """
  725. group = 'setuptools.finalize_distribution_options'
  726. def by_order(hook):
  727. return getattr(hook, 'order', 0)
  728. defined = metadata.entry_points(group=group)
  729. filtered = itertools.filterfalse(self._removed, defined)
  730. loaded = map(lambda e: e.load(), filtered)
  731. for ep in sorted(loaded, key=by_order):
  732. ep(self)
  733. @staticmethod
  734. def _removed(ep):
  735. """
  736. When removing an entry point, if metadata is loaded
  737. from an older version of Setuptools, that removed
  738. entry point will attempt to be loaded and will fail.
  739. See #2765 for more details.
  740. """
  741. removed = {
  742. # removed 2021-09-05
  743. '2to3_doctests',
  744. }
  745. return ep.name in removed
  746. def _finalize_setup_keywords(self):
  747. for ep in metadata.entry_points(group='distutils.setup_keywords'):
  748. value = getattr(self, ep.name, None)
  749. if value is not None:
  750. self._install_dependencies(ep)
  751. ep.load()(self, ep.name, value)
  752. def _install_dependencies(self, ep):
  753. """
  754. Given an entry point, ensure that any declared extras for
  755. its distribution are installed.
  756. """
  757. for req in nspektr.missing(ep):
  758. # fetch_build_egg expects pkg_resources.Requirement
  759. self.fetch_build_egg(pkg_resources.Requirement(str(req)))
  760. def get_egg_cache_dir(self):
  761. egg_cache_dir = os.path.join(os.curdir, '.eggs')
  762. if not os.path.exists(egg_cache_dir):
  763. os.mkdir(egg_cache_dir)
  764. windows_support.hide_file(egg_cache_dir)
  765. readme_txt_filename = os.path.join(egg_cache_dir, 'README.txt')
  766. with open(readme_txt_filename, 'w') as f:
  767. f.write(
  768. 'This directory contains eggs that were downloaded '
  769. 'by setuptools to build, test, and run plug-ins.\n\n'
  770. )
  771. f.write(
  772. 'This directory caches those eggs to prevent '
  773. 'repeated downloads.\n\n'
  774. )
  775. f.write('However, it is safe to delete this directory.\n\n')
  776. return egg_cache_dir
  777. def fetch_build_egg(self, req):
  778. """Fetch an egg needed for building"""
  779. from setuptools.installer import fetch_build_egg
  780. return fetch_build_egg(self, req)
  781. def get_command_class(self, command):
  782. """Pluggable version of get_command_class()"""
  783. if command in self.cmdclass:
  784. return self.cmdclass[command]
  785. eps = metadata.entry_points(group='distutils.commands', name=command)
  786. for ep in eps:
  787. self._install_dependencies(ep)
  788. self.cmdclass[command] = cmdclass = ep.load()
  789. return cmdclass
  790. else:
  791. return _Distribution.get_command_class(self, command)
  792. def print_commands(self):
  793. for ep in metadata.entry_points(group='distutils.commands'):
  794. if ep.name not in self.cmdclass:
  795. cmdclass = ep.load()
  796. self.cmdclass[ep.name] = cmdclass
  797. return _Distribution.print_commands(self)
  798. def get_command_list(self):
  799. for ep in metadata.entry_points(group='distutils.commands'):
  800. if ep.name not in self.cmdclass:
  801. cmdclass = ep.load()
  802. self.cmdclass[ep.name] = cmdclass
  803. return _Distribution.get_command_list(self)
  804. def include(self, **attrs):
  805. """Add items to distribution that are named in keyword arguments
  806. For example, 'dist.include(py_modules=["x"])' would add 'x' to
  807. the distribution's 'py_modules' attribute, if it was not already
  808. there.
  809. Currently, this method only supports inclusion for attributes that are
  810. lists or tuples. If you need to add support for adding to other
  811. attributes in this or a subclass, you can add an '_include_X' method,
  812. where 'X' is the name of the attribute. The method will be called with
  813. the value passed to 'include()'. So, 'dist.include(foo={"bar":"baz"})'
  814. will try to call 'dist._include_foo({"bar":"baz"})', which can then
  815. handle whatever special inclusion logic is needed.
  816. """
  817. for k, v in attrs.items():
  818. include = getattr(self, '_include_' + k, None)
  819. if include:
  820. include(v)
  821. else:
  822. self._include_misc(k, v)
  823. def exclude_package(self, package):
  824. """Remove packages, modules, and extensions in named package"""
  825. pfx = package + '.'
  826. if self.packages:
  827. self.packages = [
  828. p for p in self.packages if p != package and not p.startswith(pfx)
  829. ]
  830. if self.py_modules:
  831. self.py_modules = [
  832. p for p in self.py_modules if p != package and not p.startswith(pfx)
  833. ]
  834. if self.ext_modules:
  835. self.ext_modules = [
  836. p
  837. for p in self.ext_modules
  838. if p.name != package and not p.name.startswith(pfx)
  839. ]
  840. def has_contents_for(self, package):
  841. """Return true if 'exclude_package(package)' would do something"""
  842. pfx = package + '.'
  843. for p in self.iter_distribution_names():
  844. if p == package or p.startswith(pfx):
  845. return True
  846. def _exclude_misc(self, name, value):
  847. """Handle 'exclude()' for list/tuple attrs without a special handler"""
  848. if not isinstance(value, sequence):
  849. raise DistutilsSetupError(
  850. "%s: setting must be a list or tuple (%r)" % (name, value)
  851. )
  852. try:
  853. old = getattr(self, name)
  854. except AttributeError as e:
  855. raise DistutilsSetupError("%s: No such distribution setting" % name) from e
  856. if old is not None and not isinstance(old, sequence):
  857. raise DistutilsSetupError(
  858. name + ": this setting cannot be changed via include/exclude"
  859. )
  860. elif old:
  861. setattr(self, name, [item for item in old if item not in value])
  862. def _include_misc(self, name, value):
  863. """Handle 'include()' for list/tuple attrs without a special handler"""
  864. if not isinstance(value, sequence):
  865. raise DistutilsSetupError("%s: setting must be a list (%r)" % (name, value))
  866. try:
  867. old = getattr(self, name)
  868. except AttributeError as e:
  869. raise DistutilsSetupError("%s: No such distribution setting" % name) from e
  870. if old is None:
  871. setattr(self, name, value)
  872. elif not isinstance(old, sequence):
  873. raise DistutilsSetupError(
  874. name + ": this setting cannot be changed via include/exclude"
  875. )
  876. else:
  877. new = [item for item in value if item not in old]
  878. setattr(self, name, old + new)
  879. def exclude(self, **attrs):
  880. """Remove items from distribution that are named in keyword arguments
  881. For example, 'dist.exclude(py_modules=["x"])' would remove 'x' from
  882. the distribution's 'py_modules' attribute. Excluding packages uses
  883. the 'exclude_package()' method, so all of the package's contained
  884. packages, modules, and extensions are also excluded.
  885. Currently, this method only supports exclusion from attributes that are
  886. lists or tuples. If you need to add support for excluding from other
  887. attributes in this or a subclass, you can add an '_exclude_X' method,
  888. where 'X' is the name of the attribute. The method will be called with
  889. the value passed to 'exclude()'. So, 'dist.exclude(foo={"bar":"baz"})'
  890. will try to call 'dist._exclude_foo({"bar":"baz"})', which can then
  891. handle whatever special exclusion logic is needed.
  892. """
  893. for k, v in attrs.items():
  894. exclude = getattr(self, '_exclude_' + k, None)
  895. if exclude:
  896. exclude(v)
  897. else:
  898. self._exclude_misc(k, v)
  899. def _exclude_packages(self, packages):
  900. if not isinstance(packages, sequence):
  901. raise DistutilsSetupError(
  902. "packages: setting must be a list or tuple (%r)" % (packages,)
  903. )
  904. list(map(self.exclude_package, packages))
  905. def _parse_command_opts(self, parser, args):
  906. # Remove --with-X/--without-X options when processing command args
  907. self.global_options = self.__class__.global_options
  908. self.negative_opt = self.__class__.negative_opt
  909. # First, expand any aliases
  910. command = args[0]
  911. aliases = self.get_option_dict('aliases')
  912. while command in aliases:
  913. src, alias = aliases[command]
  914. del aliases[command] # ensure each alias can expand only once!
  915. import shlex
  916. args[:1] = shlex.split(alias, True)
  917. command = args[0]
  918. nargs = _Distribution._parse_command_opts(self, parser, args)
  919. # Handle commands that want to consume all remaining arguments
  920. cmd_class = self.get_command_class(command)
  921. if getattr(cmd_class, 'command_consumes_arguments', None):
  922. self.get_option_dict(command)['args'] = ("command line", nargs)
  923. if nargs is not None:
  924. return []
  925. return nargs
  926. def get_cmdline_options(self):
  927. """Return a '{cmd: {opt:val}}' map of all command-line options
  928. Option names are all long, but do not include the leading '--', and
  929. contain dashes rather than underscores. If the option doesn't take
  930. an argument (e.g. '--quiet'), the 'val' is 'None'.
  931. Note that options provided by config files are intentionally excluded.
  932. """
  933. d = {}
  934. for cmd, opts in self.command_options.items():
  935. for opt, (src, val) in opts.items():
  936. if src != "command line":
  937. continue
  938. opt = opt.replace('_', '-')
  939. if val == 0:
  940. cmdobj = self.get_command_obj(cmd)
  941. neg_opt = self.negative_opt.copy()
  942. neg_opt.update(getattr(cmdobj, 'negative_opt', {}))
  943. for neg, pos in neg_opt.items():
  944. if pos == opt:
  945. opt = neg
  946. val = None
  947. break
  948. else:
  949. raise AssertionError("Shouldn't be able to get here")
  950. elif val == 1:
  951. val = None
  952. d.setdefault(cmd, {})[opt] = val
  953. return d
  954. def iter_distribution_names(self):
  955. """Yield all packages, modules, and extension names in distribution"""
  956. for pkg in self.packages or ():
  957. yield pkg
  958. for module in self.py_modules or ():
  959. yield module
  960. for ext in self.ext_modules or ():
  961. if isinstance(ext, tuple):
  962. name, buildinfo = ext
  963. else:
  964. name = ext.name
  965. if name.endswith('module'):
  966. name = name[:-6]
  967. yield name
  968. def handle_display_options(self, option_order):
  969. """If there were any non-global "display-only" options
  970. (--help-commands or the metadata display options) on the command
  971. line, display the requested info and return true; else return
  972. false.
  973. """
  974. import sys
  975. if self.help_commands:
  976. return _Distribution.handle_display_options(self, option_order)
  977. # Stdout may be StringIO (e.g. in tests)
  978. if not isinstance(sys.stdout, io.TextIOWrapper):
  979. return _Distribution.handle_display_options(self, option_order)
  980. # Don't wrap stdout if utf-8 is already the encoding. Provides
  981. # workaround for #334.
  982. if sys.stdout.encoding.lower() in ('utf-8', 'utf8'):
  983. return _Distribution.handle_display_options(self, option_order)
  984. # Print metadata in UTF-8 no matter the platform
  985. encoding = sys.stdout.encoding
  986. errors = sys.stdout.errors
  987. newline = sys.platform != 'win32' and '\n' or None
  988. line_buffering = sys.stdout.line_buffering
  989. sys.stdout = io.TextIOWrapper(
  990. sys.stdout.detach(), 'utf-8', errors, newline, line_buffering
  991. )
  992. try:
  993. return _Distribution.handle_display_options(self, option_order)
  994. finally:
  995. sys.stdout = io.TextIOWrapper(
  996. sys.stdout.detach(), encoding, errors, newline, line_buffering
  997. )
  998. def run_command(self, command):
  999. self.set_defaults()
  1000. # Postpone defaults until all explicit configuration is considered
  1001. # (setup() args, config files, command line and plugins)
  1002. super().run_command(command)
  1003. class DistDeprecationWarning(SetuptoolsDeprecationWarning):
  1004. """Class for warning about deprecations in dist in
  1005. setuptools. Not ignored by default, unlike DeprecationWarning."""