summaryrefslogtreecommitdiff
path: root/bzrlib/globbing.py
blob: 547d971c397b2963bf3c0379e5f011e7bcea4172 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# Copyright (C) 2006-2011 Canonical Ltd

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

"""Tools for converting globs to regular expressions.

This module provides functions for converting shell-like globs to regular
expressions.
"""

from __future__ import absolute_import

import re

from bzrlib import (
    errors,
    lazy_regex,
    )
from bzrlib.trace import (
    mutter,
    warning,
    )


class Replacer(object):
    """Do a multiple-pattern substitution.

    The patterns and substitutions are combined into one, so the result of
    one replacement is never substituted again. Add the patterns and
    replacements via the add method and then call the object. The patterns
    must not contain capturing groups.
    """

    _expand = lazy_regex.lazy_compile(ur'\\&')

    def __init__(self, source=None):
        self._pat = None
        if source:
            self._pats = list(source._pats)
            self._funs = list(source._funs)
        else:
            self._pats = []
            self._funs = []

    def add(self, pat, fun):
        r"""Add a pattern and replacement.

        The pattern must not contain capturing groups.
        The replacement might be either a string template in which \& will be
        replaced with the match, or a function that will get the matching text
        as argument. It does not get match object, because capturing is
        forbidden anyway.
        """
        self._pat = None
        self._pats.append(pat)
        self._funs.append(fun)

    def add_replacer(self, replacer):
        r"""Add all patterns from another replacer.

        All patterns and replacements from replacer are appended to the ones
        already defined.
        """
        self._pat = None
        self._pats.extend(replacer._pats)
        self._funs.extend(replacer._funs)

    def __call__(self, text):
        if not self._pat:
            self._pat = lazy_regex.lazy_compile(
                    u'|'.join([u'(%s)' % p for p in self._pats]),
                    re.UNICODE)
        return self._pat.sub(self._do_sub, text)

    def _do_sub(self, m):
        fun = self._funs[m.lastindex - 1]
        if hasattr(fun, '__call__'):
            return fun(m.group(0))
        else:
            return self._expand.sub(m.group(0), fun)


_sub_named = Replacer()
_sub_named.add(ur'\[:digit:\]', ur'\d')
_sub_named.add(ur'\[:space:\]', ur'\s')
_sub_named.add(ur'\[:alnum:\]', ur'\w')
_sub_named.add(ur'\[:ascii:\]', ur'\0-\x7f')
_sub_named.add(ur'\[:blank:\]', ur' \t')
_sub_named.add(ur'\[:cntrl:\]', ur'\0-\x1f\x7f-\x9f')


def _sub_group(m):
    if m[1] in (u'!', u'^'):
        return u'[^' + _sub_named(m[2:-1]) + u']'
    return u'[' + _sub_named(m[1:-1]) + u']'


def _invalid_regex(repl):
    def _(m):
        warning(u"'%s' not allowed within a regular expression. "
                "Replacing with '%s'" % (m, repl))
        return repl
    return _


def _trailing_backslashes_regex(m):
    """Check trailing backslashes.

    Does a head count on trailing backslashes to ensure there isn't an odd
    one on the end that would escape the brackets we wrap the RE in.
    """
    if (len(m) % 2) != 0:
        warning(u"Regular expressions cannot end with an odd number of '\\'. "
                "Dropping the final '\\'.")
        return m[:-1]
    return m


_sub_re = Replacer()
_sub_re.add(u'^RE:', u'')
_sub_re.add(u'\((?!\?)', u'(?:')
_sub_re.add(u'\(\?P<.*>', _invalid_regex(u'(?:'))
_sub_re.add(u'\(\?P=[^)]*\)', _invalid_regex(u''))
_sub_re.add(ur'\\+$', _trailing_backslashes_regex)


