~bzr-pqm/bzr/bzr.dev

5967.9.3 by Martin Pool
Explicitly use lazy_regexp where we count on its error reporting behaviour
1
# Copyright (C) 2006-2011 Canonical Ltd
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
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
6379.6.7 by Jelmer Vernooij
Move importing from future until after doc string, otherwise the doc string will disappear.
23
from __future__ import absolute_import
24
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
25
import re
26
5967.9.3 by Martin Pool
Explicitly use lazy_regexp where we count on its error reporting behaviour
27
from bzrlib import (
28
    errors,
29
    lazy_regex,
30
    )
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
31
from bzrlib.trace import (
5326.2.7 by Parth Malwankar
Globster now mutters regex failure message before changing message
32
    mutter,
5326.2.1 by Parth Malwankar
added InvalidPattern error.
33
    warning,
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
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
5967.9.5 by Martin Pool
More explicit laziness
46
    _expand = lazy_regex.lazy_compile(ur'\\&')
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
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
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
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
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
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:
5967.9.5 by Martin Pool
More explicit laziness
82
            self._pat = lazy_regex.lazy_compile(
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
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):
2135.2.7 by Kent Gibson
Implement JAM's review suggestions.
112
        warning(u"'%s' not allowed within a regular expression. "
113
                "Replacing with '%s'" % (m, repl))
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
114
        return repl
115
    return _
116
117
2298.8.1 by Kent Gibson
Normalise ignore patterns to use '/' path separator.
118
def _trailing_backslashes_regex(m):
2298.8.2 by Kent Gibson
Review fixes for lp86451 patch.
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:
2298.8.1 by Kent Gibson
Normalise ignore patterns to use '/' path separator.
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
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
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''))
2298.8.1 by Kent Gibson
Normalise ignore patterns to use '/' path separator.
136
_sub_re.add(ur'\\+$', _trailing_backslashes_regex)
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
137
138
2135.2.2 by Kent Gibson
Ignore pattern matcher (glob.py) patches:
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:])
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
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
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
170
    The regular expressions for multiple patterns are aggregated into
171
    a super-regex containing groups of up to 99 patterns.
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
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.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
175
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
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).
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
180
    The translations used for extensions and basenames are relatively simpler
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
181
    and therefore faster to perform than the fullpath patterns.
182
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
183
    Also, the extension patterns are more likely to find a match and
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
184
    so are matched first, then the basename patterns, then the fullpath
185
    patterns.
186
    """
5050.14.2 by Parth Malwankar
_add_patterns is now done in a specific order in Globster
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.
5050.14.3 by Parth Malwankar
use dict for managining pattern information
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
        },
5339.3.1 by Parth Malwankar
'bzr ignore' now fails on bad pattern.
206
    }
207
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
208
    def __init__(self, patterns):
209
        self._regex_patterns = []
5339.3.1 by Parth Malwankar
'bzr ignore' now fails on bad pattern.
210
        pattern_lists = {
5050.14.3 by Parth Malwankar
use dict for managining pattern information
211
            "extension" : [],
212
            "basename" : [],
213
            "fullpath" : [],
5339.3.1 by Parth Malwankar
'bzr ignore' now fails on bad pattern.
214
        }
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
215
        for pat in patterns:
2298.8.1 by Kent Gibson
Normalise ignore patterns to use '/' path separator.
216
            pat = normalize_pattern(pat)
5339.3.1 by Parth Malwankar
'bzr ignore' now fails on bad pattern.
217
            pattern_lists[Globster.identify(pat)].append(pat)
5050.14.3 by Parth Malwankar
use dict for managining pattern information
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"])
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
222
223
    def _add_patterns(self, patterns, translator, prefix=''):
224
        while patterns:
5967.9.3 by Martin Pool
Explicitly use lazy_regexp where we count on its error reporting behaviour
225
            grouped_rules = [
226
                '(%s)' % translator(pat) for pat in patterns[:99]]
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
227
            joined_rule = '%s(?:%s)$' % (prefix, '|'.join(grouped_rules))
5967.9.3 by Martin Pool
Explicitly use lazy_regexp where we count on its error reporting behaviour
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),
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
232
                patterns[:99]))
233
            patterns = patterns[99:]
234
235
    def match(self, filename):
236
        """Searches for a pattern that matches the given filename.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
237
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
238
        :return A matching pattern or None if there is no matching pattern.
