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.

1116 lines
41KB

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