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.

1147 lines
44 KiB

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