filelist.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. """distutils.filelist
  2. Provides the FileList class, used for poking about the filesystem
  3. and building lists of files.
  4. """
  5. import os, re
  6. import fnmatch
  7. import functools
  8. from distutils.util import convert_path
  9. from distutils.errors import DistutilsTemplateError, DistutilsInternalError
  10. from distutils import log
  11. class FileList:
  12. """A list of files built by on exploring the filesystem and filtered by
  13. applying various patterns to what we find there.
  14. Instance attributes:
  15. dir
  16. directory from which files will be taken -- only used if
  17. 'allfiles' not supplied to constructor
  18. files
  19. list of filenames currently being built/filtered/manipulated
  20. allfiles
  21. complete list of files under consideration (ie. without any
  22. filtering applied)
  23. """
  24. def __init__(self, warn=None, debug_print=None):
  25. # ignore argument to FileList, but keep them for backwards
  26. # compatibility
  27. self.allfiles = None
  28. self.files = []
  29. def set_allfiles(self, allfiles):
  30. self.allfiles = allfiles
  31. def findall(self, dir=os.curdir):
  32. self.allfiles = findall(dir)
  33. def debug_print(self, msg):
  34. """Print 'msg' to stdout if the global DEBUG (taken from the
  35. DISTUTILS_DEBUG environment variable) flag is true.
  36. """
  37. from distutils.debug import DEBUG
  38. if DEBUG:
  39. print(msg)
  40. # -- List-like methods ---------------------------------------------
  41. def append(self, item):
  42. self.files.append(item)
  43. def extend(self, items):
  44. self.files.extend(items)
  45. def sort(self):
  46. # Not a strict lexical sort!
  47. sortable_files = sorted(map(os.path.split, self.files))
  48. self.files = []
  49. for sort_tuple in sortable_files:
  50. self.files.append(os.path.join(*sort_tuple))
  51. # -- Other miscellaneous utility methods ---------------------------
  52. def remove_duplicates(self):
  53. # Assumes list has been sorted!
  54. for i in range(len(self.files) - 1, 0, -1):
  55. if self.files[i] == self.files[i - 1]:
  56. del self.files[i]
  57. # -- "File template" methods ---------------------------------------
  58. def _parse_template_line(self, line):
  59. words = line.split()
  60. action = words[0]
  61. patterns = dir = dir_pattern = None
  62. if action in ('include', 'exclude',
  63. 'global-include', 'global-exclude'):
  64. if len(words) < 2:
  65. raise DistutilsTemplateError(
  66. "'%s' expects <pattern1> <pattern2> ..." % action)
  67. patterns = [convert_path(w) for w in words[1:]]
  68. elif action in ('recursive-include', 'recursive-exclude'):
  69. if len(words) < 3:
  70. raise DistutilsTemplateError(
  71. "'%s' expects <dir> <pattern1> <pattern2> ..." % action)
  72. dir = convert_path(words[1])
  73. patterns = [convert_path(w) for w in words[2:]]
  74. elif action in ('graft', 'prune'):
  75. if len(words) != 2:
  76. raise DistutilsTemplateError(
  77. "'%s' expects a single <dir_pattern>" % action)
  78. dir_pattern = convert_path(words[1])
  79. else:
  80. raise DistutilsTemplateError("unknown action '%s'" % action)
  81. return (action, patterns, dir, dir_pattern)
  82. def process_template_line(self, line):
  83. # Parse the line: split it up, make sure the right number of words
  84. # is there, and return the relevant words. 'action' is always
  85. # defined: it's the first word of the line. Which of the other
  86. # three are defined depends on the action; it'll be either
  87. # patterns, (dir and patterns), or (dir_pattern).
  88. (action, patterns, dir, dir_pattern) = self._parse_template_line(line)
  89. # OK, now we know that the action is valid and we have the
  90. # right number of words on the line for that action -- so we
  91. # can proceed with minimal error-checking.
  92. if action == 'include':
  93. self.debug_print("include " + ' '.join(patterns))
  94. for pattern in patterns:
  95. if not self.include_pattern(pattern, anchor=1):
  96. log.warn("warning: no files found matching '%s'",
  97. pattern)
  98. elif action == 'exclude':
  99. self.debug_print("exclude " + ' '.join(patterns))
  100. for pattern in patterns:
  101. if not self.exclude_pattern(pattern, anchor=1):
  102. log.warn(("warning: no previously-included files "
  103. "found matching '%s'"), pattern)
  104. elif action == 'global-include':
  105. self.debug_print("global-include " + ' '.join(patterns))
  106. for pattern in patterns:
  107. if not self.include_pattern(pattern, anchor=0):
  108. log.warn(("warning: no files found matching '%s' "
  109. "anywhere in distribution"), pattern)
  110. elif action == 'global-exclude':
  111. self.debug_print("global-exclude " + ' '.join(patterns))
  112. for pattern in patterns:
  113. if not self.exclude_pattern(pattern, anchor=0):
  114. log.warn(("warning: no previously-included files matching "
  115. "'%s' found anywhere in distribution"),
  116. pattern)
  117. elif action == 'recursive-include':
  118. self.debug_print("recursive-include %s %s" %
  119. (dir, ' '.join(patterns)))
  120. for pattern in patterns:
  121. if not self.include_pattern(pattern, prefix=dir):
  122. log.warn(("warning: no files found matching '%s' "
  123. "under directory '%s'"),
  124. pattern, dir)
  125. elif action == 'recursive-exclude':
  126. self.debug_print("recursive-exclude %s %s" %
  127. (dir, ' '.join(patterns)))
  128. for pattern in patterns:
  129. if not self.exclude_pattern(pattern, prefix=dir):
  130. log.warn(("warning: no previously-included files matching "
  131. "'%s' found under directory '%s'"),
  132. pattern, dir)
  133. elif action == 'graft':
  134. self.debug_print("graft " + dir_pattern)
  135. if not self.include_pattern(None, prefix=dir_pattern):
  136. log.warn("warning: no directories found matching '%s'",
  137. dir_pattern)
  138. elif action == 'prune':
  139. self.debug_print("prune " + dir_pattern)
  140. if not self.exclude_pattern(None, prefix=dir_pattern):
  141. log.warn(("no previously-included directories found "
  142. "matching '%s'"), dir_pattern)
  143. else:
  144. raise DistutilsInternalError(
  145. "this cannot happen: invalid action '%s'" % action)
  146. # -- Filtering/selection methods -----------------------------------
  147. def include_pattern(self, pattern, anchor=1, prefix=None, is_regex=0):
  148. """Select strings (presumably filenames) from 'self.files' that
  149. match 'pattern', a Unix-style wildcard (glob) pattern. Patterns
  150. are not quite the same as implemented by the 'fnmatch' module: '*'
  151. and '?' match non-special characters, where "special" is platform-
  152. dependent: slash on Unix; colon, slash, and backslash on
  153. DOS/Windows; and colon on Mac OS.
  154. If 'anchor' is true (the default), then the pattern match is more
  155. stringent: "*.py" will match "foo.py" but not "foo/bar.py". If
  156. 'anchor' is false, both of these will match.
  157. If 'prefix' is supplied, then only filenames starting with 'prefix'
  158. (itself a pattern) and ending with 'pattern', with anything in between
  159. them, will match. 'anchor' is ignored in this case.
  160. If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and
  161. 'pattern' is assumed to be either a string containing a regex or a
  162. regex object -- no translation is done, the regex is just compiled
  163. and used as-is.
  164. Selected strings will be added to self.files.
  165. Return True if files are found, False otherwise.
  166. """
  167. # XXX docstring lying about what the special chars are?
  168. files_found = False
  169. pattern_re = translate_pattern(pattern, anchor, prefix, is_regex)
  170. self.debug_print("include_pattern: applying regex r'%s'" %
  171. pattern_re.pattern)
  172. # delayed loading of allfiles list
  173. if self.allfiles is None:
  174. self.findall()
  175. for name in self.allfiles:
  176. if pattern_re.search(name):
  177. self.debug_print(" adding " + name)
  178. self.files.append(name)
  179. files_found = True
  180. return files_found
  181. def exclude_pattern (self, pattern,
  182. anchor=1, prefix=None, is_regex=0):
  183. """Remove strings (presumably filenames) from 'files' that match
  184. 'pattern'. Other parameters are the same as for
  185. 'include_pattern()', above.
  186. The list 'self.files' is modified in place.
  187. Return True if files are found, False otherwise.
  188. """
  189. files_found = False
  190. pattern_re = translate_pattern(pattern, anchor, prefix, is_regex)
  191. self.debug_print("exclude_pattern: applying regex r'%s'" %
  192. pattern_re.pattern)
  193. for i in range(len(self.files)-1, -1, -1):
  194. if pattern_re.search(self.files[i]):
  195. self.debug_print(" removing " + self.files[i])
  196. del self.files[i]
  197. files_found = True
  198. return files_found
  199. # ----------------------------------------------------------------------
  200. # Utility functions
  201. def _find_all_simple(path):
  202. """
  203. Find all files under 'path'
  204. """
  205. results = (
  206. os.path.join(base, file)
  207. for base, dirs, files in os.walk(path, followlinks=True)
  208. for file in files
  209. )
  210. return filter(os.path.isfile, results)
  211. def findall(dir=os.curdir):
  212. """
  213. Find all files under 'dir' and return the list of full filenames.
  214. Unless dir is '.', return full filenames with dir prepended.
  215. """
  216. files = _find_all_simple(dir)
  217. if dir == os.curdir:
  218. make_rel = functools.partial(os.path.relpath, start=dir)
  219. files = map(make_rel, files)
  220. return list(files)
  221. def glob_to_re(pattern):
  222. """Translate a shell-like glob pattern to a regular expression; return
  223. a string containing the regex. Differs from 'fnmatch.translate()' in
  224. that '*' does not match "special characters" (which are
  225. platform-specific).
  226. """
  227. pattern_re = fnmatch.translate(pattern)
  228. # '?' and '*' in the glob pattern become '.' and '.*' in the RE, which
  229. # IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix,
  230. # and by extension they shouldn't match such "special characters" under
  231. # any OS. So change all non-escaped dots in the RE to match any
  232. # character except the special characters (currently: just os.sep).
  233. sep = os.sep
  234. if os.sep == '\\':
  235. # we're using a regex to manipulate a regex, so we need
  236. # to escape the backslash twice
  237. sep = r'\\\\'
  238. escaped = r'\1[^%s]' % sep
  239. pattern_re = re.sub(r'((?<!\\)(\\\\)*)\.', escaped, pattern_re)
  240. return pattern_re
  241. def translate_pattern(pattern, anchor=1, prefix=None, is_regex=0):
  242. """Translate a shell-like wildcard pattern to a compiled regular
  243. expression. Return the compiled regex. If 'is_regex' true,
  244. then 'pattern' is directly compiled to a regex (if it's a string)
  245. or just returned as-is (assumes it's a regex object).
  246. """
  247. if is_regex:
  248. if isinstance(pattern, str):
  249. return re.compile(pattern)
  250. else:
  251. return pattern
  252. # ditch start and end characters
  253. start, _, end = glob_to_re('_').partition('_')
  254. if pattern:
  255. pattern_re = glob_to_re(pattern)
  256. assert pattern_re.startswith(start) and pattern_re.endswith(end)
  257. else:
  258. pattern_re = ''
  259. if prefix is not None:
  260. prefix_re = glob_to_re(prefix)
  261. assert prefix_re.startswith(start) and prefix_re.endswith(end)
  262. prefix_re = prefix_re[len(start): len(prefix_re) - len(end)]
  263. sep = os.sep
  264. if os.sep == '\\':
  265. sep = r'\\'
  266. pattern_re = pattern_re[len(start): len(pattern_re) - len(end)]
  267. pattern_re = r'%s\A%s%s.*%s%s' % (start, prefix_re, sep, pattern_re, end)
  268. else: # no prefix -- respect anchor flag
  269. if anchor:
  270. pattern_re = r'%s\A%s' % (start, pattern_re[len(start):])
  271. return re.compile(pattern_re)