dist.py 49 KB

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