~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/globbing.py

  • Committer: John Arbash Meinel
  • Author(s): Mark Hammond
  • Date: 2008-09-09 17:02:21 UTC
  • mto: This revision was merged to the branch mainline in revision 3697.
  • Revision ID: john@arbash-meinel.com-20080909170221-svim3jw2mrz0amp3
An updated transparent icon for bzr.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2011 Canonical Ltd
 
1
# Copyright (C) 2006, 2008 Canonical Ltd
2
2
 
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""Tools for converting globs to regular expressions.
18
18
 
20
20
expressions.
21
21
"""
22
22
 
23
 
from __future__ import absolute_import
24
 
 
25
23
import re
26
24
 
27
 
from bzrlib import (
28
 
    errors,
29
 
    lazy_regex,
30
 
    )
31
25
from bzrlib.trace import (
32
 
    mutter,
33
 
    warning,
 
26
    warning
34
27
    )
35
28
 
36
29
 
43
36
    must not contain capturing groups.
44
37
    """
45
38
 
46
 
    _expand = lazy_regex.lazy_compile(ur'\\&')
 
39
    _expand = re.compile(ur'\\&')
47
40
 
48
41
    def __init__(self, source=None):
49
42
        self._pat = None
59
52
 
60
53
        The pattern must not contain capturing groups.
61
54
        The replacement might be either a string template in which \& will be
62
 
        replaced with the match, or a function that will get the matching text
63
 
        as argument. It does not get match object, because capturing is
 
55
        replaced with the match, or a function that will get the matching text  
 
56
        as argument. It does not get match object, because capturing is 
64
57
        forbidden anyway.
65
58
        """
66
59
        self._pat = None
79
72
 
80
73
    def __call__(self, text):
81
74
        if not self._pat:
82
 
            self._pat = lazy_regex.lazy_compile(
 
75
            self._pat = re.compile(
83
76
                    u'|'.join([u'(%s)' % p for p in self._pats]),
84
77
                    re.UNICODE)
85
78
        return self._pat.sub(self._do_sub, text)
167
160
 
168
161
    Patterns are translated to regular expressions to expidite matching.
169
162
 
170
 
    The regular expressions for multiple patterns are aggregated into
171
 
    a super-regex containing groups of up to 99 patterns.
 
163
    The regular expressions for multiple patterns are aggregated into 
 
164
    a super-regex containing groups of up to 99 patterns.  
172
165
    The 99 limitation is due to the grouping limit of the Python re module.
173
166
    The resulting super-regex and associated patterns are stored as a list of
174
167
    (regex,[patterns]) in _regex_patterns.
175
 
 
 
168
    
176
169
    For performance reasons the patterns are categorised as extension patterns
177
170
    (those that match against a file extension), basename patterns
178
171
    (those that match against the basename of the filename),
179
172
    and fullpath patterns (those that match against the full path).
180
 
    The translations used for extensions and basenames are relatively simpler
 
173
    The translations used for extensions and basenames are relatively simpler 
181
174
    and therefore faster to perform than the fullpath patterns.
182
175
 
183
 
    Also, the extension patterns are more likely to find a match and
 
176
    Also, the extension patterns are more likely to find a match and 
184
177
    so are matched first, then the basename patterns, then the fullpath
185
178
    patterns.
186
179
    """
187
 
    # We want to _add_patterns in a specific order (as per type_list below)
188
 
    # starting with the shortest and going to the longest.
189
 
    # As some Python version don't support ordered dicts the list below is
190
 
    # used to select inputs for _add_pattern in a specific order.
191
 
    pattern_types = [ "extension", "basename", "fullpath" ]
192
 
 
193
 
    pattern_info = {
194
 
        "extension" : {
195
 
            "translator" : _sub_extension,
196
 
            "prefix" : r'(?:.*/)?(?!.*/)(?:.*\.)'
197
 
        },
198
 
        "basename" : {
199
 
            "translator" : _sub_basename,
200
 
            "prefix" : r'(?:.*/)?(?!.*/)'
201
 
        },
202
 
        "fullpath" : {
203
 
            "translator" : _sub_fullpath,
204
 
            "prefix" : r''
205
 
        },
206
 
    }
