~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/globbing.py

  • Committer: Jelmer Vernooij
  • Date: 2015-11-15 02:30:05 UTC
  • mto: This revision was merged to the branch mainline in revision 6609.
  • Revision ID: jelmer@jelmer.uk-20151115023005-fcfi763b5eu1ne2o
Fix auodoc_rstx when running with LANG=C.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006 Canonical Ltd
 
1
# Copyright (C) 2006-2011 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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
 
23
25
import re
24
26
 
 
27
from bzrlib import (
 
28
    errors,
 
29
    lazy_regex,
 
30
    )
25
31
from bzrlib.trace import (
26
 
    warning
 
32
    mutter,
 
33
    warning,
27
34
    )
28
35
 
29
36
 
36
43
    must not contain capturing groups.
37
44
    """
38
45
 
39
 
    _expand = re.compile(ur'\\&')
 
46
    _expand = lazy_regex.lazy_compile(ur'\\&')
40
47
 
41
48
    def __init__(self, source=None):
42
49
        self._pat = None
52
59
 
53
60
        The pattern must not contain capturing groups.
54
61
        The replacement might be either a string template in which \& will be
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 
 
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
57
64
        forbidden anyway.
58
65
        """
59
66
        self._pat = None
72
79
 
73
80
    def __call__(self, text):
74
81
        if not self._pat:
75
 
            self._pat = re.compile(
 
82
            self._pat = lazy_regex.lazy_compile(
76
83
                    u'|'.join([u'(%s)' % p for p in self._pats]),
77
84
                    re.UNICODE)
78
85
        return self._pat.sub(self._do_sub, text)
108
115
    return _
109
116
 
110
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
 
111
131
_sub_re = Replacer()
112
132
_sub_re.add(u'^RE:', u'')
113
133
_sub_re.add(u'\((?!\?)', u'(?:')
114
134
_sub_re.add(u'\(\?P<.*>', _invalid_regex(u'(?:'))
115
135
_sub_re.add(u'\(\?P=[^)]*\)', _invalid_regex(u''))
 
136
_sub_re.add(ur'\\+$', _trailing_backslashes_regex)
116
137
 
117
138
 
118
139
_sub_fullpath = Replacer()
146
167
 
147
168
    Patterns are translated to regular expressions to expidite matching.
148
169
 
149
 
    The regular expressions for multiple patterns are aggregated into 
150
 
    a super-regex containing groups of up to 99 patterns.  
 
170
    The regular expressions for multiple patterns are aggregated into
 
171
    a super-regex containing groups of up to 99 patterns.
151
172
    The 99 limitation is due to the grouping limit of the Python re module.
152
173
    The resulting super-regex and associated patterns are stored as a list of
153
174
    (regex,[patterns]) in _regex_patterns.
154
 
    
 
175
 
155
176
    For performance reasons the patterns are categorised as extension patterns
156
177
    (those that match against a file extension), basename patterns
157
178
    (those that match against the basename of the filename),
158
179
    and fullpath patterns (those that match against the full path).
159
 
    The translations used for extensions and basenames are relatively simpler 
 
180
    The translations used for extensions and basenames are relatively simpler
160
181
    and therefore faster to perform than the fullpath patterns.
161
182
 
162
 
    Also, the extension patterns are more likely to find a match and 
 
183
    Also, the extension patterns are more likely to find a match and
163
184
    so are matched first, then the basename patterns, then the fullpath
164
185
    patterns.
165
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
 
166
208
    def __init__(self, patterns):
167
209
        self._regex_patterns = []
168
 
        path_patterns = []
169
 
        base_patterns = []
170
 
        ext_patterns = []
 
210
        pattern_lists = {
 
211
            "extension" : [],
 
212
            "basename" : [],
 
213
            "fullpath" : [],
 
214
        }
171
215
        for pat in patterns:
172
 
            if pat.startswith(u'RE:') or u'/' in pat:
173
 
                path_patterns.append(pat)
174
 
            elif pat.startswith(u'*.'):
175
 
                ext_patterns.append(pat)
176
 
            else:
177
 
                base_patterns.append(pat)
178
 
        self._add_patterns(ext_patterns,_sub_extension,
179
 
            prefix=r'(?:.*/)?(?!.*/)(?:.*\.)')
180
 
        self._add_patterns(base_patterns,_sub_basename, 
181
 
            prefix=r'(?:.*/)?(?!.*/)')
182
 
        self._add_patterns(path_patterns,_sub_fullpath) 
 
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"])
183
222
 
184
223
    def _add_patterns(self, patterns, translator, prefix=''):
185
224
        while patterns:
186
 
            grouped_rules = ['(%s)' % translator(pat) for pat in patterns[:99]]
 
225
            grouped_rules = [
 
226
                '(%s)' % translator(pat) for pat in patterns[:99]]
187
227
            joined_rule = '%s(?:%s)$' % (prefix, '|'.join(grouped_rules))
188
 
            self._regex_patterns.append((re.compile(joined_rule, re.UNICODE), 
 
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),
189
232
                patterns[:99]))
190
233
            patterns = patterns[99:]
191
234
 
192
235
    def match(self, filename):
193
236
        """Searches for a pattern that matches the given filename.
194
 
        
 
237
 
195
238
        :return A matching pattern or None if there is no matching pattern.
196
239
        """
197
 
        for regex, patterns in self._regex_patterns:
198
 
            match = regex.match(filename)
199
 
            if match:
200
 
                return patterns[match.lastindex -1]
 
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
201
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]
202
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