filelist.py 13 KB

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