207
 
 
208
180
    def __init__(self, patterns):
209
181
        self._regex_patterns = []
210
 
        pattern_lists = {
211
 
            "extension" : [],
212
 
            "basename" : [],
213
 
            "fullpath" : [],
214
 
        }
 
182
        path_patterns = []
 
183
        base_patterns = []
 
184
        ext_patterns = []
215
185
        for pat in patterns:
216
186
            pat = normalize_pattern(pat)
217
 
            pattern_lists[Globster.identify(pat)].append(pat)
218
 
        pi = Globster.pattern_info
219
 
        for t in Globster.pattern_types:
220
 
            self._add_patterns(pattern_lists[t], pi[t]["translator"],
221
 
                pi[t]["prefix"])
 
187
            if pat.startswith(u'RE:') or u'/' in pat:
 
188
                path_patterns.append(pat)
 
189
            elif pat.startswith(u'*.'):
 
190
                ext_patterns.append(pat)
 
191
            else:
 
192
                base_patterns.append(pat)
 
193
        self._add_patterns(ext_patterns,_sub_extension,
 
194
            prefix=r'(?:.*/)?(?!.*/)(?:.*\.)')
 
195
        self._add_patterns(base_patterns,_sub_basename, 
 
196
            prefix=r'(?:.*/)?(?!.*/)')
 
197
        self._add_patterns(path_patterns,_sub_fullpath) 
222
198
 
223
199
    def _add_patterns(self, patterns, translator, prefix=''):
224
200
        while patterns:
225
 
            grouped_rules = [
226
 
                '(%s)' % translator(pat) for pat in patterns[:99]]
 
201
            grouped_rules = ['(%s)' % translator(pat) for pat in patterns[:99]]
227
202
            joined_rule = '%s(?:%s)$' % (prefix, '|'.join(grouped_rules))
228
 
            # Explicitly use lazy_compile here, because we count on its
229
 
            # nicer error reporting.
