__init__.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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. dist = distutils.core.Distribution(dict(
  101. (k, v) for k, v in attrs.items()
  102. if k in ('dependency_links', 'setup_requires')
  103. ))
  104. # Honor setup.cfg's options.
  105. dist.parse_config_files(ignore_option_errors=True)
  106. if dist.setup_requires:
  107. dist.fetch_build_eggs(dist.setup_requires)
  108. def setup(**attrs):
  109. # Make sure we have any requirements needed to interpret 'attrs'.
  110. _install_setup_requires(attrs)
  111. return distutils.core.setup(**attrs)
  112. setup.__doc__ = distutils.core.setup.__doc__
  113. _Command = monkey.get_unpatched(distutils.core.Command)
  114. class Command(_Command):
  115. __doc__ = _Command.__doc__
  116. command_consumes_arguments = False
  117. def __init__(self, dist, **kw):
  118. """
  119. Construct the command for dist, updating
  120. vars(self) with any keyword parameters.
  121. """
  122. _Command.__init__(self, dist)
  123. vars(self).update(kw)
  124. def _ensure_stringlike(self, option, what, default=None):
  125. val = getattr(self, option)
  126. if val is None:
  127. setattr(self, option, default)
  128. return default
  129. elif not isinstance(val, string_types):
  130. raise DistutilsOptionError("'%s' must be a %s (got `%s`)"
  131. % (option, what, val))
  132. return val
  133. def ensure_string_list(self, option):
  134. r"""Ensure that 'option' is a list of strings. If 'option' is
  135. currently a string, we split it either on /,\s*/ or /\s+/, so
  136. "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become
  137. ["foo", "bar", "baz"].
  138. """
  139. val = getattr(self, option)
  140. if val is None:
  141. return
  142. elif isinstance(val, string_types):
  143. setattr(self, option, re.split(r',\s*|\s+', val))
  144. else:
  145. if isinstance(val, list):
  146. ok = all(isinstance(v, string_types) for v in val)
  147. else:
  148. ok = False
  149. if not ok:
  150. raise DistutilsOptionError(
  151. "'%s' must be a list of strings (got %r)"
  152. % (option, val))
  153. def reinitialize_command(self, command, reinit_subcommands=0, **kw):
  154. cmd = _Command.reinitialize_command(self, command, reinit_subcommands)
  155. vars(cmd).update(kw)
  156. return cmd
  157. def _find_all_simple(path):
  158. """
  159. Find all files under 'path'
  160. """
  161. results = (
  162. os.path.join(base, file)
  163. for base, dirs, files in os.walk(path, followlinks=True)
  164. for file in files
  165. )
  166. return filter(os.path.isfile, results)
  167. def findall(dir=os.curdir):
  168. """
  169. Find all files under 'dir' and return the list of full filenames.
  170. Unless dir is '.', return full filenames with dir prepended.
  171. """
  172. files = _find_all_simple(dir)
  173. if dir == os.curdir:
  174. make_rel = functools.partial(os.path.relpath, start=dir)
  175. files = map(make_rel, files)
  176. return list(files)
  177. # Apply monkey patches
  178. monkey.patch_all()