/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/globbing.py

  • Committer: Robert Collins
  • Date: 2010-05-06 11:08:10 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506110810-h3j07fh5gmw54s25
Cleaner matcher matching revised unlocking protocol.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006 Canonical Ltd
 
1
# Copyright (C) 2006-2010 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
 
52
52
 
53
53
        The pattern must not contain capturing groups.
54
54
        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 
 
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
57
57
        forbidden anyway.
58
58
        """
59
59
        self._pat = None
108
108
    return _
109
109
 
110
110
 
 
111
def _trailing_backslashes_regex(m):
 
112
    """Check trailing backslashes.
 
113
 
 
114
    Does a head count on trailing backslashes to ensure there isn't an odd
 
115
    one on the end that would escape the brackets we wrap the RE in.
 
116
    """
 
117
    if (len(m) % 2) != 0:
 
118
        warning(u"Regular expressions cannot end with an odd number of '\\'. "
 
119
                "Dropping the final '\\'.")
 
120
        return m[:-1]
 
121
    return m
 
122
 
 
123
 
111
124
_sub_re = Replacer()
112
125
_sub_re.add(u'^RE:', u'')
113
126
_sub_re.add(u'\((?!\?)', u'(?:')
114
127
_sub_re.add(u'\(\?P<.*>', _invalid_regex(u'(?:'))
115
128
_sub_re.add(u'\(\?P=[^)]*\)', _invalid_regex(u''))
 
129
_sub_re.add(ur'\\+$', _trailing_backslashes_regex)
116
130
 
117
131
 
118
132
_sub_fullpath = Replacer()
146
160
 
147
161
    Patterns are translated to regular expressions to expidite matching.
148
162
 
149
 
    The regular expressions for multiple patterns are aggregated into 
150
 
    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.
151
165
    The 99 limitation is due to the grouping limit of the Python re module.
152
166
    The resulting super-regex and associated patterns are stored as a list of
153
167
    (regex,[patterns]) in _regex_patterns.
154
 
    
 
168
 
155
169
    For performance reasons the patterns are categorised as extension patterns
156
170
    (those that match against a file extension), basename patterns
157
171
    (those that match against the basename of the filename),
158
172
    and fullpath patterns (those that match against the full path).
159
 
    The translations used for extensions and basenames are relatively simpler 
 
173
    The translations used for extensions and basenames are relatively simpler
160
174
    and therefore faster to perform than the fullpath patterns.
161
175
 
162
 
    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
163
177
    so are matched first, then the basename patterns, then the fullpath
164
178
    patterns.
165
179
    """
169
183
        base_patterns = []
170
184
        ext_patterns = []
171
185
        for pat in patterns:
 
186
            pat = normalize_pattern(pat)
172
187
            if pat.startswith(u'RE:') or u'/' in pat:
173
188
                path_patterns.append(pat)
174
189
            elif pat.startswith(u'*.'):
177
192
                base_patterns.append(pat)
178
193
        self._add_patterns(ext_patterns,_sub_extension,
179
194
            prefix=r'(?:.*/)?(?!.*/)(?:.*\.)')
180
 
        self._add_patterns(base_patterns,_sub_basename, 
 
195
        self._add_patterns(base_patterns,_sub_basename,
181
196
            prefix=r'(?:.*/)?(?!.*/)')
182
 
        self._add_patterns(path_patterns,_sub_fullpath) 
 
197
        self._add_patterns(path_patterns,_sub_fullpath)
183
198
 
184
199
    def _add_patterns(self, patterns, translator, prefix=''):
185
200
        while patterns:
186
201
            grouped_rules = ['(%s)' % translator(pat) for pat in patterns[:99]]
187
202
            joined_rule = '%s(?:%s)$' % (prefix, '|'.join(grouped_rules))
188
 
            self._regex_patterns.append((re.compile(joined_rule, re.UNICODE), 
 
203
            self._regex_patterns.append((re.compile(joined_rule, re.UNICODE),
189
204
                patterns[:99]))
190
205
            patterns = patterns[99:]
191
206
 
192
207
    def match(self, filename):
193
208
        """Searches for a pattern that matches the given filename.
194
 
        
 
209
 
195
210
        :return A matching pattern or None if there is no matching pattern.
196
211
        """
197
212
        for regex, patterns in self._regex_patterns:
199
214
            if match:
200
215
                return patterns[match.lastindex -1]
201
216
        return None
 
217
 
 
218
class ExceptionGlobster(object):
 
219
    """A Globster that supports exception patterns.
 
220
    
 
221
    Exceptions are ignore patterns prefixed with '!'.  Exception
 
222
    patterns take precedence over regular patterns and cause a 
 
223
    matching filename to return None from the match() function.  
 
224
    Patterns using a '!!' prefix are highest precedence, and act 
 
225
    as regular ignores. '!!' patterns are useful to establish ignores
 
226
    that apply under paths specified by '!' exception patterns.
 
227
    """
 
228
    
 
229
    def __init__(self,patterns):
 
230
        ignores = [[], [], []]
 
231
        for p in patterns:
 
232
            if p.startswith(u'!!'):
 
233
                ignores[2].append(p[2:])
 
234
            elif p.startswith(u'!'):
 
235
                ignores[1].append(p[1:])
 
236
            else:
 
237
                ignores[0].append(p)
 
238
        self._ignores = [Globster(i) for i in ignores]
202
239
        
 
240
    def match(self, filename):
 
241
        """Searches for a pattern that matches the given filename.
 
242
 
 
243
        :return A matching pattern or None if there is no matching pattern.
 
244
        """
 
245
        double_neg = self._ignores[2].match(filename)
 
246
        if double_neg:
 
247
            return "!!%s" % double_neg
 
248
        elif self._ignores[1].match(filename):
 
249
            return None
 
250
        else:
 
251
            return self._ignores[0].match(filename)
 
252
 
 
253
class _OrderedGlobster(Globster):
 
254
    """A Globster that keeps pattern order."""
 
255
 
 
256
    def __init__(self, patterns):
 
257
        """Constructor.
 
258
 
 
259
        :param patterns: sequence of glob patterns
 
260
        """
 
261
        # Note: This could be smarter by running like sequences together
 
262
        self._regex_patterns = []
 
263
        for pat in patterns:
 
264
            pat = normalize_pattern(pat)
 
265
            if pat.startswith(u'RE:') or u'/' in pat:
 
266
                self._add_patterns([pat], _sub_fullpath)
 
267
            elif pat.startswith(u'*.'):
 
268
                self._add_patterns([pat], _sub_extension,
 
269
                    prefix=r'(?:.*/)?(?!.*/)(?:.*\.)')
 
270
            else:
 
271
                self._add_patterns([pat], _sub_basename,
 
272
                    prefix=r'(?:.*/)?(?!.*/)')
 
273
 
 
274
 
 
275
_slashes = re.compile(r'[\\/]+')
 
276
def normalize_pattern(pattern):
 
277
    """Converts backslashes in path patterns to forward slashes.
 
278
 
 
279
    Doesn't normalize regular expressions - they may contain escapes.
 
280
    """
 
281
    if not (pattern.startswith('RE:') or pattern.startswith('!RE:')):
 
282
        pattern = _slashes.sub('/', pattern)
 
283
    if len(pattern) > 1:
 
284
        pattern = pattern.rstrip('/')
 
285
    return pattern