_sub_fullpath = Replacer()
_sub_fullpath.add(ur'^RE:.*', _sub_re) # RE:<anything> is a regex
_sub_fullpath.add(ur'\[\^?\]?(?:[^][]|\[:[^]]+:\])+\]', _sub_group) # char group
_sub_fullpath.add(ur'(?:(?<=/)|^)(?:\.?/)+', u'') # canonicalize path
_sub_fullpath.add(ur'\\.', ur'\&') # keep anything backslashed
_sub_fullpath.add(ur'[(){}|^$+.]', ur'\\&') # escape specials
_sub_fullpath.add(ur'(?:(?<=/)|^)\*\*+/', ur'(?:.*/)?') # **/ after ^ or /
_sub_fullpath.add(ur'\*+', ur'[^/]*') # * elsewhere
_sub_fullpath.add(ur'\?', ur'[^/]') # ? everywhere


_sub_basename = Replacer()
_sub_basename.add(ur'\[\^?\]?(?:[^][]|\[:[^]]+:\])+\]', _sub_group) # char group
_sub_basename.add(ur'\\.', ur'\&') # keep anything backslashed
_sub_basename.add(ur'[(){}|^$+.]', ur'\\&') # escape specials
_sub_basename.add(ur'\*+', ur'.*') # * everywhere
_sub_basename.add(ur'\?', ur'.') # ? everywhere


def _sub_extension(pattern):
    return _sub_basename(pattern[2:])


class Globster(object):
    """A simple wrapper for a set of glob patterns.

    Provides the capability to search the patterns to find a match for
    a given filename (including the full path).

    Patterns are translated to regular expressions to expidite matching.

    The regular expressions for multiple patterns are aggregated into
    a super-regex containing groups of up to 99 patterns.
    The 99 limitation is due to the grouping limit of the Python re module.
    The resulting super-regex and associated patterns are stored as a list of
    (regex,[patterns]) in _regex_patterns.

    For performance reasons the patterns are categorised as extension patterns
    (those that match against a file extension), basename patterns
    (those that match against the basename of the filename),
    and fullpath patterns (those that match against the full path).
    The translations used for extensions and basenames are relatively simpler
    and therefore faster to perform than the fullpath patterns.

    Also, the extension patterns are more likely to find a match and
    so are matched first, then the basename patterns, then the fullpath
    patterns.
    """
    # We want to _add_patterns in a specific order (as per type_list below)
    # starting with the shortest and going to the longest.
    # As some Python version don't support ordered dicts the list below is
    # used to select inputs for _add_pattern in a specific order.
    pattern_types = [ "extension", "basename", "fullpath" ]

    pattern_info = {
        "extension" : {
            "translator" : _sub_extension,
            "prefix" : r'(?:.*/)?(?!.*/)(?:.*\.)'
        },
        "basename" : {
            "translator" : _sub_basename,
            "prefix" : r'(?:.*/)?(?!.*/)'
        },
        "fullpath" : {
            "translator" : _sub_fullpath,
            "prefix" : r''
        },
    }

    def __init__(self, patterns):
        self._regex_patterns = []
        pattern_lists = {
            "extension" : [],
            "basename" : [],
            "fullpath" : [],
        }
        for pat in patterns:
            pat = normalize_pattern(pat)
            pattern_lists[Globster.identify(pat)].append(pat)
        pi = Globster.pattern_info
        for t in Globster.pattern_types:
            self._add_patterns(pattern_lists[t], pi[t]["translator"],
                pi[t]["prefix"])

    def _add_patterns(self, patterns, translator, prefix=''):
        while patterns:
            grouped_rules = [
                '(%s)' % translator(pat) for pat in patterns[:99]]
            joined_rule = '%s(?:%s)$' % (prefix, '|'.join(grouped_rules))
            # Explicitly use lazy_compile here, because we count on its
            # nicer error reporting.
            self._regex_patterns.append((
                lazy_regex.lazy_compile(joined_rule, re.UNICODE),
                patterns[:99]))
            patterns = patterns[99:]

    def match(self, filename):
        """Searches for a pattern that matches the given filename.

        :return A matching pattern or None if there is no matching pattern.
        """
        try:
            for regex, patterns in self._regex_patterns:
                match = regex.match(filename)
                if match:
                    return patterns[match.lastindex -1]
        except errors.InvalidPattern, e:
            # We can't show the default e.msg to the user as thats for
            # the combined pattern we sent to regex. Instead we indicate to
            # the user that an ignore file needs fixing.
            mutter('Invalid pattern found in regex: %s.', e.msg)
            e.msg = "File ~/.bazaar/ignore or .bzrignore contains error(s)."
            bad_patterns = ''
            for _, patterns in self._regex_patterns:
                for p in patterns:
                    if not Globster.is_pattern_valid(p):
                        bad_patterns += ('\n  %s' % p)
            e.msg += bad_patterns
            raise e
        return None

    @staticmethod
    def identify(pattern):
        """Returns pattern category.

        :param pattern: normalized pattern.
        Identify if a pattern is fullpath, basename or extension
        and returns the appropriate type.
        """
        if pattern.startswith(u'RE:') or u'/' in pattern:
            return "fullpath"
        elif pattern.startswith(u'*.'):
            return "extension"
        else:
            return "basename"

    @staticmethod
    def is_pattern_valid(pattern):
        """Returns True if pattern is valid.

        :param pattern: Normalized pattern.
        is_pattern_valid() assumes pattern to be normalized.
        see: globbing.normalize_pattern
        """
        result = True
        translator = Globster.pattern_info[Globster.identify(pattern)]["translator"]
        tpattern = '(%s)' % translator(pattern)
        try:
            re_obj = lazy_regex.lazy_compile(tpattern, re.UNICODE)
            re_obj.search("") # force compile
        except errors.InvalidPattern, e:
            result = False
        return result


