dist.py 39 KB

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