dist.py 35 KB

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