__init__.py 7.7 KB

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