dist.py 42 KB

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