dist.py 40 KB

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