dist.py 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285
  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.errors import DistutilsOptionError
  14. from distutils.util import strtobool
  15. from distutils.debug import DEBUG
  16. from distutils.fancy_getopt import translate_longopt
  17. import itertools
  18. from collections import defaultdict
  19. from email import message_from_file
  20. from distutils.errors import (
  21. DistutilsOptionError, DistutilsPlatformError, DistutilsSetupError,
  22. )
  23. from distutils.util import rfc822_escape
  24. from distutils.version import StrictVersion
  25. from setuptools.extern import six
  26. from setuptools.extern import packaging
  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. from .unicode_utils import detect_encoding
  34. import pkg_resources
  35. __import__('setuptools.extern.packaging.specifiers')
  36. __import__('setuptools.extern.packaging.version')
  37. def _get_unpatched(cls):
  38. warnings.warn("Do not call this function", DistDeprecationWarning)
  39. return get_unpatched(cls)
  40. def get_metadata_version(self):
  41. mv = getattr(self, 'metadata_version', None)
  42. if mv is None:
  43. if self.long_description_content_type or self.provides_extras:
  44. mv = StrictVersion('2.1')
  45. elif (self.maintainer is not None or
  46. self.maintainer_email is not None or
  47. getattr(self, 'python_requires', None) is not None):
  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 or None"""
  173. try:
  174. assert ''.join(value) != value
  175. except (TypeError, ValueError, AttributeError, AssertionError):
  176. raise DistutilsSetupError(
  177. "%r must be a list of strings (got %r)" % (attr, value)
  178. )
  179. def check_nsp(dist, attr, value):
  180. """Verify that namespace packages are valid"""
  181. ns_packages = value
  182. assert_string_list(dist, attr, ns_packages)
  183. for nsp in ns_packages:
  184. if not dist.has_contents_for(nsp):
  185. raise DistutilsSetupError(
  186. "Distribution contains no modules or packages for " +
  187. "namespace package %r" % nsp
  188. )
  189. parent, sep, child = nsp.rpartition('.')
  190. if parent and parent not in ns_packages:
  191. distutils.log.warn(
  192. "WARNING: %r is declared as a package namespace, but %r"
  193. " is not: please correct this in setup.py", nsp, parent
  194. )
  195. def check_extras(dist, attr, value):
  196. """Verify that extras_require mapping is valid"""
  197. try:
  198. list(itertools.starmap(_check_extra, value.items()))
  199. except (TypeError, ValueError, AttributeError):
  200. raise DistutilsSetupError(
  201. "'extras_require' must be a dictionary whose values are "
  202. "strings or lists of strings containing valid project/version "
  203. "requirement specifiers."
  204. )
  205. def _check_extra(extra, reqs):
  206. name, sep, marker = extra.partition(':')
  207. if marker and pkg_resources.invalid_marker(marker):
  208. raise DistutilsSetupError("Invalid environment marker: " + marker)
  209. list(pkg_resources.parse_requirements(reqs))
  210. def assert_bool(dist, attr, value):
  211. """Verify that value is True, False, 0, or 1"""
  212. if bool(value) != value:
  213. tmpl = "{attr!r} must be a boolean value (got {value!r})"
  214. raise DistutilsSetupError(tmpl.format(attr=attr, value=value))
  215. def check_requirements(dist, attr, value):
  216. """Verify that install_requires is a valid requirements list"""
  217. try:
  218. list(pkg_resources.parse_requirements(value))
  219. if isinstance(value, (dict, set)):
  220. raise TypeError("Unordered types are not allowed")
  221. except (TypeError, ValueError) as error:
  222. tmpl = (
  223. "{attr!r} must be a string or list of strings "
  224. "containing valid project/version requirement specifiers; {error}"
  225. )
  226. raise DistutilsSetupError(tmpl.format(attr=attr, error=error))
  227. def check_specifier(dist, attr, value):
  228. """Verify that value is a valid version specifier"""
  229. try:
  230. packaging.specifiers.SpecifierSet(value)
  231. except packaging.specifiers.InvalidSpecifier as error:
  232. tmpl = (
  233. "{attr!r} must be a string "
  234. "containing valid version specifiers; {error}"
  235. )
  236. raise DistutilsSetupError(tmpl.format(attr=attr, error=error))
  237. def check_entry_points(dist, attr, value):
  238. """Verify that entry_points map is parseable"""
  239. try:
  240. pkg_resources.EntryPoint.parse_map(value)
  241. except ValueError as e:
  242. raise DistutilsSetupError(e)
  243. def check_test_suite(dist, attr, value):
  244. if not isinstance(value, six.string_types):
  245. raise DistutilsSetupError("test_suite must be a string")
  246. def check_package_data(dist, attr, value):
  247. """Verify that value is a dictionary of package names to glob lists"""
  248. if isinstance(value, dict):
  249. for k, v in value.items():
  250. if not isinstance(k, str):
  251. break
  252. try:
  253. iter(v)
  254. except TypeError:
  255. break
  256. else:
  257. return
  258. raise DistutilsSetupError(
  259. attr + " must be a dictionary mapping package names to lists of "
  260. "wildcard patterns"
  261. )
  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, 'rb') as fp:
  490. encoding = detect_encoding(fp)
  491. if DEBUG:
  492. self.announce(" reading %s [%s]" % (
  493. filename, encoding or 'locale')
  494. )
  495. reader = io.TextIOWrapper(fp, encoding=encoding)
  496. (parser.read_file if six.PY3 else parser.readfp)(reader)
  497. for section in parser.sections():
  498. options = parser.options(section)
  499. opt_dict = self.get_option_dict(section)
  500. for opt in options:
  501. if opt != '__name__' and opt not in ignore_options:
  502. val = self._try_str(parser.get(section, opt))
  503. opt = opt.replace('-', '_')
  504. opt_dict[opt] = (filename, val)
  505. # Make the ConfigParser forget everything (so we retain
  506. # the original filenames that options come from)
  507. parser.__init__()
  508. # If there was a "global" section in the config file, use it
  509. # to set Distribution options.
  510. if 'global' in self.command_options:
  511. for (opt, (src, val)) in self.command_options['global'].items():
  512. alias = self.negative_opt.get(opt)
  513. try:
  514. if alias:
  515. setattr(self, alias, not strtobool(val))
  516. elif opt in ('verbose', 'dry_run'): # ugh!
  517. setattr(self, opt, strtobool(val))
  518. else:
  519. setattr(self, opt, val)
  520. except ValueError as msg:
  521. raise DistutilsOptionError(msg)
  522. @staticmethod
  523. def _try_str(val):
  524. """
  525. On Python 2, much of distutils relies on string values being of
  526. type 'str' (bytes) and not unicode text. If the value can be safely
  527. encoded to bytes using the default encoding, prefer that.
  528. Why the default encoding? Because that value can be implicitly
  529. decoded back to text if needed.
  530. Ref #1653
  531. """
  532. if six.PY3:
  533. return val
  534. try:
  535. return val.encode()
  536. except UnicodeEncodeError:
  537. pass
  538. return val
  539. def _set_command_options(self, command_obj, option_dict=None):
  540. """
  541. Set the options for 'command_obj' from 'option_dict'. Basically
  542. this means copying elements of a dictionary ('option_dict') to
  543. attributes of an instance ('command').
  544. 'command_obj' must be a Command instance. If 'option_dict' is not
  545. supplied, uses the standard option dictionary for this command
  546. (from 'self.command_options').
  547. (Adopted from distutils.dist.Distribution._set_command_options)
  548. """
  549. command_name = command_obj.get_command_name()
  550. if option_dict is None:
  551. option_dict = self.get_option_dict(command_name)
  552. if DEBUG:
  553. self.announce(" setting options for '%s' command:" % command_name)
  554. for (option, (source, value)) in option_dict.items():
  555. if DEBUG:
  556. self.announce(" %s = %s (from %s)" % (option, value,
  557. source))
  558. try:
  559. bool_opts = [translate_longopt(o)
  560. for o in command_obj.boolean_options]
  561. except AttributeError:
  562. bool_opts = []
  563. try:
  564. neg_opt = command_obj.negative_opt
  565. except AttributeError:
  566. neg_opt = {}
  567. try:
  568. is_string = isinstance(value, six.string_types)
  569. if option in neg_opt and is_string:
  570. setattr(command_obj, neg_opt[option], not strtobool(value))
  571. elif option in bool_opts and is_string:
  572. setattr(command_obj, option, strtobool(value))
  573. elif hasattr(command_obj, option):
  574. setattr(command_obj, option, value)
  575. else:
  576. raise DistutilsOptionError(
  577. "error in %s: command '%s' has no such option '%s'"
  578. % (source, command_name, option))
  579. except ValueError as msg:
  580. raise DistutilsOptionError(msg)
  581. def parse_config_files(self, filenames=None, ignore_option_errors=False):
  582. """Parses configuration files from various levels
  583. and loads configuration.
  584. """
  585. self._parse_config_files(filenames=filenames)
  586. parse_configuration(self, self.command_options,
  587. ignore_option_errors=ignore_option_errors)
  588. self._finalize_requires()
  589. def parse_command_line(self):
  590. """Process features after parsing command line options"""
  591. result = _Distribution.parse_command_line(self)
  592. if self.features:
  593. self._finalize_features()
  594. return result
  595. def _feature_attrname(self, name):
  596. """Convert feature name to corresponding option attribute name"""
  597. return 'with_' + name.replace('-', '_')
  598. def fetch_build_eggs(self, requires):
  599. """Resolve pre-setup requirements"""
  600. resolved_dists = pkg_resources.working_set.resolve(
  601. pkg_resources.parse_requirements(requires),
  602. installer=self.fetch_build_egg,
  603. replace_conflicting=True,
  604. )
  605. for dist in resolved_dists:
  606. pkg_resources.working_set.add(dist, replace=True)
  607. return resolved_dists
  608. def finalize_options(self):
  609. _Distribution.finalize_options(self)
  610. if self.features:
  611. self._set_global_opts_from_features()
  612. for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
  613. value = getattr(self, ep.name, None)
  614. if value is not None:
  615. ep.require(installer=self.fetch_build_egg)
  616. ep.load()(self, ep.name, value)
  617. if getattr(self, 'convert_2to3_doctests', None):
  618. # XXX may convert to set here when we can rely on set being builtin
  619. self.convert_2to3_doctests = [
  620. os.path.abspath(p)
  621. for p in self.convert_2to3_doctests
  622. ]
  623. else:
  624. self.convert_2to3_doctests = []
  625. def get_egg_cache_dir(self):
  626. egg_cache_dir = os.path.join(os.curdir, '.eggs')
  627. if not os.path.exists(egg_cache_dir):
  628. os.mkdir(egg_cache_dir)
  629. windows_support.hide_file(egg_cache_dir)
  630. readme_txt_filename = os.path.join(egg_cache_dir, 'README.txt')
  631. with open(readme_txt_filename, 'w') as f:
  632. f.write('This directory contains eggs that were downloaded '
  633. 'by setuptools to build, test, and run plug-ins.\n\n')
  634. f.write('This directory caches those eggs to prevent '
  635. 'repeated downloads.\n\n')
  636. f.write('However, it is safe to delete this directory.\n\n')
  637. return egg_cache_dir
  638. def fetch_build_egg(self, req):
  639. """Fetch an egg needed for building"""
  640. from setuptools.command.easy_install import easy_install
  641. dist = self.__class__({'script_args': ['easy_install']})
  642. opts = dist.get_option_dict('easy_install')
  643. opts.clear()
  644. opts.update(
  645. (k, v)
  646. for k, v in self.get_option_dict('easy_install').items()
  647. if k in (
  648. # don't use any other settings
  649. 'find_links', 'site_dirs', 'index_url',
  650. 'optimize', 'site_dirs', 'allow_hosts',
  651. ))
  652. if self.dependency_links:
  653. links = self.dependency_links[:]
  654. if 'find_links' in opts:
  655. links = opts['find_links'][1] + links
  656. opts['find_links'] = ('setup', links)
  657. install_dir = self.get_egg_cache_dir()
  658. cmd = easy_install(
  659. dist, args=["x"], install_dir=install_dir,
  660. exclude_scripts=True,
  661. always_copy=False, build_directory=None, editable=False,
  662. upgrade=False, multi_version=True, no_report=True, user=False
  663. )
  664. cmd.ensure_finalized()
  665. return cmd.easy_install(req)
  666. def _set_global_opts_from_features(self):
  667. """Add --with-X/--without-X options based on optional features"""
  668. go = []
  669. no = self.negative_opt.copy()
  670. for name, feature in self.features.items():
  671. self._set_feature(name, None)
  672. feature.validate(self)
  673. if feature.optional:
  674. descr = feature.description
  675. incdef = ' (default)'
  676. excdef = ''
  677. if not feature.include_by_default():
  678. excdef, incdef = incdef, excdef
  679. new = (
  680. ('with-' + name, None, 'include ' + descr + incdef),
  681. ('without-' + name, None, 'exclude ' + descr + excdef),
  682. )
  683. go.extend(new)
  684. no['without-' + name] = 'with-' + name
  685. self.global_options = self.feature_options = go + self.global_options
  686. self.negative_opt = self.feature_negopt = no
  687. def _finalize_features(self):
  688. """Add/remove features and resolve dependencies between them"""
  689. # First, flag all the enabled items (and thus their dependencies)
  690. for name, feature in self.features.items():
  691. enabled = self.feature_is_included(name)
  692. if enabled or (enabled is None and feature.include_by_default()):
  693. feature.include_in(self)
  694. self._set_feature(name, 1)
  695. # Then disable the rest, so that off-by-default features don't
  696. # get flagged as errors when they're required by an enabled feature
  697. for name, feature in self.features.items():
  698. if not self.feature_is_included(name):
  699. feature.exclude_from(self)
  700. self._set_feature(name, 0)
  701. def get_command_class(self, command):
  702. """Pluggable version of get_command_class()"""
  703. if command in self.cmdclass:
  704. return self.cmdclass[command]
  705. eps = pkg_resources.iter_entry_points('distutils.commands', command)
  706. for ep in eps:
  707. ep.require(installer=self.fetch_build_egg)
  708. self.cmdclass[command] = cmdclass = ep.load()
  709. return cmdclass
  710. else:
  711. return _Distribution.get_command_class(self, command)
  712. def print_commands(self):
  713. for ep in pkg_resources.iter_entry_points('distutils.commands'):
  714. if ep.name not in self.cmdclass:
  715. # don't require extras as the commands won't be invoked
  716. cmdclass = ep.resolve()
  717. self.cmdclass[ep.name] = cmdclass
  718. return _Distribution.print_commands(self)
  719. def get_command_list(self):
  720. for ep in pkg_resources.iter_entry_points('distutils.commands'):
  721. if ep.name not in self.cmdclass:
  722. # don't require extras as the commands won't be invoked
  723. cmdclass = ep.resolve()
  724. self.cmdclass[ep.name] = cmdclass
  725. return _Distribution.get_command_list(self)
  726. def _set_feature(self, name, status):
  727. """Set feature's inclusion status"""
  728. setattr(self, self._feature_attrname(name), status)
  729. def feature_is_included(self, name):
  730. """Return 1 if feature is included, 0 if excluded, 'None' if unknown"""
  731. return getattr(self, self._feature_attrname(name))
  732. def include_feature(self, name):
  733. """Request inclusion of feature named 'name'"""
  734. if self.feature_is_included(name) == 0:
  735. descr = self.features[name].description
  736. raise DistutilsOptionError(
  737. descr + " is required, but was excluded or is not available"
  738. )
  739. self.features[name].include_in(self)
  740. self._set_feature(name, 1)
  741. def include(self, **attrs):
  742. """Add items to distribution that are named in keyword arguments
  743. For example, 'dist.exclude(py_modules=["x"])' would add 'x' to
  744. the distribution's 'py_modules' attribute, if it was not already
  745. there.
  746. Currently, this method only supports inclusion for attributes that are
  747. lists or tuples. If you need to add support for adding to other
  748. attributes in this or a subclass, you can add an '_include_X' method,
  749. where 'X' is the name of the attribute. The method will be called with
  750. the value passed to 'include()'. So, 'dist.include(foo={"bar":"baz"})'
  751. will try to call 'dist._include_foo({"bar":"baz"})', which can then
  752. handle whatever special inclusion logic is needed.
  753. """
  754. for k, v in attrs.items():
  755. include = getattr(self, '_include_' + k, None)
  756. if include:
  757. include(v)
  758. else:
  759. self._include_misc(k, v)
  760. def exclude_package(self, package):
  761. """Remove packages, modules, and extensions in named package"""
  762. pfx = package + '.'
  763. if self.packages:
  764. self.packages = [
  765. p for p in self.packages
  766. if p != package and not p.startswith(pfx)
  767. ]
  768. if self.py_modules:
  769. self.py_modules = [
  770. p for p in self.py_modules
  771. if p != package and not p.startswith(pfx)
  772. ]
  773. if self.ext_modules:
  774. self.ext_modules = [
  775. p for p in self.ext_modules
  776. if p.name != package and not p.name.startswith(pfx)
  777. ]
  778. def has_contents_for(self, package):
  779. """Return true if 'exclude_package(package)' would do something"""
  780. pfx = package + '.'
  781. for p in self.iter_distribution_names():
  782. if p == package or p.startswith(pfx):
  783. return True
  784. def _exclude_misc(self, name, value):
  785. """Handle 'exclude()' for list/tuple attrs without a special handler"""
  786. if not isinstance(value, sequence):
  787. raise DistutilsSetupError(
  788. "%s: setting must be a list or tuple (%r)" % (name, value)
  789. )
  790. try:
  791. old = getattr(self, name)
  792. except AttributeError:
  793. raise DistutilsSetupError(
  794. "%s: No such distribution setting" % name
  795. )
  796. if old is not None and not isinstance(old, sequence):
  797. raise DistutilsSetupError(
  798. name + ": this setting cannot be changed via include/exclude"
  799. )
  800. elif old:
  801. setattr(self, name, [item for item in old if item not in value])
  802. def _include_misc(self, name, value):
  803. """Handle 'include()' for list/tuple attrs without a special handler"""
  804. if not isinstance(value, sequence):
  805. raise DistutilsSetupError(
  806. "%s: setting must be a list (%r)" % (name, value)
  807. )
  808. try:
  809. old = getattr(self, name)
  810. except AttributeError:
  811. raise DistutilsSetupError(
  812. "%s: No such distribution setting" % name
  813. )
  814. if old is None:
  815. setattr(self, name, value)
  816. elif not isinstance(old, sequence):
  817. raise DistutilsSetupError(
  818. name + ": this setting cannot be changed via include/exclude"
  819. )
  820. else:
  821. new = [item for item in value if item not in old]
  822. setattr(self, name, old + new)
  823. def exclude(self, **attrs):
  824. """Remove items from distribution that are named in keyword arguments
  825. For example, 'dist.exclude(py_modules=["x"])' would remove 'x' from
  826. the distribution's 'py_modules' attribute. Excluding packages uses
  827. the 'exclude_package()' method, so all of the package's contained
  828. packages, modules, and extensions are also excluded.
  829. Currently, this method only supports exclusion from attributes that are
  830. lists or tuples. If you need to add support for excluding from other
  831. attributes in this or a subclass, you can add an '_exclude_X' method,
  832. where 'X' is the name of the attribute. The method will be called with
  833. the value passed to 'exclude()'. So, 'dist.exclude(foo={"bar":"baz"})'
  834. will try to call 'dist._exclude_foo({"bar":"baz"})', which can then
  835. handle whatever special exclusion logic is needed.
  836. """
  837. for k, v in attrs.items():
  838. exclude = getattr(self, '_exclude_' + k, None)
  839. if exclude:
  840. exclude(v)
  841. else:
  842. self._exclude_misc(k, v)
  843. def _exclude_packages(self, packages):
  844. if not isinstance(packages, sequence):
  845. raise DistutilsSetupError(
  846. "packages: setting must be a list or tuple (%r)" % (packages,)
  847. )
  848. list(map(self.exclude_package, packages))
  849. def _parse_command_opts(self, parser, args):
  850. # Remove --with-X/--without-X options when processing command args
  851. self.global_options = self.__class__.global_options
  852. self.negative_opt = self.__class__.negative_opt
  853. # First, expand any aliases
  854. command = args[0]
  855. aliases = self.get_option_dict('aliases')
  856. while command in aliases:
  857. src, alias = aliases[command]
  858. del aliases[command] # ensure each alias can expand only once!
  859. import shlex
  860. args[:1] = shlex.split(alias, True)
  861. command = args[0]
  862. nargs = _Distribution._parse_command_opts(self, parser, args)
  863. # Handle commands that want to consume all remaining arguments
  864. cmd_class = self.get_command_class(command)
  865. if getattr(cmd_class, 'command_consumes_arguments', None):
  866. self.get_option_dict(command)['args'] = ("command line", nargs)
  867. if nargs is not None:
  868. return []
  869. return nargs
  870. def get_cmdline_options(self):
  871. """Return a '{cmd: {opt:val}}' map of all command-line options
  872. Option names are all long, but do not include the leading '--', and
  873. contain dashes rather than underscores. If the option doesn't take
  874. an argument (e.g. '--quiet'), the 'val' is 'None'.
  875. Note that options provided by config files are intentionally excluded.
  876. """
  877. d = {}
  878. for cmd, opts in self.command_options.items():
  879. for opt, (src, val) in opts.items():
  880. if src != "command line":
  881. continue
  882. opt = opt.replace('_', '-')
  883. if val == 0:
  884. cmdobj = self.get_command_obj(cmd)
  885. neg_opt = self.negative_opt.copy()
  886. neg_opt.update(getattr(cmdobj, 'negative_opt', {}))
  887. for neg, pos in neg_opt.items():
  888. if pos == opt:
  889. opt = neg
  890. val = None
  891. break
  892. else:
  893. raise AssertionError("Shouldn't be able to get here")
  894. elif val == 1:
  895. val = None
  896. d.setdefault(cmd, {})[opt] = val
  897. return d
  898. def iter_distribution_names(self):
  899. """Yield all packages, modules, and extension names in distribution"""
  900. for pkg in self.packages or ():
  901. yield pkg
  902. for module in self.py_modules or ():
  903. yield module
  904. for ext in self.ext_modules or ():
  905. if isinstance(ext, tuple):
  906. name, buildinfo = ext
  907. else:
  908. name = ext.name
  909. if name.endswith('module'):
  910. name = name[:-6]
  911. yield name
  912. def handle_display_options(self, option_order):
  913. """If there were any non-global "display-only" options
  914. (--help-commands or the metadata display options) on the command
  915. line, display the requested info and return true; else return
  916. false.
  917. """
  918. import sys
  919. if six.PY2 or self.help_commands:
  920. return _Distribution.handle_display_options(self, option_order)
  921. # Stdout may be StringIO (e.g. in tests)
  922. import io
  923. if not isinstance(sys.stdout, io.TextIOWrapper):
  924. return _Distribution.handle_display_options(self, option_order)
  925. # Don't wrap stdout if utf-8 is already the encoding. Provides
  926. # workaround for #334.
  927. if sys.stdout.encoding.lower() in ('utf-8', 'utf8'):
  928. return _Distribution.handle_display_options(self, option_order)
  929. # Print metadata in UTF-8 no matter the platform
  930. encoding = sys.stdout.encoding
  931. errors = sys.stdout.errors
  932. newline = sys.platform != 'win32' and '\n' or None
  933. line_buffering = sys.stdout.line_buffering
  934. sys.stdout = io.TextIOWrapper(
  935. sys.stdout.detach(), 'utf-8', errors, newline, line_buffering)
  936. try:
  937. return _Distribution.handle_display_options(self, option_order)
  938. finally:
  939. sys.stdout = io.TextIOWrapper(
  940. sys.stdout.detach(), encoding, errors, newline, line_buffering)
  941. class Feature:
  942. """
  943. **deprecated** -- The `Feature` facility was never completely implemented
  944. or supported, `has reported issues
  945. <https://github.com/pypa/setuptools/issues/58>`_ and will be removed in
  946. a future version.
  947. A subset of the distribution that can be excluded if unneeded/wanted
  948. Features are created using these keyword arguments:
  949. 'description' -- a short, human readable description of the feature, to
  950. be used in error messages, and option help messages.
  951. 'standard' -- if true, the feature is included by default if it is
  952. available on the current system. Otherwise, the feature is only
  953. included if requested via a command line '--with-X' option, or if
  954. another included feature requires it. The default setting is 'False'.
  955. 'available' -- if true, the feature is available for installation on the
  956. current system. The default setting is 'True'.
  957. 'optional' -- if true, the feature's inclusion can be controlled from the
  958. command line, using the '--with-X' or '--without-X' options. If
  959. false, the feature's inclusion status is determined automatically,
  960. based on 'availabile', 'standard', and whether any other feature
  961. requires it. The default setting is 'True'.
  962. 'require_features' -- a string or sequence of strings naming features
  963. that should also be included if this feature is included. Defaults to
  964. empty list. May also contain 'Require' objects that should be
  965. added/removed from the distribution.
  966. 'remove' -- a string or list of strings naming packages to be removed
  967. from the distribution if this feature is *not* included. If the
  968. feature *is* included, this argument is ignored. This argument exists
  969. to support removing features that "crosscut" a distribution, such as
  970. defining a 'tests' feature that removes all the 'tests' subpackages
  971. provided by other features. The default for this argument is an empty
  972. list. (Note: the named package(s) or modules must exist in the base
  973. distribution when the 'setup()' function is initially called.)
  974. other keywords -- any other keyword arguments are saved, and passed to
  975. the distribution's 'include()' and 'exclude()' methods when the
  976. feature is included or excluded, respectively. So, for example, you
  977. could pass 'packages=["a","b"]' to cause packages 'a' and 'b' to be
  978. added or removed from the distribution as appropriate.
  979. A feature must include at least one 'requires', 'remove', or other
  980. keyword argument. Otherwise, it can't affect the distribution in any way.
  981. Note also that you can subclass 'Feature' to create your own specialized
  982. feature types that modify the distribution in other ways when included or
  983. excluded. See the docstrings for the various methods here for more detail.
  984. Aside from the methods, the only feature attributes that distributions look
  985. at are 'description' and 'optional'.
  986. """
  987. @staticmethod
  988. def warn_deprecated():
  989. msg = (
  990. "Features are deprecated and will be removed in a future "
  991. "version. See https://github.com/pypa/setuptools/issues/65."
  992. )
  993. warnings.warn(msg, DistDeprecationWarning, stacklevel=3)
  994. def __init__(
  995. self, description, standard=False, available=True,
  996. optional=True, require_features=(), remove=(), **extras):
  997. self.warn_deprecated()
  998. self.description = description
  999. self.standard = standard
  1000. self.available = available
  1001. self.optional = optional
  1002. if isinstance(require_features, (str, Require)):
  1003. require_features = require_features,
  1004. self.require_features = [
  1005. r for r in require_features if isinstance(r, str)
  1006. ]
  1007. er = [r for r in require_features if not isinstance(r, str)]
  1008. if er:
  1009. extras['require_features'] = er
  1010. if isinstance(remove, str):
  1011. remove = remove,
  1012. self.remove = remove
  1013. self.extras = extras
  1014. if not remove and not require_features and not extras:
  1015. raise DistutilsSetupError(
  1016. "Feature %s: must define 'require_features', 'remove', or "
  1017. "at least one of 'packages', 'py_modules', etc."
  1018. )
  1019. def include_by_default(self):
  1020. """Should this feature be included by default?"""
  1021. return self.available and self.standard
  1022. def include_in(self, dist):
  1023. """Ensure feature and its requirements are included in distribution
  1024. You may override this in a subclass to perform additional operations on
  1025. the distribution. Note that this method may be called more than once
  1026. per feature, and so should be idempotent.
  1027. """
  1028. if not self.available:
  1029. raise DistutilsPlatformError(
  1030. self.description + " is required, "
  1031. "but is not available on this platform"
  1032. )
  1033. dist.include(**self.extras)
  1034. for f in self.require_features:
  1035. dist.include_feature(f)
  1036. def exclude_from(self, dist):
  1037. """Ensure feature is excluded from distribution
  1038. You may override this in a subclass to perform additional operations on
  1039. the distribution. This method will be called at most once per
  1040. feature, and only after all included features have been asked to
  1041. include themselves.
  1042. """
  1043. dist.exclude(**self.extras)
  1044. if self.remove:
  1045. for item in self.remove:
  1046. dist.exclude_package(item)
  1047. def validate(self, dist):
  1048. """Verify that feature makes sense in context of distribution
  1049. This method is called by the distribution just before it parses its
  1050. command line. It checks to ensure that the 'remove' attribute, if any,
  1051. contains only valid package/module names that are present in the base
  1052. distribution when 'setup()' is called. You may override it in a
  1053. subclass to perform any other required validation of the feature
  1054. against a target distribution.
  1055. """
  1056. for item in self.remove:
  1057. if not dist.has_contents_for(item):
  1058. raise DistutilsSetupError(
  1059. "%s wants to be able to remove %s, but the distribution"
  1060. " doesn't contain any packages or modules under %s"
  1061. % (self.description, item, item)
  1062. )
  1063. class DistDeprecationWarning(SetuptoolsDeprecationWarning):
  1064. """Class for warning about deprecations in dist in setuptools. Not ignored by default, unlike DeprecationWarning."""