1
# Copyright (C) 2006-2010 Canonical Ltd
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.
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.
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
17
"""Tools for converting globs to regular expressions.
19
This module provides functions for converting shell-like globs to regular
25
from bzrlib import errors
26
from bzrlib.trace import (
32
class Replacer(object):
33
"""Do a multiple-pattern substitution.
35
The patterns and substitutions are combined into one, so the result of
36
one replacement is never substituted again. Add the patterns and
37
replacements via the add method and then call the object. The patterns
38
must not contain capturing groups.
41
_expand = re.compile(ur'\\&')
43
def __init__(self, source=None):
46
self._pats = list(source._pats)
47
self._funs = list(source._funs)
52
def add(self, pat, fun):
53
r"""Add a pattern and replacement.
55
The pattern must not contain capturing groups.
56
The replacement might be either a string template in which \& will be
57
replaced with the match, or a function that will get the matching text
58
as argument. It does not get match object, because capturing is
62
self._pats.append(pat)
63
self._funs.append(fun)
65
def add_replacer(self, replacer):
66
r"""Add all patterns from another replacer.
68
All patterns and replacements from replacer are appended to the ones
72
self._pats.extend(replacer._pats)
73
self._funs.extend(replacer._funs)
75
def __call__(self, text):
77
self._pat = re.compile(
78
u'|'.join([u'(%s)' % p for p in self._pats]),
80
return self._pat.sub(self._do_sub, text)
83
fun = self._funs[m.lastindex - 1]
84
if hasattr(fun, '__call__'):
85
return fun(m.group(0))
87
return self._expand.sub(m.group(0), fun)
90
_sub_named = Replacer()
91
_sub_named.add(ur'\[:digit:\]', ur'\d')
92
_sub_named.add(ur'\[:space:\]', ur'\s')
93
_sub_named.add(ur'\[:alnum:\]', ur'\w')
94
_sub_named.add(ur'\[:ascii:\]', ur'\0-\x7f')
95
_sub_named.add(ur'\[:blank:\]', ur' \t')
96
_sub_named.add(ur'\[:cntrl:\]', ur'\0-\x1f\x7f-\x9f')
100
if m[1] in (u'!', u'^'):
101
return u'[^' + _sub_named(m[2:-1]) + u']'
102
return u'[' + _sub_named(m[1:-1]) + u']'
105
def _invalid_regex(repl):
107
warning(u"'%s' not allowed within a regular expression. "
108
"Replacing with '%s'" % (m, repl))
113
def _trailing_backslashes_regex(m):
114
"""Check trailing backslashes.
116
Does a head count on trailing backslashes to ensure there isn't an odd
117
one on the end that would escape the brackets we wrap the RE in.
119
if (len(m) % 2) != 0:
120
warning(u"Regular expressions cannot end with an odd number of '\\'. "
121
"Dropping the final '\\'.")
127
_sub_re.add(u'^RE:', u'')
128
_sub_re.add(u'\((?!\?)', u'(?:')
129
_sub_re.add(u'\(\?P<.*>', _invalid_regex(u'(?:'))
130
_sub_re.add(u'\(\?P=[^)]*\)', _invalid_regex(u''))
131
_sub_re.add(ur'\\+$', _trailing_backslashes_regex)
134
_sub_fullpath = Replacer()
135
_sub_fullpath.add(ur'^RE:.*', _sub_re) # RE:<anything> is a regex
136
_sub_fullpath.add(ur'\[\^?\]?(?:[^][]|\[:[^]]+:\])+\]', _sub_group) # char group
137
_sub_fullpath.add(ur'(?:(?<=/)|^)(?:\.?/)+', u'') # canonicalize path
138
_sub_fullpath.add(ur'\\.', ur'\&') # keep anything backslashed
139
_sub_fullpath.add(ur'[(){}|^$+.]', ur'\\&') # escape specials
140
_sub_fullpath.add(ur'(?:(?<=/)|^)\*\*+/', ur'(?:.*/)?') # **/ after ^ or /
141
_sub_fullpath.add(ur'\*+', ur'[^/]*') # * elsewhere
142
_sub_fullpath.add(ur'\?', ur'[^/]') # ? everywhere
145
_sub_basename = Replacer()
146
_sub_basename.add(ur'\[\^?\]?(?:[^][]|\[:[^]]+:\])+\]', _sub_group) # char group
147
_sub_basename.add(ur'\\.', ur'\&') # keep anything backslashed
148
_sub_basename.add(ur'[(){}|^$+.]', ur'\\&') # escape specials
149
_sub_basename.add(ur'\*+', ur'.*') # * everywhere
150
_sub_basename.add(ur'\?', ur'.') # ? everywhere
153
def _sub_extension(pattern):
154
return _sub_basename(pattern[2:])
157
class Globster(object):
158
"""A simple wrapper for a set of glob patterns.
160
Provides the capability to search the patterns to find a match for
161
a given filename (including the full path).
163
Patterns are translated to regular expressions to expidite matching.
165
The regular expressions for multiple patterns are aggregated into
166
a super-regex containing groups of up to 99 patterns.
167
The 99 limitation is due to the grouping limit of the Python re module.
168
The resulting super-regex and associated patterns are stored as a list of
169
(regex,[patterns]) in _regex_patterns.
171
For performance reasons the patterns are categorised as extension patterns
172
(those that match against a file extension), basename patterns
173
(those that match against the basename of the filename),
174
and fullpath patterns (those that match against the full path).
175
The translations used for extensions and basenames are relatively simpler
176
and therefore faster to perform than the fullpath patterns.
178
Also, the extension patterns are more likely to find a match and
179
so are matched first, then the basename patterns, then the fullpath
182
def __init__(self, patterns):
183
self._regex_patterns = []
188
pat = normalize_pattern(pat)
189
if pat.startswith(u'RE:') or u'/' in pat:
190
path_patterns.append(pat)
191
elif pat.startswith(u'*.'):
192
ext_patterns.append(pat)
194
base_patterns.append(pat)
195
self._add_patterns(ext_patterns,_sub_extension,
196
prefix=r'(?:.*/)?(?!.*/)(?:.*\.)')
197
self._add_patterns(base_patterns,_sub_basename,
198
prefix=r'(?:.*/)?(?!.*/)')
199
self._add_patterns(path_patterns,_sub_fullpath)
201
def _add_patterns(self, patterns, translator, prefix=''):
203
grouped_rules = ['(%s)' % translator(pat) for pat in patterns[:99]]
204
joined_rule = '%s(?:%s)$' % (prefix, '|'.join(grouped_rules))
205
self._regex_patterns.append((re.compile(joined_rule, re.UNICODE),
207
patterns = patterns[99:]
209
def match(self, filename):
210
"""Searches for a pattern that matches the given filename.
212
:return A matching pattern or None if there is no matching pattern.
215
for regex, patterns in self._regex_patterns:
216
match = regex.match(filename)
218
return patterns[match.lastindex -1]
219
except errors.InvalidPattern, e:
220
# We can't show the default e.msg to the user as thats for
221
# the combined pattern we sent to regex. Instead we indicate to
222
# the user that an ignore file needs fixing.
223
mutter('Invalid pattern found in regex: %s.', e.msg)
224
e.msg = "File ~/.bazaar/ignore or .bzrignore contains errors."
228
class ExceptionGlobster(object):
229
"""A Globster that supports exception patterns.
231
Exceptions are ignore patterns prefixed with '!'. Exception
232
patterns take precedence over regular patterns and cause a
233
matching filename to return None from the match() function.
234
Patterns using a '!!' prefix are highest precedence, and act
235
as regular ignores. '!!' patterns are useful to establish ignores
236
that apply under paths specified by '!' exception patterns.
239
def __init__(self,patterns):
240
ignores = [[], [], []]
242
if p.startswith(u'!!'):
243
ignores[2].append(p[2:])
244
elif p.startswith(u'!'):
245
ignores[1].append(p[1:])
248
self._ignores = [Globster(i) for i in ignores]
250
def match(self, filename):
251
"""Searches for a pattern that matches the given filename.
253
:return A matching pattern or None if there is no matching pattern.
255
double_neg = self._ignores[2].match(filename)
257
return "!!%s" % double_neg
258
elif self._ignores[1].match(filename):
261
return self._ignores[0].match(filename)
263
class _OrderedGlobster(Globster):
264
"""A Globster that keeps pattern order."""
266
def __init__(self, patterns):
269
:param patterns: sequence of glob patterns
271
# Note: This could be smarter by running like sequences together
272
self._regex_patterns = []
274
pat = normalize_pattern(pat)
275
if pat.startswith(u'RE:') or u'/' in pat:
276
self._add_patterns([pat], _sub_fullpath)
277
elif pat.startswith(u'*.'):
278
self._add_patterns([pat], _sub_extension,
279
prefix=r'(?:.*/)?(?!.*/)(?:.*\.)')
281
self._add_patterns([pat], _sub_basename,
282
prefix=r'(?:.*/)?(?!.*/)')
285
_slashes = re.compile(r'[\\/]+')
286
def normalize_pattern(pattern):
287
"""Converts backslashes in path patterns to forward slashes.
289
Doesn't normalize regular expressions - they may contain escapes.
291
if not (pattern.startswith('RE:') or pattern.startswith('!RE:')):
292
pattern = _slashes.sub('/', pattern)
294
pattern = pattern.rstrip('/')