dist.py 38 KB

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