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

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