Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dist.py 42KB

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