1
# Copyright (C) 2006-2011 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
23
from __future__ import absolute_import
31
from bzrlib.trace import (
37
class Replacer(object):
38
"""Do a multiple-pattern substitution.
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.
46
_expand = lazy_regex.lazy_compile(ur'\\&')
48
def __init__(self, source=None):
51
self._pats = list(source._pats)
52
self._funs = list(source._funs)
57
def add(self, pat, fun):
58
r"""Add a pattern and replacement.
60
The pattern must not contain capturing groups.
61
The replacement might be either a string template in which \& will be
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
67
self._pats.append(pat)
68
self._funs.append(fun)
70
def add_replacer(self, replacer):
71
r"""Add all patterns from another replacer.
73
All patterns and replacements from replacer are appended to the ones
77
self._pats.extend(replacer._pats)
78
self._funs.extend(replacer._funs)
80
def __call__(self, text):
82
self._pat = lazy_regex.lazy_compile(
83
u'|'.join([u'(%s)' % p for p in self._pats]),
85
return self._pat.sub(self._do_sub, text)
88
fun = self._funs[m.lastindex - 1]
89
if hasattr(fun, '__call__'):
90
return fun(m.group(0))
92
return self._expand.sub(m.group(0), fun)
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')
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']'
110
def _invalid_regex(repl):
112
warning(u"'%s' not allowed within a regular expression. "
113
"Replacing with '%s'" % (m, repl))
118
def _trailing_backslashes_regex(m):
119
"""Check trailing backslashes.
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.
124
if (len(m) % 2) != 0:
125
warning(u"Regular expressions cannot end with an odd number of '\\'. "
126
"Dropping the final '\\'.")
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''))
136
_sub_re.add(ur'\\+$', _trailing_backslashes_regex)
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
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
158
def _sub_extension(pattern):
159
return _sub_basename(pattern[2:])
162
class Globster(object):
163
"""A simple wrapper for a set of glob patterns.
165
Provides the capability to search the patterns to find a match for
166
a given filename (including the full path).
168
Patterns are translated to regular expressions to expidite matching.
170
The regular expressions for multiple patterns are aggregated into
171
a super-regex containing groups of up to 99 patterns.
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.
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).
180
The translations used for extensions and basenames are relatively simpler
181
and therefore faster to perform than the fullpath patterns.
183
Also, the extension patterns are more likely to find a match and
184
so are matched first, then the basename patterns, then the fullpath
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" ]
195
"translator" : _sub_extension,
196
"prefix" : r'(?:.*/)?(?!.*/)(?:.*\.)'
199
"translator" : _sub_basename,
200
"prefix" : r'(?:.*/)?(?!.*/)'
203
"translator" : _sub_fullpath,
208
def __init__(self, patterns):
209
self._regex_patterns = []
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"],
223
def _add_patterns(self, patterns, translator, prefix=''):
226
'(%s)' % translator(pat) for pat in patterns[:99]]
227
joined_rule = '%s(?:%s)$' % (prefix, '|'.join(grouped_rules))
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),
233
patterns = patterns[99:]
235
def match(self, filename):
236
"""Searches for a pattern that matches the given filename.
238
:return A matching pattern or None if there is no matching pattern.
241
for regex, patterns in self._regex_patterns:
242
match = regex.match(filename)
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)."
252
for _, patterns in self._regex_patterns:
254
if not Globster.is_pattern_valid(p):
255
bad_patterns += ('\n %s' % p)
256
e.msg += bad_patterns
261
def identify(pattern):
262
"""Returns pattern category.
264
:param pattern: normalized pattern.
265
Identify if a pattern is fullpath, basename or extension
266
and returns the appropriate type.
268
if pattern.startswith(u'RE:') or u'/' in pattern:
270
elif pattern.startswith(u'*.'):
276
def is_pattern_valid(pattern):
277
"""Returns True if pattern is valid.
279
:param pattern: Normalized pattern.
280
is_pattern_valid() assumes pattern to be normalized.
281
see: globbing.normalize_pattern
284
translator = Globster.pattern_info[Globster.identify(pattern)]["translator"]
285
tpattern = '(%s)' % translator(pattern)
287
re_obj = lazy_regex.lazy_compile(tpattern, re.UNICODE)
288
re_obj.search("") # force compile
289
except errors.InvalidPattern, e:
294
class ExceptionGlobster(object):
295
"""A Globster that supports exception patterns.
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.
305
def __init__(self,patterns):
306
ignores = [[], [], []]
308
if p.startswith(u'!!'):
309
ignores[2].append(p[2:])
310
elif p.startswith(u'!'):
311
ignores[1].append(p[1:])
314
self._ignores = [Globster(i) for i in ignores]
316
def match(self, filename):
317
"""Searches for a pattern that matches the given filename.
319
:return A matching pattern or None if there is no matching pattern.
321
double_neg = self._ignores[2].match(filename)
323
return "!!%s" % double_neg
324
elif self._ignores[1].match(filename):
327
return self._ignores[0].match(filename)
329
class _OrderedGlobster(Globster):
330
"""A Globster that keeps pattern order."""
332
def __init__(self, patterns):
335
:param patterns: sequence of glob patterns
337
# Note: This could be smarter by running like sequences together
338
self._regex_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"])
346
_slashes = lazy_regex.lazy_compile(r'[\\/]+')
347
def normalize_pattern(pattern):
348
"""Converts backslashes in path patterns to forward slashes.
350
Doesn't normalize regular expressions - they may contain escapes.
352
if not (pattern.startswith('RE:') or pattern.startswith('!RE:')):
353
pattern = _slashes.sub('/', pattern)
355
pattern = pattern.rstrip('/')