230
 
            self._regex_patterns.append((
231
 
                lazy_regex.lazy_compile(joined_rule, re.UNICODE),
 
203
            self._regex_patterns.append((re.compile(joined_rule, re.UNICODE), 
232
204
                patterns[:99]))
233
205
            patterns = patterns[99:]
234
206
 
235
207
    def match(self, filename):
236
208
        """Searches for a pattern that matches the given filename.
237
 
 
 
209
        
238
210
        :return A matching pattern or None if there is no matching pattern.
239
211
        """
240
 
        try:
241
 
            for regex, patterns in self._regex_patterns:
242
 
                match = regex.match(filename)
243
 
                if match:
244
 
                    return patterns[match.lastindex -1]
245
 
        except errors.InvalidPattern, e:
246
 
            # We can't show the default e.msg to the user as thats for
247
 
            # the combined pattern we sent to regex. Instead we indicate to
248
 
            # the user that an ignore file needs fixing.
249
 
            mutter('Invalid pattern found in regex: %s.', e.msg)
250
 
            e.msg = "File ~/.bazaar/ignore or .bzrignore contains error(s)."
251
 
            bad_patterns = ''
252
 
            for _, patterns in self._regex_patterns:
253
 
                for p in patterns:
254
 
                    if not Globster.is_pattern_valid(p):
255
 
                        bad_patterns += ('\n  %s' % p)
256
 
            e.msg += bad_patterns
257
 
            raise e
 
212
        for regex, patterns in self._regex_patterns:
 
213
            match = regex.match(filename)
 
214
            if match:
 
215
                return patterns[match.lastindex -1]
258
216
        return None
259
217
 
260
 
    @staticmethod
261
 
    def identify(pattern):
262
 
        """Returns pattern category.
263
 
 
264
 
        :param pattern: normalized pattern.
265
 
        Identify if a pattern is fullpath, basename or extension
266
 
        and returns the appropriate type.
267
 
        """
268
 
        if pattern.startswith(u'RE:') or u'/' in pattern:
269
 
            return "fullpath"
270
 
        elif pattern.startswith(u'*.'):
271
 
            return "extension"
272
 
        else:
273
 
            return "basename"
274
 
 
275
 
    @staticmethod
276
 
    def is_pattern_valid(pattern):
277
 
        """Returns True if pattern is valid.
278
 
 
279
 
        :param pattern: Normalized pattern.
280
 
        is_pattern_valid() assumes pattern to be normalized.
281
 
        see: globbing.normalize_pattern
282
 
        """
283
 
        result = True
284
 
        translator = Globster.pattern_info[Globster.identify(pattern)]["translator"]
285
 
        tpattern = '(%s)' % translator(pattern)
286
 
        try:
287
 
            re_obj = lazy_regex.lazy_compile(tpattern, re.UNICODE)
288
 
            re_obj.search("") # force compile
289
 
        except errors.InvalidPattern, e:
290
 
            result = False
291
 
        return result
292
 
 
293
 
 
294
 
class ExceptionGlobster(object):
295
 
    """A Globster that supports exception patterns.
296
 
    
297
 
    Exceptions are ignore patterns prefixed with '!'.  Exception
298
 
    patterns take precedence over regular patterns and cause a 
299
 
    matching filename to return None from the match() function.  
300
 
    Patterns using a '!!' prefix are highest precedence, and act 
301
 
    as regular ignores. '!!' patterns are useful to establish ignores
302
 
    that apply under paths specified by '!' exception patterns.
303
 
    """
304
 
    
305
 
    def __init__(self,patterns):
306
 
        ignores = [[], [], []]
307
 
        for p in patterns:
308
 
            if p.startswith(u'!!'):
309
 
                ignores[2].append(p[2:])
310
 
            elif p.startswith(u'!'):
311
 
                ignores[1].append(p[1:])
312
 
            else:
313
 
                ignores[0].append(p)
314
 
        self._ignores = [Globster(i) for i in ignores]
315
 
        
316
 
    def match(self, filename):
317
 
        """Searches for a pattern that matches the given filename.
318
 
 
319
 
        :return A matching pattern or None if there is no matching pattern.
320
 
        """
321
 
        double_neg = self._ignores[2].match(filename)
322
 
        if double_neg:
323
 
            return "!!%s" % double_neg
324
 
        elif self._ignores[1].match(filename):
325
 
            return None
326
 
        else:
327
 
            return self._ignores[0].match(filename)
328
218
 
329
219
class _OrderedGlobster(Globster):
330
220
    """A Globster that keeps pattern order."""
338
228
        self._regex_patterns = []
339
229
        for pat in patterns:
340
230
            pat = normalize_pattern(pat)
341
 
            t = Globster.identify(pat)
342
 
            self._add_patterns([pat], Globster.pattern_info[t]["translator"],
343
 
                Globster.pattern_info[t]["prefix"])
344
 
 
345
 
 
346
 
_slashes = lazy_regex.lazy_compile(r'[\\/]+')
 
231
            if pat.startswith(u'RE:') or u'/' in pat:
 
232
                self._add_patterns([pat], _sub_fullpath) 
 
233
            elif pat.startswith(u'*.'):
 
234
                self._add_patterns([pat], _sub_extension,
 
235
                    prefix=r'(?:.*/)?(?!.*/)(?:.*\.)')
 
236
            else:
 
237
                self._add_patterns([pat], _sub_basename, 
 
238
                    prefix=r'(?:.*/)?(?!.*/)')
 
239
 
 
240
 
347
241
def normalize_pattern(pattern):
348
242
    """Converts backslashes in path patterns to forward slashes.
349
 
 
 
243
    
350
244
    Doesn't normalize regular expressions - they may contain escapes.
351
245
    """
352
 
    if not (pattern.startswith('RE:') or pattern.startswith('!RE:')):
353
 
        pattern = _slashes.sub('/', pattern)
354
 
    if len(pattern) > 1:
355
 
        pattern = pattern.rstrip('/')
356
 
    return pattern
 
246
    if not pattern.startswith('RE:'):
 
247
        pattern = pattern.replace('\\','/')
 
248
    return pattern.rstrip('/')