blob: cc48e48e58c85fbba3d5dfb38649c13609428a25 [file] [log] [blame]
Greg Wardadc11722000-07-30 00:04:17 +00001"""distutils.filelist
2
3Provides the FileList class, used for poking about the filesystem
4and building lists of files.
5"""
6
Martin v. Löwis5a6601c2004-11-10 22:23:15 +00007# This module should be kept compatible with Python 2.1.
Andrew M. Kuchlingd448f662002-11-19 13:12:28 +00008
Greg Wardadc11722000-07-30 00:04:17 +00009__revision__ = "$Id$"
10
Neal Norwitz9d72bb42007-04-17 08:48:32 +000011import os, re
Greg Wardadc11722000-07-30 00:04:17 +000012import fnmatch
13from types import *
14from glob import glob
15from distutils.util import convert_path
Greg Ward7b3d56c2000-07-30 00:21:36 +000016from distutils.errors import DistutilsTemplateError, DistutilsInternalError
Jeremy Hylton4f2f1332002-06-04 21:04:03 +000017from distutils import log
Greg Wardadc11722000-07-30 00:04:17 +000018
19class FileList:
20
Greg Wardc98927a2000-07-30 00:08:13 +000021 """A list of files built by on exploring the filesystem and filtered by
22 applying various patterns to what we find there.
Greg Wardadc11722000-07-30 00:04:17 +000023
Greg Wardc98927a2000-07-30 00:08:13 +000024 Instance attributes:
25 dir
26 directory from which files will be taken -- only used if
27 'allfiles' not supplied to constructor
28 files
29 list of filenames currently being built/filtered/manipulated
30 allfiles
31 complete list of files under consideration (ie. without any
32 filtering applied)
33 """
Greg Wardadc11722000-07-30 00:04:17 +000034
Fred Drakeb94b8492001-12-06 20:51:35 +000035 def __init__(self,
36 warn=None,
Greg Wardadc11722000-07-30 00:04:17 +000037 debug_print=None):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000038 # ignore argument to FileList, but keep them for backwards
39 # compatibility
Greg Wardc98927a2000-07-30 00:08:13 +000040
Greg Ward979db972000-07-30 01:45:42 +000041 self.allfiles = None
42 self.files = []
Greg Wardadc11722000-07-30 00:04:17 +000043
Greg Ward979db972000-07-30 01:45:42 +000044 def set_allfiles (self, allfiles):
45 self.allfiles = allfiles
46
47 def findall (self, dir=os.curdir):
48 self.allfiles = findall(dir)
49
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000050 def debug_print (self, msg):
Greg Wardadc11722000-07-30 00:04:17 +000051 """Print 'msg' to stdout if the global DEBUG (taken from the
52 DISTUTILS_DEBUG environment variable) flag is true.
53 """
Jeremy Hyltonfcd73532002-09-11 16:31:53 +000054 from distutils.debug import DEBUG
Greg Wardadc11722000-07-30 00:04:17 +000055 if DEBUG:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000056 print(msg)
Greg Wardadc11722000-07-30 00:04:17 +000057
Greg Ward979db972000-07-30 01:45:42 +000058 # -- List-like methods ---------------------------------------------
59
60 def append (self, item):
61 self.files.append(item)
62
63 def extend (self, items):
64 self.files.extend(items)
65
66 def sort (self):
67 # Not a strict lexical sort!
Collin Winterdc40ae62007-07-17 00:39:32 +000068 sortable_files = sorted(map(os.path.split, self.files))
Greg Ward979db972000-07-30 01:45:42 +000069 self.files = []
70 for sort_tuple in sortable_files:
Neal Norwitzd9108552006-03-17 08:00:19 +000071 self.files.append(os.path.join(*sort_tuple))
Greg Ward979db972000-07-30 01:45:42 +000072
73
74 # -- Other miscellaneous utility methods ---------------------------
75
76 def remove_duplicates (self):
77 # Assumes list has been sorted!
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000078 for i in range(len(self.files) - 1, 0, -1):
79 if self.files[i] == self.files[i - 1]:
Greg Ward979db972000-07-30 01:45:42 +000080 del self.files[i]
81
82
83 # -- "File template" methods ---------------------------------------
Fred Drakeb94b8492001-12-06 20:51:35 +000084
Greg Ward7b3d56c2000-07-30 00:21:36 +000085 def _parse_template_line (self, line):
Neal Norwitz9d72bb42007-04-17 08:48:32 +000086 words = line.split()
Greg Wardc98927a2000-07-30 00:08:13 +000087 action = words[0]
Greg Wardadc11722000-07-30 00:04:17 +000088
Greg Ward7b3d56c2000-07-30 00:21:36 +000089 patterns = dir = dir_pattern = None
90
91 if action in ('include', 'exclude',
92 'global-include', 'global-exclude'):
Greg Ward071ed762000-09-26 02:12:31 +000093 if len(words) < 2:
Greg Ward7b3d56c2000-07-30 00:21:36 +000094 raise DistutilsTemplateError, \
95 "'%s' expects <pattern1> <pattern2> ..." % action
Greg Wardadc11722000-07-30 00:04:17 +000096
Greg Ward7b3d56c2000-07-30 00:21:36 +000097 patterns = map(convert_path, words[1:])
Greg Wardadc11722000-07-30 00:04:17 +000098
Greg Ward7b3d56c2000-07-30 00:21:36 +000099 elif action in ('recursive-include', 'recursive-exclude'):
Greg Ward071ed762000-09-26 02:12:31 +0000100 if len(words) < 3:
Greg Ward7b3d56c2000-07-30 00:21:36 +0000101 raise DistutilsTemplateError, \
102 "'%s' expects <dir> <pattern1> <pattern2> ..." % action
Greg Wardadc11722000-07-30 00:04:17 +0000103
Greg Wardc98927a2000-07-30 00:08:13 +0000104 dir = convert_path(words[1])
Greg Ward7b3d56c2000-07-30 00:21:36 +0000105 patterns = map(convert_path, words[2:])
Greg Wardadc11722000-07-30 00:04:17 +0000106
Greg Ward7b3d56c2000-07-30 00:21:36 +0000107 elif action in ('graft', 'prune'):
Greg Ward071ed762000-09-26 02:12:31 +0000108 if len(words) != 2:
Greg Ward7b3d56c2000-07-30 00:21:36 +0000109 raise DistutilsTemplateError, \
110 "'%s' expects a single <dir_pattern>" % action
Greg Wardadc11722000-07-30 00:04:17 +0000111
Greg Ward7b3d56c2000-07-30 00:21:36 +0000112 dir_pattern = convert_path(words[1])
Greg Wardadc11722000-07-30 00:04:17 +0000113
Greg Wardc98927a2000-07-30 00:08:13 +0000114 else:
Greg Ward7b3d56c2000-07-30 00:21:36 +0000115 raise DistutilsTemplateError, "unknown action '%s'" % action
116
Greg Wardd5dcc172000-07-30 01:04:22 +0000117 return (action, patterns, dir, dir_pattern)
Greg Ward7b3d56c2000-07-30 00:21:36 +0000118
119 # _parse_template_line ()
Greg Ward7b3d56c2000-07-30 00:21:36 +0000120
Fred Drakeb94b8492001-12-06 20:51:35 +0000121
122 def process_template_line (self, line):
Greg Ward7b3d56c2000-07-30 00:21:36 +0000123
124 # Parse the line: split it up, make sure the right number of words
Greg Ward0f341852000-07-30 00:36:25 +0000125 # is there, and return the relevant words. 'action' is always
Greg Ward7b3d56c2000-07-30 00:21:36 +0000126 # defined: it's the first word of the line. Which of the other
127 # three are defined depends on the action; it'll be either
128 # patterns, (dir and patterns), or (dir_pattern).
129 (action, patterns, dir, dir_pattern) = self._parse_template_line(line)
Greg Wardadc11722000-07-30 00:04:17 +0000130
Greg Wardc98927a2000-07-30 00:08:13 +0000131 # OK, now we know that the action is valid and we have the
132 # right number of words on the line for that action -- so we
Greg Ward7b3d56c2000-07-30 00:21:36 +0000133 # can proceed with minimal error-checking.
Greg Wardc98927a2000-07-30 00:08:13 +0000134 if action == 'include':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000135 self.debug_print("include " + ' '.join(patterns))
Greg Ward7b3d56c2000-07-30 00:21:36 +0000136 for pattern in patterns:
Greg Ward071ed762000-09-26 02:12:31 +0000137 if not self.include_pattern(pattern, anchor=1):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000138 log.warn("warning: no files found matching '%s'",
139 pattern)
Greg Wardadc11722000-07-30 00:04:17 +0000140
Greg Wardc98927a2000-07-30 00:08:13 +0000141 elif action == 'exclude':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000142 self.debug_print("exclude " + ' '.join(patterns))
Greg Ward7b3d56c2000-07-30 00:21:36 +0000143 for pattern in patterns:
Greg Ward071ed762000-09-26 02:12:31 +0000144 if not self.exclude_pattern(pattern, anchor=1):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000145 log.warn(("warning: no previously-included files "
146 "found matching '%s'"), pattern)
Greg Wardc98927a2000-07-30 00:08:13 +0000147
148 elif action == 'global-include':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000149 self.debug_print("global-include " + ' '.join(patterns))
Greg Ward7b3d56c2000-07-30 00:21:36 +0000150 for pattern in patterns:
Greg Ward071ed762000-09-26 02:12:31 +0000151 if not self.include_pattern(pattern, anchor=0):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000152 log.warn(("warning: no files found matching '%s' " +
153 "anywhere in distribution"), pattern)
Greg Wardc98927a2000-07-30 00:08:13 +0000154
155 elif action == 'global-exclude':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000156 self.debug_print("global-exclude " + ' '.join(patterns))
Greg Ward7b3d56c2000-07-30 00:21:36 +0000157 for pattern in patterns:
Greg Ward071ed762000-09-26 02:12:31 +0000158 if not self.exclude_pattern(pattern, anchor=0):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000159 log.warn(("warning: no previously-included files matching "
160 "'%s' found anywhere in distribution"),
161 pattern)
Greg Wardc98927a2000-07-30 00:08:13 +0000162
163 elif action == 'recursive-include':
164 self.debug_print("recursive-include %s %s" %
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000165 (dir, ' '.join(patterns)))
Greg Ward7b3d56c2000-07-30 00:21:36 +0000166 for pattern in patterns:
Greg Ward071ed762000-09-26 02:12:31 +0000167 if not self.include_pattern(pattern, prefix=dir):
Walter Dörwaldcbd0b362004-05-31 15:12:27 +0000168 log.warn(("warning: no files found matching '%s' " +
Tim Peters182b5ac2004-07-18 06:16:08 +0000169 "under directory '%s'"),
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000170 pattern, dir)
Greg Wardc98927a2000-07-30 00:08:13 +0000171
172 elif action == 'recursive-exclude':
173 self.debug_print("recursive-exclude %s %s" %
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000174 (dir, ' '.join(patterns)))
Greg Ward7b3d56c2000-07-30 00:21:36 +0000175 for pattern in patterns:
Greg Wardc98927a2000-07-30 00:08:13 +0000176 if not self.exclude_pattern(pattern, prefix=dir):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000177 log.warn(("warning: no previously-included files matching "
178 "'%s' found under directory '%s'"),
179 pattern, dir)
Fred Drakeb94b8492001-12-06 20:51:35 +0000180
Greg Wardc98927a2000-07-30 00:08:13 +0000181 elif action == 'graft':
182 self.debug_print("graft " + dir_pattern)
Greg Ward0f341852000-07-30 00:36:25 +0000183 if not self.include_pattern(None, prefix=dir_pattern):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000184 log.warn("warning: no directories found matching '%s'",
185 dir_pattern)
Greg Wardc98927a2000-07-30 00:08:13 +0000186
187 elif action == 'prune':
188 self.debug_print("prune " + dir_pattern)
189 if not self.exclude_pattern(None, prefix=dir_pattern):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000190 log.warn(("no previously-included directories found " +
191 "matching '%s'"), dir_pattern)
Greg Wardc98927a2000-07-30 00:08:13 +0000192 else:
Greg Ward7b3d56c2000-07-30 00:21:36 +0000193 raise DistutilsInternalError, \
Greg Wardc98927a2000-07-30 00:08:13 +0000194 "this cannot happen: invalid action '%s'" % action
Greg Wardadc11722000-07-30 00:04:17 +0000195
Greg Ward7b3d56c2000-07-30 00:21:36 +0000196 # process_template_line ()
Greg Wardadc11722000-07-30 00:04:17 +0000197
198
Greg Ward979db972000-07-30 01:45:42 +0000199 # -- Filtering/selection methods -----------------------------------
200
Greg Ward0f341852000-07-30 00:36:25 +0000201 def include_pattern (self, pattern,
Greg Ward071ed762000-09-26 02:12:31 +0000202 anchor=1, prefix=None, is_regex=0):
Greg Ward0f341852000-07-30 00:36:25 +0000203 """Select strings (presumably filenames) from 'self.files' that
204 match 'pattern', a Unix-style wildcard (glob) pattern. Patterns
205 are not quite the same as implemented by the 'fnmatch' module: '*'
206 and '?' match non-special characters, where "special" is platform-
207 dependent: slash on Unix; colon, slash, and backslash on
208 DOS/Windows; and colon on Mac OS.
Greg Wardadc11722000-07-30 00:04:17 +0000209
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
214 If 'prefix' is supplied, then only filenames starting with 'prefix'
215 (itself a pattern) and ending with 'pattern', with anything in between
216 them, will match. 'anchor' is ignored in this case.
217
218 If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and
219 'pattern' is assumed to be either a string containing a regex or a
220 regex object -- no translation is done, the regex is just compiled
221 and used as-is.
222
223 Selected strings will be added to self.files.
224
225 Return 1 if files are found.
226 """
227 files_found = 0
Greg Ward071ed762000-09-26 02:12:31 +0000228 pattern_re = translate_pattern(pattern, anchor, prefix, is_regex)
Greg Ward0f341852000-07-30 00:36:25 +0000229 self.debug_print("include_pattern: applying regex r'%s'" %
Greg Wardadc11722000-07-30 00:04:17 +0000230 pattern_re.pattern)
231
232 # delayed loading of allfiles list
Greg Ward979db972000-07-30 01:45:42 +0000233 if self.allfiles is None:
234 self.findall()
Greg Wardadc11722000-07-30 00:04:17 +0000235
236 for name in self.allfiles:
Greg Ward071ed762000-09-26 02:12:31 +0000237 if pattern_re.search(name):
Greg Wardadc11722000-07-30 00:04:17 +0000238 self.debug_print(" adding " + name)
Greg Ward071ed762000-09-26 02:12:31 +0000239 self.files.append(name)
Greg Wardadc11722000-07-30 00:04:17 +0000240 files_found = 1
Fred Drakeb94b8492001-12-06 20:51:35 +0000241
Greg Wardadc11722000-07-30 00:04:17 +0000242 return files_found
243
Greg Ward0f341852000-07-30 00:36:25 +0000244 # include_pattern ()
Greg Wardadc11722000-07-30 00:04:17 +0000245
246
247 def exclude_pattern (self, pattern,
248 anchor=1, prefix=None, is_regex=0):
249 """Remove strings (presumably filenames) from 'files' that match
250 'pattern'. Other parameters are the same as for
Fred Drakeb94b8492001-12-06 20:51:35 +0000251 'include_pattern()', above.
Greg Wardadc11722000-07-30 00:04:17 +0000252 The list 'self.files' is modified in place.
253 Return 1 if files are found.
254 """
255 files_found = 0
Greg Ward071ed762000-09-26 02:12:31 +0000256 pattern_re = translate_pattern(pattern, anchor, prefix, is_regex)
Greg Wardadc11722000-07-30 00:04:17 +0000257 self.debug_print("exclude_pattern: applying regex r'%s'" %
258 pattern_re.pattern)
Greg Ward071ed762000-09-26 02:12:31 +0000259 for i in range(len(self.files)-1, -1, -1):
260 if pattern_re.search(self.files[i]):
Greg Wardadc11722000-07-30 00:04:17 +0000261 self.debug_print(" removing " + self.files[i])
262 del self.files[i]
263 files_found = 1
Fred Drakeb94b8492001-12-06 20:51:35 +0000264
Greg Wardadc11722000-07-30 00:04:17 +0000265 return files_found
266
267 # exclude_pattern ()
268
Greg Wardadc11722000-07-30 00:04:17 +0000269# class FileList
270
271
272# ----------------------------------------------------------------------
273# Utility functions
274
275def findall (dir = os.curdir):
276 """Find all files under 'dir' and return the list of full filenames
277 (relative to 'dir').
278 """
279 from stat import ST_MODE, S_ISREG, S_ISDIR, S_ISLNK
280
281 list = []
282 stack = [dir]
283 pop = stack.pop
284 push = stack.append
285
286 while stack:
287 dir = pop()
Greg Ward071ed762000-09-26 02:12:31 +0000288 names = os.listdir(dir)
Greg Wardadc11722000-07-30 00:04:17 +0000289
290 for name in names:
291 if dir != os.curdir: # avoid the dreaded "./" syndrome
Greg Ward071ed762000-09-26 02:12:31 +0000292 fullname = os.path.join(dir, name)
Greg Wardadc11722000-07-30 00:04:17 +0000293 else:
294 fullname = name
295
296 # Avoid excess stat calls -- just one will do, thank you!
297 stat = os.stat(fullname)
298 mode = stat[ST_MODE]
299 if S_ISREG(mode):
Greg Ward071ed762000-09-26 02:12:31 +0000300 list.append(fullname)
Greg Wardadc11722000-07-30 00:04:17 +0000301 elif S_ISDIR(mode) and not S_ISLNK(mode):
Greg Ward071ed762000-09-26 02:12:31 +0000302 push(fullname)
Greg Wardadc11722000-07-30 00:04:17 +0000303
304 return list
305
306
307def glob_to_re (pattern):
308 """Translate a shell-like glob pattern to a regular expression; return
309 a string containing the regex. Differs from 'fnmatch.translate()' in
310 that '*' does not match "special characters" (which are
311 platform-specific).
312 """
Greg Ward071ed762000-09-26 02:12:31 +0000313 pattern_re = fnmatch.translate(pattern)
Greg Wardadc11722000-07-30 00:04:17 +0000314
315 # '?' and '*' in the glob pattern become '.' and '.*' in the RE, which
316 # IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix,
317 # and by extension they shouldn't match such "special characters" under
318 # any OS. So change all non-escaped dots in the RE to match any
319 # character except the special characters.
320 # XXX currently the "special characters" are just slash -- i.e. this is
321 # Unix-only.
Greg Ward071ed762000-09-26 02:12:31 +0000322 pattern_re = re.sub(r'(^|[^\\])\.', r'\1[^/]', pattern_re)
Greg Wardadc11722000-07-30 00:04:17 +0000323 return pattern_re
324
325# glob_to_re ()
326
327
328def translate_pattern (pattern, anchor=1, prefix=None, is_regex=0):
329 """Translate a shell-like wildcard pattern to a compiled regular
330 expression. Return the compiled regex. If 'is_regex' true,
331 then 'pattern' is directly compiled to a regex (if it's a string)
332 or just returned as-is (assumes it's a regex object).
333 """
334 if is_regex:
Guido van Rossum572dbf82007-04-27 23:53:51 +0000335 if isinstance(pattern, basestring):
Greg Wardadc11722000-07-30 00:04:17 +0000336 return re.compile(pattern)
337 else:
338 return pattern
339
340 if pattern:
Greg Ward071ed762000-09-26 02:12:31 +0000341 pattern_re = glob_to_re(pattern)
Greg Wardadc11722000-07-30 00:04:17 +0000342 else:
343 pattern_re = ''
Fred Drakeb94b8492001-12-06 20:51:35 +0000344
Greg Wardadc11722000-07-30 00:04:17 +0000345 if prefix is not None:
Greg Ward071ed762000-09-26 02:12:31 +0000346 prefix_re = (glob_to_re(prefix))[0:-1] # ditch trailing $
347 pattern_re = "^" + os.path.join(prefix_re, ".*" + pattern_re)
Greg Wardadc11722000-07-30 00:04:17 +0000348 else: # no prefix -- respect anchor flag
349 if anchor:
350 pattern_re = "^" + pattern_re
Fred Drakeb94b8492001-12-06 20:51:35 +0000351
Greg Ward071ed762000-09-26 02:12:31 +0000352 return re.compile(pattern_re)
Greg Wardadc11722000-07-30 00:04:17 +0000353
354# translate_pattern ()