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.

1031 lines
38 KiB

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