239
        """
5326.2.1 by Parth Malwankar
added InvalidPattern error.
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:
5339.1.1 by Parth Malwankar
fixes errors.InvalidPattern to work on Python2.5
246
            # We can't show the default e.msg to the user as thats for
5326.2.1 by Parth Malwankar
added InvalidPattern error.
247
            # the combined pattern we sent to regex. Instead we indicate to
248
            # the user that an ignore file needs fixing.
5339.1.1 by Parth Malwankar
fixes errors.InvalidPattern to work on Python2.5
249
            mutter('Invalid pattern found in regex: %s.', e.msg)
5050.14.1 by Parth Malwankar
'bzr ignore' now fails on bad patterns. failing patterns are displayed.
250
            e.msg = "File ~/.bazaar/ignore or .bzrignore contains error(s)."
5339.3.2 by Parth Malwankar
Globster now prints specific patterns that are bad.
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)
5050.14.1 by Parth Malwankar
'bzr ignore' now fails on bad patterns. failing patterns are displayed.
256
            e.msg += bad_patterns
5326.2.1 by Parth Malwankar
added InvalidPattern error.
257
            raise e
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
258
        return None
3398.1.1 by Ian Clatworthy
simplify the custom Globster to only care about ordering
259
5339.3.1 by Parth Malwankar
'bzr ignore' now fails on bad pattern.
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:
5050.14.3 by Parth Malwankar
use dict for managining pattern information
269
            return "fullpath"
5339.3.1 by Parth Malwankar
'bzr ignore' now fails on bad pattern.
270
        elif pattern.startswith(u'*.'):
5050.14.3 by Parth Malwankar
use dict for managining pattern information
271
            return "extension"
5339.3.1 by Parth Malwankar
'bzr ignore' now fails on bad pattern.
272
        else:
5050.14.3 by Parth Malwankar
use dict for managining pattern information
273
            return "basename"
5339.3.1 by Parth Malwankar
'bzr ignore' now fails on bad pattern.
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
5050.14.3 by Parth Malwankar
use dict for managining pattern information
284
        translator = Globster.pattern_info[Globster.identify(pattern)]["translator"]
5339.3.1 by Parth Malwankar
'bzr ignore' now fails on bad pattern.
285
        tpattern = '(%s)' % translator(pattern)
286
        try:
5967.9.5 by Martin Pool
More explicit laziness
287
            re_obj = lazy_regex.lazy_compile(tpattern, re.UNICODE)
5339.3.1 by Parth Malwankar
'bzr ignore' now fails on bad pattern.
288
            re_obj.search("") # force compile
289
        except errors.InvalidPattern, e:
290
            result = False
291
        return result
292
293
4948.5.7 by John Whitley
Terminology change: exclusion => exception.
294
class ExceptionGlobster(object):
295
    """A Globster that supports exception patterns.
4948.5.5 by John Whitley
Add descriptive text to ExcludingGlobster.
296
    
4948.5.7 by John Whitley
Terminology change: exclusion => exception.
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.
4948.5.5 by John Whitley
Add descriptive text to ExcludingGlobster.
303
    """
4948.5.3 by John Whitley
Refactor the exclusion handling functionality out of
304
    
305
    def __init__(self,patterns):
4948.5.7 by John Whitley
Terminology change: exclusion => exception.
306
        ignores = [[], [], []]
4948.5.3 by John Whitley
Refactor the exclusion handling functionality out of
307
        for p in patterns:
4948.5.6 by John Whitley
A trial implementation of '!!' syntax for double-negative ignore exclusions.
308
            if p.startswith(u'!!'):
4948.5.7 by John Whitley
Terminology change: exclusion => exception.
309
                ignores[2].append(p[2:])
4948.5.6 by John Whitley
A trial implementation of '!!' syntax for double-negative ignore exclusions.
310
            elif p.startswith(u'!'):
4948.5.7 by John Whitley
Terminology change: exclusion => exception.
311
                ignores[1].append(p[1:])
4948.5.3 by John Whitley
Refactor the exclusion handling functionality out of
312
            else:
4948.5.7 by John Whitley
Terminology change: exclusion => exception.
313
                ignores[0].append(p)
314
        self._ignores = [Globster(i) for i in ignores]
4948.5.3 by John Whitley
Refactor the exclusion handling functionality out of
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
        """
4948.5.7 by John Whitley
Terminology change: exclusion => exception.
321
        double_neg = self._ignores[2].match(filename)
4948.5.6 by John Whitley
A trial implementation of '!!' syntax for double-negative ignore exclusions.
322
        if double_neg:
323
            return "!!%s" % double_neg
4948.5.7 by John Whitley
Terminology change: exclusion => exception.
324
        elif self._ignores[1].match(filename):
4948.5.3 by John Whitley
Refactor the exclusion handling functionality out of
325
            return None
326
        else:
4948.5.7 by John Whitley
Terminology change: exclusion => exception.
327
            return self._ignores[0].match(filename)
3398.1.1 by Ian Clatworthy
simplify the custom Globster to only care about ordering
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)
5050.14.3 by Parth Malwankar
use dict for managining pattern information
341
            t = Globster.identify(pat)
342
            self._add_patterns([pat], Globster.pattern_info[t]["translator"],
343
                Globster.pattern_info[t]["prefix"])
3398.1.1 by Ian Clatworthy
simplify the custom Globster to only care about ordering
344
2298.8.1 by Kent Gibson
Normalise ignore patterns to use '/' path separator.
345
5967.9.5 by Martin Pool
More explicit laziness
346
_slashes = lazy_regex.lazy_compile(r'[\\/]+')
2298.8.1 by Kent Gibson
Normalise ignore patterns to use '/' path separator.
347
def normalize_pattern(pattern):
348
    """Converts backslashes in path patterns to forward slashes.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
349
2298.8.2 by Kent Gibson
Review fixes for lp86451 patch.
350
    Doesn't normalize regular expressions - they may contain escapes.
2298.8.1 by Kent Gibson
Normalise ignore patterns to use '/' path separator.
351
    """
4948.5.4 by John Whitley
bzrlib.globbing.normalize_pattern needed fix to avoid mangling ignore
352
    if not (pattern.startswith('RE:') or pattern.startswith('!RE:')):
4792.4.1 by Gordon Tyler
Fixed globbing.normalize_pattern to not strip '/' down to '' and normalize multiple slashes.
353
        pattern = _slashes.sub('/', pattern)
354
    if len(pattern) > 1:
355
        pattern = pattern.rstrip('/')
356
    return pattern