class ExceptionGlobster(object):
    """A Globster that supports exception patterns.
    
    Exceptions are ignore patterns prefixed with '!'.  Exception
    patterns take precedence over regular patterns and cause a 
    matching filename to return None from the match() function.  
    Patterns using a '!!' prefix are highest precedence, and act 
    as regular ignores. '!!' patterns are useful to establish ignores
    that apply under paths specified by '!' exception patterns.
    """
    
    def __init__(self,patterns):
        ignores = [[], [], []]
        for p in patterns:
            if p.startswith(u'!!'):
                ignores[2].append(p[2:])
            elif p.startswith(u'!'):
                ignores[1].append(p[1:])
            else:
                ignores[0].append(p)
        self._ignores = [Globster(i) for i in ignores]
        
    def match(self, filename):
        """Searches for a pattern that matches the given filename.

        :return A matching pattern or None if there is no matching pattern.
        """
        double_neg = self._ignores[2].match(filename)
        if double_neg:
            return "!!%s" % double_neg
        elif self._ignores[1].match(filename):
            return None
        else:
            return self._ignores[0].match(filename)

class _OrderedGlobster(Globster):
    """A Globster that keeps pattern order."""

    def __init__(self, patterns):
        """Constructor.

        :param patterns: sequence of glob patterns
        """
        # Note: This could be smarter by running like sequences together
        self._regex_patterns = []
        for pat in patterns:
            pat = normalize_pattern(pat)
            t = Globster.identify(pat)
            self._add_patterns([pat], Globster.pattern_info[t]["translator"],
                Globster.pattern_info[t]["prefix"])


_slashes = lazy_regex.lazy_compile(r'[\\/]+')
def normalize_pattern(pattern):
    """Converts backslashes in path patterns to forward slashes.

    Doesn't normalize regular expressions - they may contain escapes.
    """
    if not (pattern.startswith('RE:') or pattern.startswith('!RE:')):
        pattern = _slashes.sub('/', pattern)
    if len(pattern) > 1:
        pattern = pattern.rstrip('/')
    return pattern