filelist.py 12 KB

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