__init__.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. """Extensions to the 'distutils' for large or complex distributions"""
  2. from fnmatch import fnmatchcase
  3. import functools
  4. import os
  5. import re
  6. import _distutils_hack.override # noqa: F401
  7. import distutils.core
  8. from distutils.errors import DistutilsOptionError
  9. from distutils.util import 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 . import monkey
  16. __all__ = [
  17. 'setup', 'Distribution', 'Command', 'Extension', 'Require',
  18. 'SetuptoolsDeprecationWarning',
  19. 'find_packages', 'find_namespace_packages',
  20. ]
  21. __version__ = setuptools.version.__version__
  22. bootstrap_install_from = None
  23. # If we run 2to3 on .py files, should we also convert docstrings?
  24. # Default: yes; assume that we can detect doctests reliably
  25. run_2to3_on_doctests = True
  26. # Standard package names for fixer packages
  27. lib2to3_fixer_packages = ['lib2to3.fixes']
  28. class PackageFinder:
  29. """
  30. Generate a list of all Python packages found within a directory
  31. """
  32. @classmethod
  33. def find(cls, where='.', exclude=(), include=('*',)):
  34. """Return a list all Python packages found within directory 'where'
  35. 'where' is the root directory which will be searched for packages. It
  36. should be supplied as a "cross-platform" (i.e. URL-style) path; it will
  37. be converted to the appropriate local path syntax.
  38. 'exclude' is a sequence of package names to exclude; '*' can be used
  39. as a wildcard in the names, such that 'foo.*' will exclude all
  40. subpackages of 'foo' (but not 'foo' itself).
  41. 'include' is a sequence of package names to include. If it's
  42. specified, only the named packages will be included. If it's not
  43. specified, all found packages will be included. 'include' can contain
  44. shell style wildcard patterns just like 'exclude'.
  45. """
  46. return list(cls._find_packages_iter(
  47. convert_path(where),
  48. cls._build_filter('ez_setup', '*__pycache__', *exclude),
  49. cls._build_filter(*include)))
  50. @classmethod
  51. def _find_packages_iter(cls, where, exclude, include):
  52. """
  53. All the packages found in 'where' that pass the 'include' filter, but
  54. not the 'exclude' filter.
  55. """
  56. for root, dirs, files in os.walk(where, followlinks=True):
  57. # Copy dirs to iterate over it, then empty dirs.
  58. all_dirs = dirs[:]
  59. dirs[:] = []
  60. for dir in all_dirs:
  61. full_path = os.path.join(root, dir)
  62. rel_path = os.path.relpath(full_path, where)
  63. package = rel_path.replace(os.path.sep, '.')
  64. # Skip directory trees that are not valid packages
  65. if ('.' in dir or not cls._looks_like_package(full_path)):
  66. continue
  67. # Should this package be included?
  68. if include(package) and not exclude(package):
  69. yield package
  70. # Keep searching subdirectories, as there may be more packages
  71. # down there, even if the parent was excluded.
  72. dirs.append(dir)
  73. @staticmethod
  74. def _looks_like_package(path):
  75. """Does a directory look like a package?"""
  76. return os.path.isfile(os.path.join(path, '__init__.py'))
  77. @staticmethod
  78. def _build_filter(*patterns):
  79. """
  80. Given a list of patterns, return a callable that will be true only if
  81. the input matches at least one of the patterns.
  82. """
  83. return lambda name: any(fnmatchcase(name, pat=pat) for pat in patterns)
  84. class PEP420PackageFinder(PackageFinder):
  85. @staticmethod
  86. def _looks_like_package(path):
  87. return True
  88. find_packages = PackageFinder.find
  89. find_namespace_packages = PEP420PackageFinder.find
  90. def _install_setup_requires(attrs):
  91. # Note: do not use `setuptools.Distribution` directly, as
  92. # our PEP 517 backend patch `distutils.core.Distribution`.
  93. class MinimalDistribution(distutils.core.Distribution):
  94. """
  95. A minimal version of a distribution for supporting the
  96. fetch_build_eggs interface.
  97. """
  98. def __init__(self, attrs):
  99. _incl = 'dependency_links', 'setup_requires'
  100. filtered = {
  101. k: attrs[k]
  102. for k in set(_incl) & set(attrs)
  103. }
  104. distutils.core.Distribution.__init__(self, filtered)
  105. def finalize_options(self):
  106. """
  107. Disable finalize_options to avoid building the working set.
  108. Ref #2158.
  109. """
  110. dist = MinimalDistribution(attrs)
  111. # Honor setup.cfg's options.
  112. dist.parse_config_files(ignore_option_errors=True)
  113. if dist.setup_requires:
  114. dist.fetch_build_eggs(dist.setup_requires)
  115. def setup(**attrs):
  116. # Make sure we have any requirements needed to interpret 'attrs'.
  117. _install_setup_requires(attrs)
  118. return distutils.core.setup(**attrs)
  119. setup.__doc__ = distutils.core.setup.__doc__
  120. _Command = monkey.get_unpatched(distutils.core.Command)
  121. class Command(_Command):
  122. __doc__ = _Command.__doc__
  123. command_consumes_arguments = False
  124. def __init__(self, dist, **kw):
  125. """
  126. Construct the command for dist, updating
  127. vars(self) with any keyword parameters.
  128. """
  129. _Command.__init__(self, dist)
  130. vars(self).update(kw)
  131. def _ensure_stringlike(self, option, what, default=None):
  132. val = getattr(self, option)
  133. if val is None:
  134. setattr(self, option, default)
  135. return default
  136. elif not isinstance(val, str):
  137. raise DistutilsOptionError("'%s' must be a %s (got `%s`)"
  138. % (option, what, val))
  139. return val
  140. def ensure_string_list(self, option):
  141. r"""Ensure that 'option' is a list of strings. If 'option' is
  142. currently a string, we split it either on /,\s*/ or /\s+/, so
  143. "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become
  144. ["foo", "bar", "baz"].
  145. """
  146. val = getattr(self, option)
  147. if val is None:
  148. return
  149. elif isinstance(val, str):
  150. setattr(self, option, re.split(r',\s*|\s+', val))
  151. else:
  152. if isinstance(val, list):
  153. ok = all(isinstance(v, str) for v in val)
  154. else:
  155. ok = False
  156. if not ok:
  157. raise DistutilsOptionError(
  158. "'%s' must be a list of strings (got %r)"
  159. % (option, val))
  160. def reinitialize_command(self, command, reinit_subcommands=0, **kw):
  161. cmd = _Command.reinitialize_command(self, command, reinit_subcommands)
  162. vars(cmd).update(kw)
  163. return cmd
  164. def _find_all_simple(path):
  165. """
  166. Find all files under 'path'
  167. """
  168. results = (
  169. os.path.join(base, file)
  170. for base, dirs, files in os.walk(path, followlinks=True)
  171. for file in files
  172. )
  173. return filter(os.path.isfile, results)
  174. def findall(dir=os.curdir):
  175. """
  176. Find all files under 'dir' and return the list of full filenames.
  177. Unless dir is '.', return full filenames with dir prepended.
  178. """
  179. files = _find_all_simple(dir)
  180. if dir == os.curdir:
  181. make_rel = functools.partial(os.path.relpath, start=dir)
  182. files = map(make_rel, files)
  183. return list(files)
  184. class sic(str):
  185. """Treat this string as-is (https://en.wikipedia.org/wiki/Sic)"""
  186. # Apply monkey patches
  187. monkey.patch_all()