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.

dist.py 49KB

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