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.

1012 lines
39 KiB

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

Powered by TurnKey Linux.