filelist.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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', 'global-include', 'global-exclude'):
  64. if len(words) < 2:
  65. raise DistutilsTemplateError(
  66. "'%s' expects <pattern1> <pattern2> ..." % action
  67. )
  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. )
  74. dir = convert_path(words[1])
  75. patterns = [convert_path(w) for w in words[2:]]
  76. elif action in ('graft', 'prune'):
  77. if len(words) != 2:
  78. raise DistutilsTemplateError(
  79. "'%s' expects a single <dir_pattern>" % action
  80. )
  81. dir_pattern = convert_path(words[1])
  82. else:
  83. raise DistutilsTemplateError("unknown action '%s'" % action)
  84. return (action, patterns, dir, dir_pattern)
  85. def process_template_line(self, line): # noqa: C901
  86. # Parse the line: split it up, make sure the right number of words
  87. # is there, and return the relevant words. 'action' is always
  88. # defined: it's the first word of the line. Which of the other
  89. # three are defined depends on the action; it'll be either
  90. # patterns, (dir and patterns), or (dir_pattern).
  91. (action, patterns, dir, dir_pattern) = self._parse_template_line(line)
  92. # OK, now we know that the action is valid and we have the
  93. # right number of words on the line for that action -- so we
  94. # can proceed with minimal error-checking.
  95. if action == 'include':
  96. self.debug_print("include " + ' '.join(patterns))
  97. for pattern in patterns:
  98. if not self.include_pattern(pattern, anchor=1):
  99. log.warn("warning: no files found matching '%s'", pattern)
  100. elif action == 'exclude':
  101. self.debug_print("exclude " + ' '.join(patterns))
  102. for pattern in patterns:
  103. if not self.exclude_pattern(pattern, anchor=1):
  104. log.warn(
  105. (
  106. "warning: no previously-included files "
  107. "found matching '%s'"
  108. ),
  109. pattern,
  110. )
  111. elif action == 'global-include':
  112. self.debug_print("global-include " + ' '.join(patterns))
  113. for pattern in patterns:
  114. if not self.include_pattern(pattern, anchor=0):
  115. log.warn(
  116. (
  117. "warning: no files found matching '%s' "
  118. "anywhere in distribution"
  119. ),
  120. pattern,
  121. )
  122. elif action == 'global-exclude':
  123. self.debug_print("global-exclude " + ' '.join(patterns))
  124. for pattern in patterns:
  125. if not self.exclude_pattern(pattern, anchor=0):
  126. log.warn(
  127. (
  128. "warning: no previously-included files matching "
  129. "'%s' found anywhere in distribution"
  130. ),
  131. pattern,
  132. )
  133. elif action == 'recursive-include':
  134. self.debug_print("recursive-include {} {}".format(dir, ' '.join(patterns)))
  135. for pattern in patterns:
  136. if not self.include_pattern(pattern, prefix=dir):
  137. msg = (
  138. "warning: no files found matching '%s' " "under directory '%s'"
  139. )
  140. log.warn(msg, pattern, dir)
  141. elif action == 'recursive-exclude':
  142. self.debug_print("recursive-exclude {} {}".format(dir, ' '.join(patterns)))
  143. for pattern in patterns:
  144. if not self.exclude_pattern(pattern, prefix=dir):
  145. log.warn(
  146. (
  147. "warning: no previously-included files matching "
  148. "'%s' found under directory '%s'"
  149. ),
  150. pattern,
  151. dir,
  152. )
  153. elif action == 'graft':
  154. self.debug_print("graft " + dir_pattern)
  155. if not self.include_pattern(None, prefix=dir_pattern):
  156. log.warn("warning: no directories found matching '%s'", dir_pattern)
  157. elif action == 'prune':
  158. self.debug_print("prune " + dir_pattern)
  159. if not self.exclude_pattern(None, prefix=dir_pattern):
  160. log.warn(
  161. ("no previously-included directories found " "matching '%s'"),
  162. dir_pattern,
  163. )
  164. else:
  165. raise DistutilsInternalError(
  166. "this cannot happen: invalid action '%s'" % action
  167. )
  168. # Filtering/selection methods
  169. def include_pattern(self, pattern, anchor=1, prefix=None, is_regex=0):
  170. """Select strings (presumably filenames) from 'self.files' that
  171. match 'pattern', a Unix-style wildcard (glob) pattern. Patterns
  172. are not quite the same as implemented by the 'fnmatch' module: '*'
  173. and '?' match non-special characters, where "special" is platform-
  174. dependent: slash on Unix; colon, slash, and backslash on
  175. DOS/Windows; and colon on Mac OS.
  176. If 'anchor' is true (the default), then the pattern match is more
  177. stringent: "*.py" will match "foo.py" but not "foo/bar.py". If
  178. 'anchor' is false, both of these will match.
  179. If 'prefix' is supplied, then only filenames starting with 'prefix'
  180. (itself a pattern) and ending with 'pattern', with anything in between
  181. them, will match. 'anchor' is ignored in this case.
  182. If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and
  183. 'pattern' is assumed to be either a string containing a regex or a
  184. regex object -- no translation is done, the regex is just compiled
  185. and used as-is.
  186. Selected strings will be added to self.files.
  187. Return True if files are found, False otherwise.
  188. """
  189. # XXX docstring lying about what the special chars are?
  190. files_found = False
  191. pattern_re = translate_pattern(pattern, anchor, prefix, is_regex)
  192. self.debug_print("include_pattern: applying regex r'%s'" % pattern_re.pattern)
  193. # delayed loading of allfiles list
  194. if self.allfiles is None:
  195. self.findall()
  196. for name in self.allfiles:
  197. if pattern_re.search(name):
  198. self.debug_print(" adding " + name)
  199. self.files.append(name)
  200. files_found = True
  201. return files_found
  202. def exclude_pattern(self, pattern, anchor=1, prefix=None, is_regex=0):
  203. """Remove strings (presumably filenames) from 'files' that match
  204. 'pattern'. Other parameters are the same as for
  205. 'include_pattern()', above.
  206. The list 'self.files' is modified in place.
  207. Return True if files are found, False otherwise.
  208. """
  209. files_found = False
  210. pattern_re = translate_pattern(pattern, anchor, prefix, is_regex)
  211. self.debug_print("exclude_pattern: applying regex r'%s'" % pattern_re.pattern)
  212. for i in range(len(self.files) - 1, -1, -1):
  213. if pattern_re.search(self.files[i]):
  214. self.debug_print(" removing " + self.files[i])
  215. del self.files[i]
  216. files_found = True
  217. return files_found
  218. # Utility functions
  219. def _find_all_simple(path):
  220. """
  221. Find all files under 'path'
  222. """
  223. all_unique = _UniqueDirs.filter(os.walk(path, followlinks=True))
  224. results = (
  225. os.path.join(base, file) for base, dirs, files in all_unique for file in files
  226. )
  227. return filter(os.path.isfile, results)
  228. class _UniqueDirs(set):
  229. """
  230. Exclude previously-seen dirs from walk results,
  231. avoiding infinite recursion.
  232. Ref https://bugs.python.org/issue44497.
  233. """
  234. def __call__(self, walk_item):
  235. """
  236. Given an item from an os.walk result, determine
  237. if the item represents a unique dir for this instance
  238. and if not, prevent further traversal.
  239. """
  240. base, dirs, files = walk_item
  241. stat = os.stat(base)
  242. candidate = stat.st_dev, stat.st_ino
  243. found = candidate in self
  244. if found:
  245. del dirs[:]
  246. self.add(candidate)
  247. return not found
  248. @classmethod
  249. def filter(cls, items):
  250. return filter(cls(), items)
  251. def findall(dir=os.curdir):
  252. """
  253. Find all files under 'dir' and return the list of full filenames.
  254. Unless dir is '.', return full filenames with dir prepended.
  255. """
  256. files = _find_all_simple(dir)
  257. if dir == os.curdir:
  258. make_rel = functools.partial(os.path.relpath, start=dir)
  259. files = map(make_rel, files)
  260. return list(files)
  261. def glob_to_re(pattern):
  262. """Translate a shell-like glob pattern to a regular expression; return
  263. a string containing the regex. Differs from 'fnmatch.translate()' in
  264. that '*' does not match "special characters" (which are
  265. platform-specific).
  266. """
  267. pattern_re = fnmatch.translate(pattern)
  268. # '?' and '*' in the glob pattern become '.' and '.*' in the RE, which
  269. # IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix,
  270. # and by extension they shouldn't match such "special characters" under
  271. # any OS. So change all non-escaped dots in the RE to match any
  272. # character except the special characters (currently: just os.sep).
  273. sep = os.sep
  274. if os.sep == '\\':
  275. # we're using a regex to manipulate a regex, so we need
  276. # to escape the backslash twice
  277. sep = r'\\\\'
  278. escaped = r'\1[^%s]' % sep
  279. pattern_re = re.sub(r'((?<!\\)(\\\\)*)\.', escaped, pattern_re)
  280. return pattern_re
  281. def translate_pattern(pattern, anchor=1, prefix=None, is_regex=0):
  282. """Translate a shell-like wildcard pattern to a compiled regular
  283. expression. Return the compiled regex. If 'is_regex' true,
  284. then 'pattern' is directly compiled to a regex (if it's a string)
  285. or just returned as-is (assumes it's a regex object).
  286. """
  287. if is_regex:
  288. if isinstance(pattern, str):
  289. return re.compile(pattern)
  290. else:
  291. return pattern
  292. # ditch start and end characters
  293. start, _, end = glob_to_re('_').partition('_')
  294. if pattern:
  295. pattern_re = glob_to_re(pattern)
  296. assert pattern_re.startswith(start) and pattern_re.endswith(end)
  297. else:
  298. pattern_re = ''
  299. if prefix is not None:
  300. prefix_re = glob_to_re(prefix)
  301. assert prefix_re.startswith(start) and prefix_re.endswith(end)
  302. prefix_re = prefix_re[len(start) : len(prefix_re) - len(end)]
  303. sep = os.sep
  304. if os.sep == '\\':
  305. sep = r'\\'
  306. pattern_re = pattern_re[len(start) : len(pattern_re) - len(end)]
  307. pattern_re = r'{}\A{}{}.*{}{}'.format(start, prefix_re, sep, pattern_re, end)
  308. else: # no prefix -- respect anchor flag
  309. if anchor:
  310. pattern_re = r'{}\A{}'.format(start, pattern_re[len(start) :])
  311. return re.compile(pattern_re)