dist.py 33 KB

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