~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/globbing.py

  • Committer: Martin Pool
  • Date: 2005-06-27 03:34:57 UTC
  • mto: This revision was merged to the branch mainline in revision 852.
  • Revision ID: mbp@sourcefrog.net-20050627033457-4d2c0d1ef375211f
Another test for version inclusion

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2011 Canonical Ltd
2
 
 
3
 
# This program is free software; you can redistribute it and/or modify
4
 
# it under the terms of the GNU General Public License as published by
5
 
# the Free Software Foundation; either version 2 of the License, or
6
 
# (at your option) any later version.
7
 
#
8
 
# This program is distributed in the hope that it will be useful,
9
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
 
# GNU General Public License for more details.
12
 
#
13
 
# You should have received a copy of the GNU General Public License
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
16
 
 
17
 
"""Tools for converting globs to regular expressions.
18
 
 
19
 
This module provides functions for converting shell-like globs to regular
20
 
expressions.
21
 
"""
22
 
 
23
 
from __future__ import absolute_import
24
 
 
25
 
import re
26
 
 
27
 
from bzrlib import (
28
 
    errors,
29
 
    lazy_regex,
30
 
    )
31
 
from bzrlib.trace import (
32
 
    mutter,
33
 
    warning,
34
 
    )
35
 
 
36
 
 
37
 
class Replacer(object):
38
 
    """Do a multiple-pattern substitution.
39
 
 
40
 
    The patterns and substitutions are combined into one, so the result of
41
 
    one replacement is never substituted again. Add the patterns and
42
 
    replacements via the add method and then call the object. The patterns
43
 
    must not contain capturing groups.
44
 
    """
45
 
 
46
 
    _expand = lazy_regex.lazy_compile(ur'\\&')
47
 
 
48
 
    def __init__(self, source=None):
49
 
        self._pat = None
50
 
        if source:
51
 
            self._pats = list(source._pats)
52
 
            self._funs = list(source._funs)
53
 
        else:
54
 
            self._pats = []
55
 
            self._funs = []
56
 
 
57
 
    def add(self, pat, fun):
58
 
        r"""Add a pattern and replacement.
59
 
 
60
 
        The pattern must not contain capturing groups.
61
 
        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
64
 
        forbidden anyway.
65
 
        """
66
 
        self._pat = None
67
 
        self._pats.append(pat)
68
 
        self._funs.append(fun)
69
 
 
70
 
    def add_replacer(self, replacer):
71
 
        r"""Add all patterns from another replacer.
72
 
 
73
 
        All patterns and replacements from replacer are appended to the ones
74
 
        already defined.
75
 
        """
76
 
        self._pat = None
77
 
        self._pats.extend(replacer._pats)
78
 
        self._funs.extend(replacer._funs)
79
 
 
80
 
    def __call__(self, text):
81
 
        if not self._pat:
82
 
            self._pat = lazy_regex.lazy_compile(
83
 
                    u'|'.join([u'(%s)' % p for p in self._pats]),
84
 
                    re.UNICODE)
85
 
        return self._pat.sub(self._do_sub, text)
86
 
 
87
 
    def _do_sub(self, m):
88
 
        fun = self._funs[m.lastindex - 1]
89
 
        if hasattr(fun, '__call__'):
90
 
            return fun(m.group(0))
91
 
        else:
92
 
            return self._expand.sub(m.group(0), fun)
93
 
 
94
 
 
95
 
_sub_named = Replacer()
96
 
_sub_named.add(ur'\[:digit:\]', ur'\d')
97
 
_sub_named.add(ur'\[:space:\]', ur'\s')
98
 
_sub_named.add(ur'\[:alnum:\]', ur'\w')
99
 
_sub_named.add(ur'\[:ascii:\]', ur'\0-\x7f')
100
 
_sub_named.add(ur'\[:blank:\]', ur' \t')
101
 
_sub_named.add(ur'\[:cntrl:\]', ur'\0-\x1f\x7f-\x9f')
102
 
 
103
 
 
104
 
def _sub_group(m):
105
 
    if m[1] in (u'!', u'^'):
106
 
        return u'[^' + _sub_named(m[2:-1]) + u']'
107
 
    return u'[' + _sub_named(m[1:-1]) + u']'
108
 
 
109
 
 
110
 
def _invalid_regex(repl):
111
 
    def _(m):
112
 
        warning(u"'%s' not allowed within a regular expression. "
113
 
                "Replacing with '%s'" % (m, repl))
114
 
        return repl
115
 
    return _
116
 
 
117
 
 
118
 
def _trailing_backslashes_regex(m):
119
 
    """Check trailing backslashes.
120
 
 
121
 
    Does a head count on trailing backslashes to ensure there isn't an odd
122
 
    one on the end that would escape the brackets we wrap the RE in.
123
 
    """
124
 
    if (len(m) % 2) != 0:
125
 
        warning(u"Regular expressions cannot end with an odd number of '\\'. "
126
 
                "Dropping the final '\\'.")
