1
0

dist.py 38 KB

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