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 34 KiB

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