127
 
        return m[:-1]
128
 
    return m
129
 
 
130
 
 
131
 
_sub_re = Replacer()
132
 
_sub_re.add(u'^RE:', u'')
133
 
_sub_re.add(u'\((?!\?)', u'(?:')
134
 
_sub_re.add(u'\(\?P<.*>', _invalid_regex(u'(?:'))
135
 
_sub_re.add(u'\(\?P=[^)]*\)', _invalid_regex(u''))
136
 
_sub_re.add(ur'\\+$', _trailing_backslashes_regex)
137
 
 
138
 
 
139
 
_sub_fullpath = Replacer()
140
 
_sub_fullpath.add(ur'^RE:.*', _sub_re) # RE:<anything> is a regex
141
 
_sub_fullpath.add(ur'\[\^?\]?(?:[^][]|\[:[^]]+:\])+\]', _sub_group) # char group
142
 
_sub_fullpath.add(ur'(?:(?<=/)|^)(?:\.?/)+', u'') # canonicalize path
143
 
_sub_fullpath.add(ur'\\.', ur'\&') # keep anything backslashed
144
 
_sub_fullpath.add(ur'[(){}|^$+.]', ur'\\&') # escape specials
145
 
_sub_fullpath.add(ur'(?:(?<=/)|^)\*\*+/', ur'(?:.*/)?') # **/ after ^ or /
146
 
_sub_fullpath.add(ur'\*+', ur'[^/]*') # * elsewhere
147
 
_sub_fullpath.add(ur'\?', ur'[^/]') # ? everywhere
148
 
 
149
 
 
150
 
_sub_basename = Replacer()
151
 
_sub_basename.add(ur'\[\^?\]?(?:[^][]|\[:[^]]+:\])+\]', _sub_group) # char group
152
 
_sub_basename.add(ur'\\.', ur'\&') # keep anything backslashed
153
 
_sub_basename.add(ur'[(){}|^$+.]', ur'\\&') # escape specials
154
 
_sub_basename.add(ur'\*+', ur'.*') # * everywhere
155
 
_sub_basename.add(ur'\?', ur'.') # ? everywhere
156
 
 
157
 
 
158
 
def _sub_extension(pattern):
159
 
    return _sub_basename(pattern[2:])
160
 
 
161
 
 
162
 
class Globster(object):
163
 
    """A simple wrapper for a set of glob patterns.
164
 
 
165
 
    Provides the capability to search the patterns to find a match for
166
 
    a given filename (including the full path).
167
 
 
168
 
    Patterns are translated to regular expressions to expidite matching.
169
 
 
170
 
    The regular expressions for multiple patterns are aggregated into
171
 
    a super-regex containing groups of up to 99 patterns.
172
 
    The 99 limitation is due to the grouping limit of the Python re module.
173
 
    The resulting super-regex and associated patterns are stored as a list of
174
 
    (regex,[patterns]) in _regex_patterns.
175
 
 
176
 
    For performance reasons the patterns are categorised as extension patterns
177
 
    (those that match against a file extension), basename patterns
178
 
    (those that match against the basename of the filename),
179
 
    and fullpath patterns (those that match against the full path).
180
 
    The translations used for extensions and basenames are relatively simpler
181
 
    and therefore faster to perform than the fullpath patterns.
182
 
 
183
 
    Also, the extension patterns are more likely to find a match and
184
 
    so are matched first, then the basename patterns, then the fullpath
185
 
    patterns.
186
 
    """
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
 
    def __init__(self, patterns):
209
 
        self._regex_patterns = []
210
 
        pattern_lists = {
211
 
            "extension" : [],
212
 
            "basename" : [],
213
 
            "fullpath" : [],
214
 
        }
215
 
        for pat in patterns:
216
 
            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"])
222
 
 
223
 
    def _add_patterns(self, patterns, translator, prefix=''):
224
 
        while patterns:
225
 
            grouped_rules = [
226
 
                '(%s)' % translator(pat) for pat in patterns[:99]]
227
 
            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),
232
 
                patterns[:99]))
233
 
            patterns = patterns[99:]
234
 
 
235
 
    def match(self, filename):
236
 
        """Searches for a pattern that matches the given filename.
237
 
 
238
 
        :return A matching pattern or None if there is no matching pattern.
239
 
        """
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
258
 
        return None
259
 
 
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
 
 
329
 
class _OrderedGlobster(Globster):
330
 
    """A Globster that keeps pattern order."""
331
 
 
332
 
    def __init__(self, patterns):
333
 
        """Constructor.
334
 
 
335
 
        :param patterns: sequence of glob patterns
336
 
        """
337
 
        # Note: This could be smarter by running like sequences together
338
 
        self._regex_patterns = []
339
 
        for pat in patterns:
340
 
            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'[\\/]+')
347
 
def normalize_pattern(pattern):
348
 
    """Converts backslashes in path patterns to forward slashes.
349
 
 
350
 
    Doesn't normalize regular expressions - they may contain escapes.
351
 
    """
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