__init__.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. """Extensions to the 'distutils' for large or complex distributions"""
  2. import functools
  3. import os
  4. import re
  5. import warnings
  6. import _distutils_hack.override # noqa: F401
  7. import distutils.core
  8. from distutils.errors import DistutilsOptionError
  9. from distutils.util import convert_path as _convert_path
  10. from ._deprecation_warning import SetuptoolsDeprecationWarning
  11. import setuptools.version
  12. from setuptools.extension import Extension
  13. from setuptools.dist import Distribution
  14. from setuptools.depends import Require
  15. from setuptools.discovery import PackageFinder, PEP420PackageFinder
  16. from . import monkey
  17. from . import logging
  18. __all__ = [
  19. 'setup',
  20. 'Distribution',
  21. 'Command',
  22. 'Extension',
  23. 'Require',
  24. 'SetuptoolsDeprecationWarning',
  25. 'find_packages',
  26. 'find_namespace_packages',
  27. ]
  28. __version__ = setuptools.version.__version__
  29. bootstrap_install_from = None
  30. find_packages = PackageFinder.find
  31. find_namespace_packages = PEP420PackageFinder.find
  32. def _install_setup_requires(attrs):
  33. # Note: do not use `setuptools.Distribution` directly, as
  34. # our PEP 517 backend patch `distutils.core.Distribution`.
  35. class MinimalDistribution(distutils.core.Distribution):
  36. """
  37. A minimal version of a distribution for supporting the
  38. fetch_build_eggs interface.
  39. """
  40. def __init__(self, attrs):
  41. _incl = 'dependency_links', 'setup_requires'
  42. filtered = {k: attrs[k] for k in set(_incl) & set(attrs)}
  43. super().__init__(filtered)
  44. # Prevent accidentally triggering discovery with incomplete set of attrs
  45. self.set_defaults._disable()
  46. def _get_project_config_files(self, filenames=None):
  47. """Ignore ``pyproject.toml``, they are not related to setup_requires"""
  48. try:
  49. cfg, toml = super()._split_standard_project_metadata(filenames)
  50. return cfg, ()
  51. except Exception:
  52. return filenames, ()
  53. def finalize_options(self):
  54. """
  55. Disable finalize_options to avoid building the working set.
  56. Ref #2158.
  57. """
  58. dist = MinimalDistribution(attrs)
  59. # Honor setup.cfg's options.
  60. dist.parse_config_files(ignore_option_errors=True)
  61. if dist.setup_requires:
  62. dist.fetch_build_eggs(dist.setup_requires)
  63. def setup(**attrs):
  64. # Make sure we have any requirements needed to interpret 'attrs'.
  65. logging.configure()
  66. _install_setup_requires(attrs)
  67. return distutils.core.setup(**attrs)
  68. setup.__doc__ = distutils.core.setup.__doc__
  69. _Command = monkey.get_unpatched(distutils.core.Command)
  70. class Command(_Command):
  71. """
  72. Setuptools internal actions are organized using a *command design pattern*.
  73. This means that each action (or group of closely related actions) executed during
  74. the build should be implemented as a ``Command`` subclass.
  75. These commands are abstractions and do not necessarily correspond to a command that
  76. can (or should) be executed via a terminal, in a CLI fashion (although historically
  77. they would).
  78. When creating a new command from scratch, custom defined classes **SHOULD** inherit
  79. from ``setuptools.Command`` and implement a few mandatory methods.
  80. Between these mandatory methods, are listed:
  81. .. method:: initialize_options(self)
  82. Set or (reset) all options/attributes/caches used by the command
  83. to their default values. Note that these values may be overwritten during
  84. the build.
  85. .. method:: finalize_options(self)
  86. Set final values for all options/attributes used by the command.
  87. Most of the time, each option/attribute/cache should only be set if it does not
  88. have any value yet (e.g. ``if self.attr is None: self.attr = val``).
  89. .. method:: run(self)
  90. Execute the actions intended by the command.
  91. (Side effects **SHOULD** only take place when ``run`` is executed,
  92. for example, creating new files or writing to the terminal output).
  93. A useful analogy for command classes is to think of them as subroutines with local
  94. variables called "options". The options are "declared" in ``initialize_options()``
  95. and "defined" (given their final values, aka "finalized") in ``finalize_options()``,
  96. both of which must be defined by every command class. The "body" of the subroutine,
  97. (where it does all the work) is the ``run()`` method.
  98. Between ``initialize_options()`` and ``finalize_options()``, ``setuptools`` may set
  99. the values for options/attributes based on user's input (or circumstance),
  100. which means that the implementation should be careful to not overwrite values in
  101. ``finalize_options`` unless necessary.
  102. Please note that other commands (or other parts of setuptools) may also overwrite
  103. the values of the command's options/attributes multiple times during the build
  104. process.
  105. Therefore it is important to consistently implement ``initialize_options()`` and
  106. ``finalize_options()``. For example, all derived attributes (or attributes that
  107. depend on the value of other attributes) **SHOULD** be recomputed in
  108. ``finalize_options``.
  109. When overwriting existing commands, custom defined classes **MUST** abide by the
  110. same APIs implemented by the original class. They also **SHOULD** inherit from the
  111. original class.
  112. """
  113. command_consumes_arguments = False
  114. def __init__(self, dist, **kw):
  115. """
  116. Construct the command for dist, updating
  117. vars(self) with any keyword parameters.
  118. """
  119. super().__init__(dist)
  120. vars(self).update(kw)
  121. def _ensure_stringlike(self, option, what, default=None):
  122. val = getattr(self, option)
  123. if val is None:
  124. setattr(self, option, default)
  125. return default
  126. elif not isinstance(val, str):
  127. raise DistutilsOptionError(
  128. "'%s' must be a %s (got `%s`)" % (option, what, val)
  129. )
  130. return val
  131. def ensure_string_list(self, option):
  132. r"""Ensure that 'option' is a list of strings. If 'option' is
  133. currently a string, we split it either on /,\s*/ or /\s+/, so
  134. "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become
  135. ["foo", "bar", "baz"].
  136. ..
  137. TODO: This method seems to be similar to the one in ``distutils.cmd``
  138. Probably it is just here for backward compatibility with old Python versions?
  139. :meta private:
  140. """
  141. val = getattr(self, option)
  142. if val is None:
  143. return
  144. elif isinstance(val, str):
  145. setattr(self, option, re.split(r',\s*|\s+', val))
  146. else:
  147. if isinstance(val, list):
  148. ok = all(isinstance(v, str) for v in val)
  149. else:
  150. ok = False
  151. if not ok:
  152. raise DistutilsOptionError(
  153. "'%s' must be a list of strings (got %r)" % (option, val)
  154. )
  155. def reinitialize_command(self, command, reinit_subcommands=0, **kw):
  156. cmd = _Command.reinitialize_command(self, command, reinit_subcommands)
  157. vars(cmd).update(kw)
  158. return cmd
  159. def _find_all_simple(path):
  160. """
  161. Find all files under 'path'
  162. """
  163. results = (
  164. os.path.join(base, file)
  165. for base, dirs, files in os.walk(path, followlinks=True)
  166. for file in files
  167. )
  168. return filter(os.path.isfile, results)
  169. def findall(dir=os.curdir):
  170. """
  171. Find all files under 'dir' and return the list of full filenames.
  172. Unless dir is '.', return full filenames with dir prepended.
  173. """
  174. files = _find_all_simple(dir)
  175. if dir == os.curdir:
  176. make_rel = functools.partial(os.path.relpath, start=dir)
  177. files = map(make_rel, files)
  178. return list(files)
  179. @functools.wraps(_convert_path)
  180. def convert_path(pathname):
  181. from inspect import cleandoc
  182. msg = """
  183. The function `convert_path` is considered internal and not part of the public API.
  184. Its direct usage by 3rd-party packages is considered deprecated and the function
  185. may be removed in the future.
  186. """
  187. warnings.warn(cleandoc(msg), SetuptoolsDeprecationWarning)
  188. return _convert_path(pathname)
  189. class sic(str):
  190. """Treat this string as-is (https://en.wikipedia.org/wiki/Sic)"""
  191. # Apply monkey patches
  192. monkey.patch_all()