dist.py 45 KB

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