manifest.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012-2013 Python Software Foundation.
  4. # See LICENSE.txt and CONTRIBUTORS.txt.
  5. #
  6. """
  7. Class representing the list of files in a distribution.
  8. Equivalent to distutils.filelist, but fixes some problems.
  9. """
  10. import fnmatch
  11. import logging
  12. import os
  13. import re
  14. from . import DistlibException
  15. from .compat import fsdecode
  16. from .util import convert_path
  17. __all__ = ['Manifest']
  18. logger = logging.getLogger(__name__)
  19. # a \ followed by some spaces + EOL
  20. _COLLAPSE_PATTERN = re.compile('\\\w*\n', re.M)
  21. _COMMENTED_LINE = re.compile('#.*?(?=\n)|\n(?=$)', re.M | re.S)
  22. class Manifest(object):
  23. """A list of files built by on exploring the filesystem and filtered by
  24. applying various patterns to what we find there.
  25. """
  26. def __init__(self, base=None):
  27. """
  28. Initialise an instance.
  29. :param base: The base directory to explore under.
  30. """
  31. self.base = os.path.abspath(os.path.normpath(base or os.getcwd()))
  32. self.prefix = self.base + os.sep
  33. self.allfiles = None
  34. self.files = set()
  35. #
  36. # Public API
  37. #
  38. def findall(self):
  39. """Find all files under the base and set ``allfiles`` to the absolute
  40. pathnames of files found.
  41. """
  42. from stat import S_ISREG, S_ISDIR, S_ISLNK
  43. self.allfiles = allfiles = []
  44. root = self.base
  45. stack = [root]
  46. pop = stack.pop
  47. push = stack.append
  48. while stack:
  49. root = pop()
  50. names = os.listdir(root)
  51. for name in names:
  52. fullname = os.path.join(root, name)
  53. # Avoid excess stat calls -- just one will do, thank you!
  54. stat = os.stat(fullname)
  55. mode = stat.st_mode
  56. if S_ISREG(mode):
  57. allfiles.append(fsdecode(fullname))
  58. elif S_ISDIR(mode) and not S_ISLNK(mode):
  59. push(fullname)
  60. def add(self, item):
  61. """
  62. Add a file to the manifest.
  63. :param item: The pathname to add. This can be relative to the base.
  64. """
  65. if not item.startswith(self.prefix):
  66. item = os.path.join(self.base, item)
  67. self.files.add(os.path.normpath(item))
  68. def add_many(self, items):
  69. """
  70. Add a list of files to the manifest.
  71. :param items: The pathnames to add. These can be relative to the base.
  72. """
  73. for item in items:
  74. self.add(item)
  75. def sorted(self, wantdirs=False):
  76. """
  77. Return sorted files in directory order
  78. """
  79. def add_dir(dirs, d):
  80. dirs.add(d)
  81. logger.debug('add_dir added %s', d)
  82. if d != self.base:
  83. parent, _ = os.path.split(d)
  84. assert parent not in ('', '/')
  85. add_dir(dirs, parent)
  86. result = set(self.files) # make a copy!
  87. if wantdirs:
  88. dirs = set()
  89. for f in result:
  90. add_dir(dirs, os.path.dirname(f))
  91. result |= dirs
  92. return [os.path.join(*path_tuple) for path_tuple in
  93. sorted(os.path.split(path) for path in result)]
  94. def clear(self):
  95. """Clear all collected files."""
  96. self.files = set()
  97. self.allfiles = []
  98. def process_directive(self, directive):
  99. """
  100. Process a directive which either adds some files from ``allfiles`` to
  101. ``files``, or removes some files from ``files``.
  102. :param directive: The directive to process. This should be in a format
  103. compatible with distutils ``MANIFEST.in`` files:
  104. http://docs.python.org/distutils/sourcedist.html#commands
  105. """
  106. # Parse the line: split it up, make sure the right number of words
  107. # is there, and return the relevant words. 'action' is always
  108. # defined: it's the first word of the line. Which of the other
  109. # three are defined depends on the action; it'll be either
  110. # patterns, (dir and patterns), or (dirpattern).
  111. action, patterns, thedir, dirpattern = self._parse_directive(directive)
  112. # OK, now we know that the action is valid and we have the
  113. # right number of words on the line for that action -- so we
  114. # can proceed with minimal error-checking.
  115. if action == 'include':
  116. for pattern in patterns:
  117. if not self._include_pattern(pattern, anchor=True):
  118. logger.warning('no files found matching %r', pattern)
  119. elif action == 'exclude':
  120. for pattern in patterns:
  121. found = self._exclude_pattern(pattern, anchor=True)
  122. #if not found:
  123. # logger.warning('no previously-included files '
  124. # 'found matching %r', pattern)
  125. elif action == 'global-include':
  126. for pattern in patterns:
  127. if not self._include_pattern(pattern, anchor=False):
  128. logger.warning('no files found matching %r '
  129. 'anywhere in distribution', pattern)
  130. elif action == 'global-exclude':
  131. for pattern in patterns:
  132. found = self._exclude_pattern(pattern, anchor=False)
  133. #if not found:
  134. # logger.warning('no previously-included files '
  135. # 'matching %r found anywhere in '
  136. # 'distribution', pattern)
  137. elif action == 'recursive-include':
  138. for pattern in patterns:
  139. if not self._include_pattern(pattern, prefix=thedir):
  140. logger.warning('no files found matching %r '
  141. 'under directory %r', pattern, thedir)
  142. elif action == 'recursive-exclude':
  143. for pattern in patterns:
  144. found = self._exclude_pattern(pattern, prefix=thedir)
  145. #if not found:
  146. # logger.warning('no previously-included files '
  147. # 'matching %r found under directory %r',
  148. # pattern, thedir)
  149. elif action == 'graft':
  150. if not self._include_pattern(None, prefix=dirpattern):
  151. logger.warning('no directories found matching %r',
  152. dirpattern)
  153. elif action == 'prune':
  154. if not self._exclude_pattern(None, prefix=dirpattern):
  155. logger.warning('no previously-included directories found '
  156. 'matching %r', dirpattern)
  157. else: # pragma: no cover
  158. # This should never happen, as it should be caught in
  159. # _parse_template_line
  160. raise DistlibException(
  161. 'invalid action %r' % action)
  162. #
  163. # Private API
  164. #
  165. def _parse_directive(self, directive):
  166. """
  167. Validate a directive.
  168. :param directive: The directive to validate.
  169. :return: A tuple of action, patterns, thedir, dir_patterns
  170. """
  171. words = directive.split()
  172. if len(words) == 1 and words[0] not in ('include', 'exclude',
  173. 'global-include',
  174. 'global-exclude',
  175. 'recursive-include',
  176. 'recursive-exclude',
  177. 'graft', 'prune'):
  178. # no action given, let's use the default 'include'
  179. words.insert(0, 'include')
  180. action = words[0]
  181. patterns = thedir = dir_pattern = None
  182. if action in ('include', 'exclude',
  183. 'global-include', 'global-exclude'):
  184. if len(words) < 2:
  185. raise DistlibException(
  186. '%r expects <pattern1> <pattern2> ...' % action)
  187. patterns = [convert_path(word) for word in words[1:]]
  188. elif action in ('recursive-include', 'recursive-exclude'):
  189. if len(words) < 3:
  190. raise DistlibException(
  191. '%r expects <dir> <pattern1> <pattern2> ...' % action)
  192. thedir = convert_path(words[1])
  193. patterns = [convert_path(word) for word in words[2:]]
  194. elif action in ('graft', 'prune'):
  195. if len(words) != 2:
  196. raise DistlibException(
  197. '%r expects a single <dir_pattern>' % action)
  198. dir_pattern = convert_path(words[1])
  199. else:
  200. raise DistlibException('unknown action %r' % action)
  201. return action, patterns, thedir, dir_pattern
  202. def _include_pattern(self, pattern, anchor=True, prefix=None,
  203. is_regex=False):
  204. """Select strings (presumably filenames) from 'self.files' that
  205. match 'pattern', a Unix-style wildcard (glob) pattern.
  206. Patterns are not quite the same as implemented by the 'fnmatch'
  207. module: '*' and '?' match non-special characters, where "special"
  208. is platform-dependent: slash on Unix; colon, slash, and backslash on
  209. DOS/Windows; and colon on Mac OS.
  210. If 'anchor' is true (the default), then the pattern match is more
  211. stringent: "*.py" will match "foo.py" but not "foo/bar.py". If
  212. 'anchor' is false, both of these will match.
  213. If 'prefix' is supplied, then only filenames starting with 'prefix'
  214. (itself a pattern) and ending with 'pattern', with anything in between
  215. them, will match. 'anchor' is ignored in this case.
  216. If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and
  217. 'pattern' is assumed to be either a string containing a regex or a
  218. regex object -- no translation is done, the regex is just compiled
  219. and used as-is.
  220. Selected strings will be added to self.files.
  221. Return True if files are found.
  222. """
  223. # XXX docstring lying about what the special chars are?
  224. found = False
  225. pattern_re = self._translate_pattern(pattern, anchor, prefix, is_regex)
  226. # delayed loading of allfiles list
  227. if self.allfiles is None:
  228. self.findall()
  229. for name in self.allfiles:
  230. if pattern_re.search(name):
  231. self.files.add(name)
  232. found = True
  233. return found
  234. def _exclude_pattern(self, pattern, anchor=True, prefix=None,
  235. is_regex=False):
  236. """Remove strings (presumably filenames) from 'files' that match
  237. 'pattern'.
  238. Other parameters are the same as for 'include_pattern()', above.
  239. The list 'self.files' is modified in place. Return True if files are
  240. found.
  241. This API is public to allow e.g. exclusion of SCM subdirs, e.g. when
  242. packaging source distributions
  243. """
  244. found = False
  245. pattern_re = self._translate_pattern(pattern, anchor, prefix, is_regex)
  246. for f in list(self.files):
  247. if pattern_re.search(f):
  248. self.files.remove(f)
  249. found = True
  250. return found
  251. def _translate_pattern(self, pattern, anchor=True, prefix=None,
  252. is_regex=False):
  253. """Translate a shell-like wildcard pattern to a compiled regular
  254. expression.
  255. Return the compiled regex. If 'is_regex' true,
  256. then 'pattern' is directly compiled to a regex (if it's a string)
  257. or just returned as-is (assumes it's a regex object).
  258. """
  259. if is_regex:
  260. if isinstance(pattern, str):
  261. return re.compile(pattern)
  262. else:
  263. return pattern
  264. if pattern:
  265. pattern_re = self._glob_to_re(pattern)
  266. else:
  267. pattern_re = ''
  268. base = re.escape(os.path.join(self.base, ''))
  269. if prefix is not None:
  270. # ditch end of pattern character
  271. empty_pattern = self._glob_to_re('')
  272. prefix_re = self._glob_to_re(prefix)[:-len(empty_pattern)]
  273. sep = os.sep
  274. if os.sep == '\\':
  275. sep = r'\\'
  276. pattern_re = '^' + base + sep.join((prefix_re,
  277. '.*' + pattern_re))
  278. else: # no prefix -- respect anchor flag
  279. if anchor:
  280. pattern_re = '^' + base + pattern_re
  281. return re.compile(pattern_re)
  282. def _glob_to_re(self, pattern):
  283. """Translate a shell-like glob pattern to a regular expression.
  284. Return a string containing the regex. Differs from
  285. 'fnmatch.translate()' in that '*' does not match "special characters"
  286. (which are platform-specific).
  287. """
  288. pattern_re = fnmatch.translate(pattern)
  289. # '?' and '*' in the glob pattern become '.' and '.*' in the RE, which
  290. # IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix,
  291. # and by extension they shouldn't match such "special characters" under
  292. # any OS. So change all non-escaped dots in the RE to match any
  293. # character except the special characters (currently: just os.sep).
  294. sep = os.sep
  295. if os.sep == '\\':
  296. # we're using a regex to manipulate a regex, so we need
  297. # to escape the backslash twice
  298. sep = r'\\\\'
  299. escaped = r'\1[^%s]' % sep
  300. pattern_re = re.sub(r'((?<!\\)(\\\\)*)\.', escaped, pattern_re)
  301. return pattern_re