__init__.py 7.6 KB

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