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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
17
"""Tools for converting globs to regular expressions.
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
161
156
Patterns are translated to regular expressions to expidite matching.
163
The regular expressions for multiple patterns are aggregated into
164
a super-regex containing groups of up to 99 patterns.
158
The regular expressions for multiple patterns are aggregated into
159
a super-regex containing groups of up to 99 patterns.
165
160
The 99 limitation is due to the grouping limit of the Python re module.
166
161
The resulting super-regex and associated patterns are stored as a list of
167
162
(regex,[patterns]) in _regex_patterns.
169
164
For performance reasons the patterns are categorised as extension patterns
170
165
(those that match against a file extension), basename patterns
171
166
(those that match against the basename of the filename),
172
167
and fullpath patterns (those that match against the full path).
173
The translations used for extensions and basenames are relatively simpler
168
The translations used for extensions and basenames are relatively simpler
174
169
and therefore faster to perform than the fullpath patterns.
176
Also, the extension patterns are more likely to find a match and
171
Also, the extension patterns are more likely to find a match and
177
172
so are matched first, then the basename patterns, then the fullpath
192
187
base_patterns.append(pat)
193
188
self._add_patterns(ext_patterns,_sub_extension,
194
189
prefix=r'(?:.*/)?(?!.*/)(?:.*\.)')
195
self._add_patterns(base_patterns,_sub_basename,
190
self._add_patterns(base_patterns,_sub_basename,
196
191
prefix=r'(?:.*/)?(?!.*/)')
197
self._add_patterns(path_patterns,_sub_fullpath)
192
self._add_patterns(path_patterns,_sub_fullpath)
199
194
def _add_patterns(self, patterns, translator, prefix=''):
201
196
grouped_rules = ['(%s)' % translator(pat) for pat in patterns[:99]]
202
197
joined_rule = '%s(?:%s)$' % (prefix, '|'.join(grouped_rules))
203
self._regex_patterns.append((re.compile(joined_rule, re.UNICODE),
198
self._regex_patterns.append((re.compile(joined_rule, re.UNICODE),
205
200
patterns = patterns[99:]
207
202
def match(self, filename):
208
203
"""Searches for a pattern that matches the given filename.
210
205
:return A matching pattern or None if there is no matching pattern.
212
207
for regex, patterns in self._regex_patterns:
215
210
return patterns[match.lastindex -1]
218
class ExceptionGlobster(object):
219
"""A Globster that supports exception patterns.
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.
229
def __init__(self,patterns):
230
ignores = [[], [], []]
232
if p.startswith(u'!!'):
233
ignores[2].append(p[2:])
234
elif p.startswith(u'!'):
235
ignores[1].append(p[1:])
238
self._ignores = [Globster(i) for i in ignores]
240
def match(self, filename):
241
"""Searches for a pattern that matches the given filename.
243
:return A matching pattern or None if there is no matching pattern.
245
double_neg = self._ignores[2].match(filename)
247
return "!!%s" % double_neg
248
elif self._ignores[1].match(filename):
251
return self._ignores[0].match(filename)
253
class _OrderedGlobster(Globster):
254
"""A Globster that keeps pattern order."""
256
def __init__(self, patterns):
259
:param patterns: sequence of glob patterns
261
# Note: This could be smarter by running like sequences together
262
self._regex_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'(?:.*/)?(?!.*/)(?:.*\.)')
271
self._add_patterns([pat], _sub_basename,
272
prefix=r'(?:.*/)?(?!.*/)')
275
_slashes = re.compile(r'[\\/]+')
214
_normalize_re = re.compile(ur'\\(?!x\d\d|\d\d\d|u\d\d\d\d)')
276
217
def normalize_pattern(pattern):
277
218
"""Converts backslashes in path patterns to forward slashes.
279
Doesn't normalize regular expressions - they may contain escapes.
220
Avoids converting escape backslashes.
281
if not (pattern.startswith('RE:') or pattern.startswith('!RE:')):
282
pattern = _slashes.sub('/', pattern)
284
pattern = pattern.rstrip('/')
222
if not pattern.startswith('RE:'):
223
pattern = _normalize_re.sub('/', pattern)
224
return pattern.rstrip('/')