dist.py 38 KB

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