您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

1282 行
49 KiB

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