__init__.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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',
  18. 'Distribution',
  19. 'Command',
  20. 'Extension',
  21. 'Require',
  22. 'SetuptoolsDeprecationWarning',
  23. 'find_packages',
  24. 'find_namespace_packages',
  25. ]
  26. __version__ = setuptools.version.__version__
  27. bootstrap_install_from = None
  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(
  47. cls._find_packages_iter(
  48. convert_path(where),
  49. cls._build_filter('ez_setup', '*__pycache__', *exclude),
  50. cls._build_filter(*include),
  51. )
  52. )
  53. @classmethod
  54. def _find_packages_iter(cls, where, exclude, include):
  55. """
  56. All the packages found in 'where' that pass the 'include' filter, but
  57. not the 'exclude' filter.
  58. """
  59. for root, dirs, files in os.walk(where, followlinks=True):
  60. # Copy dirs to iterate over it, then empty dirs.
  61. all_dirs = dirs[:]
  62. dirs[:] = []
  63. for dir in all_dirs:
  64. full_path = os.path.join(root, dir)
  65. rel_path = os.path.relpath(full_path, where)
  66. package = rel_path.replace(os.path.sep, '.')
  67. # Skip directory trees that are not valid packages
  68. if '.' in dir or not cls._looks_like_package(full_path):
  69. continue
  70. # Should this package be included?
  71. if include(package) and not exclude(package):
  72. yield package
  73. # Keep searching subdirectories, as there may be more packages
  74. # down there, even if the parent was excluded.
  75. dirs.append(dir)
  76. @staticmethod
  77. def _looks_like_package(path):
  78. """Does a directory look like a package?"""
  79. return os.path.isfile(os.path.join(path, '__init__.py'))
  80. @staticmethod
  81. def _build_filter(*patterns):
  82. """
  83. Given a list of patterns, return a callable that will be true only if
  84. the input matches at least one of the patterns.
  85. """
  86. return lambda name: any(fnmatchcase(name, pat=pat) for pat in patterns)
  87. class PEP420PackageFinder(PackageFinder):
  88. @staticmethod
  89. def _looks_like_package(path):
  90. return True
  91. find_packages = PackageFinder.find
  92. find_namespace_packages = PEP420PackageFinder.find
  93. def _install_setup_requires(attrs):
  94. # Note: do not use `setuptools.Distribution` directly, as
  95. # our PEP 517 backend patch `distutils.core.Distribution`.
  96. class MinimalDistribution(distutils.core.Distribution):
  97. """
  98. A minimal version of a distribution for supporting the
  99. fetch_build_eggs interface.
  100. """
  101. def __init__(self, attrs):
  102. _incl = 'dependency_links', 'setup_requires'
  103. filtered = {k: attrs[k] for k in set(_incl) & set(attrs)}
  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(
  138. "'%s' must be a %s (got `%s`)" % (option, what, val)
  139. )
  140. return val
  141. def ensure_string_list(self, option):
  142. r"""Ensure that 'option' is a list of strings. If 'option' is
  143. currently a string, we split it either on /,\s*/ or /\s+/, so
  144. "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become
  145. ["foo", "bar", "baz"].
  146. """
  147. val = getattr(self, option)
  148. if val is None:
  149. return
  150. elif isinstance(val, str):
  151. setattr(self, option, re.split(r',\s*|\s+', val))
  152. else:
  153. if isinstance(val, list):
  154. ok = all(isinstance(v, str) for v in val)
  155. else:
  156. ok = False
  157. if not ok:
  158. raise DistutilsOptionError(
  159. "'%s' must be a list of strings (got %r)" % (option, val)
  160. )
  161. def reinitialize_command(self, command, reinit_subcommands=0, **kw):
  162. cmd = _Command.reinitialize_command(self, command, reinit_subcommands)
  163. vars(cmd).update(kw)
  164. return cmd
  165. def _find_all_simple(path):
  166. """
  167. Find all files under 'path'
  168. """
  169. results = (
  170. os.path.join(base, file)
  171. for base, dirs, files in os.walk(path, followlinks=True)
  172. for file in files
  173. )
  174. return filter(os.path.isfile, results)
  175. def findall(dir=os.curdir):
  176. """
  177. Find all files under 'dir' and return the list of full filenames.
  178. Unless dir is '.', return full filenames with dir prepended.
  179. """
  180. files = _find_all_simple(dir)
  181. if dir == os.curdir:
  182. make_rel = functools.partial(os.path.relpath, start=dir)
  183. files = map(make_rel, files)
  184. return list(files)
  185. class sic(str):
  186. """Treat this string as-is (https://en.wikipedia.org/wiki/Sic)"""
  187. # Apply monkey patches
  188. monkey.patch_all()