Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dist.py 42KB

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