/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 breezy/globbing.py

  • Committer: Jelmer Vernooij
  • Date: 2020-02-07 02:14:30 UTC
  • mto: This revision was merged to the branch mainline in revision 7492.
  • Revision ID: jelmer@jelmer.uk-20200207021430-m49iq3x4x8xlib6x
Drop python2 support.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006-2011 Canonical Ltd
 
2
 
 
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.
 
7
#
 
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.
 
12
#
 
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
 
16
 
 
17
"""Tools for converting globs to regular expressions.
 
18
 
 
19
This module provides functions for converting shell-like globs to regular
 
20
expressions.
 
21
"""
 
22
 
 
23
from __future__ import absolute_import
 
24
 
 
25
import re
 
26
 
 
27
from . import (
 
28
    lazy_regex,
 
29
    )
 
30
from .trace import (
 
31
    mutter,
 
32
    warning,
 
33
    )
 
34
 
 
35
 
 
36
class Replacer(object):
 
37
    """Do a multiple-pattern substitution.
 
38
 
 
39
    The patterns and substitutions are combined into one, so the result of
 
40
    one replacement is never substituted again. Add the patterns and
 
41
    replacements via the add method and then call the object. The patterns
 
42
    must not contain capturing groups.
 
43
    """
 
44
 
 
45
    _expand = lazy_regex.lazy_compile(u'\\\\&')
 
46
 
 
47
    def __init__(self, source=None):
 
48
        self._pat = None
 
49
        if source:
 
50
            self._pats = list(source._pats)
 
51
            self._funs = list(source._funs)
 
52
        else:
 
53
            self._pats = []
 
54
            self._funs = []
 
55
 
 
56
    def add(self, pat, fun):
 
57
        r"""Add a pattern and replacement.
 
58
 
 
59
        The pattern must not contain capturing groups.
 
60
        The replacement might be either a string template in which \& will be
 
61
        replaced with the match, or a function that will get the matching text
 
62
        as argument. It does not get match object, because capturing is
 
63
        forbidden anyway.
 
64
        """
 
65
        self._pat = None
 
66
        self._pats.append(pat)
 
67
        self._funs.append(fun)
 
68
 
 
69
    def add_replacer(self, replacer):
 
70
        r"""Add all patterns from another replacer.
 
71
 
 
72
        All patterns and replacements from replacer are appended to the ones
 
73
        already defined.
 
74
        """
 
75
        self._pat = None
 
76
        self._pats.extend(replacer._pats)
 
77
        self._funs.extend(replacer._funs)
 
78
 
 
79
    def __call__(self, text):
 
80
        if not self._pat:
 
81
            self._pat = lazy_regex.lazy_compile(
 
82
                u'|'.join([u'(%s)' % p for p in self._pats]),
 
83
                re.UNICODE)
 
84
        return self._pat.sub(self._do_sub, text)
 
85
 
 
86
    def _do_sub(self, m):
 
87
        fun = self._funs[m.lastindex - 1]
 
88
        if hasattr(fun, '__call__'):
 
89
            return fun(m.group(0))
 
90
        else:
 
91
            return self._expand.sub(m.group(0), fun)
 
92
 
 
93
 
 
94
_sub_named = Replacer()
 
95
_sub_named.add(r'\[:digit:\]', r'\d')
 
96
_sub_named.add(r'\[:space:\]', r'\s')
 
97
_sub_named.add(r'\[:alnum:\]', r'\w')
 
98
_sub_named.add(r'\[:ascii:\]', r'\0-\x7f')
 
99
_sub_named.add(r'\[:blank:\]', r' \t')
 
100
_sub_named.add(r'\[:cntrl:\]', r'\0-\x1f\x7f-\x9f')
 
101
 
 
102
 
 
103
def _sub_group(m):
 
104
    if m[1] in (u'!', u'^'):
 
105
        return u'[^' + _sub_named(m[2:-1]) + u']'
 
106
    return u'[' + _sub_named(m[1:-1]) + u']'
 
107
 
 
108
 
 
109
def _invalid_regex(repl):
 
110
    def _(m):
 
111
        warning(u"'%s' not allowed within a regular expression. "
 
112
                "Replacing with '%s'" % (m, repl))
 
113
        return repl
 
114
    return _
 
115
 
 
116
 
 
117
def _trailing_backslashes_regex(m):
 
118
    """Check trailing backslashes.
 
119
 
 
120
    Does a head count on trailing backslashes to ensure there isn't an odd
 
121
    one on the end that would escape the brackets we wrap the RE in.
 
122
    """
 
123
    if (len(m) % 2) != 0:
 
124
        warning(u"Regular expressions cannot end with an odd number of '\\'. "
 
125
                "Dropping the final '\\'.")
 
126
        return m[:-1]
 
127
    return m
 
128
 
 
129
 
 
130
_sub_re = Replacer()
 
131
_sub_re.add(u'^RE:', u'')
 
132
_sub_re.add(u'\\((?!\\?)', u'(?:')
 
133
_sub_re.add(u'\\(\\?P<.*>', _invalid_regex(u'(?:'))
 
134
_sub_re.add(u'\\(\\?P=[^)]*\\)', _invalid_regex(u''))
 
135
_sub_re.add(r'\\+$', _trailing_backslashes_regex)
 
136
 
 
137
 
 
138
_sub_fullpath = Replacer()
 
139
_sub_fullpath.add(r'^RE:.*', _sub_re)  # RE:<anything> is a regex
 
140
_sub_fullpath.add(r'\[\^?\]?(?:[^][]|\[:[^]]+:\])+\]',
 
141
                  _sub_group)  # char group
 
142
_sub_fullpath.add(r'(?:(?<=/)|^)(?:\.?/)+', u'')  # canonicalize path
 
143
_sub_fullpath.add(r'\\.', r'\&')  # keep anything backslashed
 
144
_sub_fullpath.add(r'[(){}|^$+.]', r'\\&')  # escape specials
 
145
_sub_fullpath.add(r'(?:(?<=/)|^)\*\*+/', r'(?:.*/)?')  # **/ after ^ or /
 
146
_sub_fullpath.add(r'\*+', r'[^/]*')  # * elsewhere
 
147
_sub_fullpath.add(r'\?', r'[^/]')  # ? everywhere
 
148
 
 
149
 
 
150
_sub_basename = Replacer()
 
151
_sub_basename.add(r'\[\^?\]?(?:[^][]|\[:[^]]+:\])+\]',
 
152
                  _sub_group)  # char group
 
153
_sub_basename.add(r'\\.', r'\&')  # keep anything backslashed
 
154
_sub_basename.add(r'[(){}|^$+.]', r'\\&')  # escape specials
 
155
_sub_basename.add(r'\*+', r'.*')  # * everywhere
 
156
_sub_basename.add(r'\?', r'.')  # ? everywhere
 
157
 
 
158
 
 
159
def _sub_extension(pattern):
 
160
    return _sub_basename(pattern[2:])
 
161
 
 
162
 
 
163
class Globster(object):
 
164
    """A simple wrapper for a set of glob patterns.
 
165
 
 
166
    Provides the capability to search the patterns to find a match for
 
167
    a given filename (including the full path).
 
168
 
 
169
    Patterns are translated to regular expressions to expidite matching.
 
170
 
 
171
    The regular expressions for multiple patterns are aggregated into
 
172
    a super-regex containing groups of up to 99 patterns.
 
173
    The 99 limitation is due to the grouping limit of the Python re module.
 
174
    The resulting super-regex and associated patterns are stored as a list of
 
175
    (regex,[patterns]) in _regex_patterns.
 
176
 
 
177
    For performance reasons the patterns are categorised as extension patterns
 
178
    (those that match against a file extension), basename patterns
 
179
    (those that match against the basename of the filename),
 
180
    and fullpath patterns (those that match against the full path).
 
181
    The translations used for extensions and basenames are relatively simpler
 
182
    and therefore faster to perform than the fullpath patterns.
 
183
 
 
184
    Also, the extension patterns are more likely to find a match and
 
185
    so are matched first, then the basename patterns, then the fullpath
 
186
    patterns.
 
187
    """
 
188
    # We want to _add_patterns in a specific order (as per type_list below)
 
189
    # starting with the shortest and going to the longest.
 
190
    # As some Python version don't support ordered dicts the list below is
 
191
    # used to select inputs for _add_pattern in a specific order.
 
192
    pattern_types = ["extension", "basename", "fullpath"]
 
193
 
 
194
    pattern_info = {
 
195
        "extension": {
 
196
            "translator": _sub_extension,
 
197
            "prefix": r'(?:.*/)?(?!.*/)(?:.*\.)'
 
198
        },
 
199
        "basename": {
 
200
            "translator": _sub_basename,
 
201
            "prefix": r'(?:.*/)?(?!.*/)'
 
202
        },
 
203
        "fullpath": {
 
204
            "translator": _sub_fullpath,
 
205
            "prefix": r''
 
206
        },
 
207
    }
 
208
 
 
209
    def __init__(self, patterns):
 
210
        self._regex_patterns = []
 
211
        pattern_lists = {
 
212
            "extension": [],
 
213
            "basename": [],
 
214
            "fullpath": [],
 
215
        }
 
216
        for pat in patterns:
 
217
            pat = normalize_pattern(pat)
 
218
            pattern_lists[Globster.identify(pat)].append(pat)
 
219
        pi = Globster.pattern_info
 
220
        for t in Globster.pattern_types:
 
221
            self._add_patterns(pattern_lists[t], pi[t]["translator"],
 
222
                               pi[t]["prefix"])
 
223
 
 
224
    def _add_patterns(self, patterns, translator, prefix=''):
 
225
        while patterns:
 
226
            grouped_rules = [
 
227
                '(%s)' % translator(pat) for pat in patterns[:99]]
 
228
            joined_rule = '%s(?:%s)$' % (prefix, '|'.join(grouped_rules))
 
229
            # Explicitly use lazy_compile here, because we count on its
 
230
            # nicer error reporting.
 
231
            self._regex_patterns.append((
 
232
                lazy_regex.lazy_compile(joined_rule, re.UNICODE),
 
233
                patterns[:99]))
 
234
            patterns = patterns[99:]
 
235
 
 
236
    def match(self, filename):
 
237
        """Searches for a pattern that matches the given filename.
 
238
 
 
239
        :return A matching pattern or None if there is no matching pattern.
 
240
        """
 
241
        try:
 
242
            for regex, patterns in self._regex_patterns:
 
243
                match = regex.match(filename)
 
244
                if match:
 
245
                    return patterns[match.lastindex - 1]
 
246
        except lazy_regex.InvalidPattern as e:
 
247
            # We can't show the default e.msg to the user as thats for
 
248
            # the combined pattern we sent to regex. Instead we indicate to
 
249
            # the user that an ignore file needs fixing.
 
250
            mutter('Invalid pattern found in regex: %s.', e.msg)
 
251
            e.msg = (
 
252
                "File ~/.config/breezy/ignore or "
 
253
                ".bzrignore contains error(s).")
 
254
            bad_patterns = ''
 
255
            for _, patterns in self._regex_patterns:
 
256
                for p in patterns:
 
257
                    if not Globster.is_pattern_valid(p):
 
258
                        bad_patterns += ('\n  %s' % p)
 
259
            e.msg += bad_patterns
 
260
            raise e
 
261
        return None
 
262
 
 
263
    @staticmethod
 
264
    def identify(pattern):
 
265
        """Returns pattern category.
 
266
 
 
267
        :param pattern: normalized pattern.
 
268
        Identify if a pattern is fullpath, basename or extension
 
269
        and returns the appropriate type.
 
270
        """
 
271
        if pattern.startswith(u'RE:') or u'/' in pattern:
 
272
            return "fullpath"
 
273
        elif pattern.startswith(u'*.'):
 
274
            return "extension"
 
275
        else:
 
276
            return "basename"
 
277
 
 
278
    @staticmethod
 
279
    def is_pattern_valid(pattern):
 
280
        """Returns True if pattern is valid.
 
281
 
 
282
        :param pattern: Normalized pattern.
 
283
        is_pattern_valid() assumes pattern to be normalized.
 
284
        see: globbing.normalize_pattern
 
285
        """
 
286
        result = True
 
287
        translator = Globster.pattern_info[Globster.identify(
 
288
            pattern)]["translator"]
 
289
        tpattern = '(%s)' % translator(pattern)
 
290
        try:
 
291
            re_obj = lazy_regex.lazy_compile(tpattern, re.UNICODE)
 
292
            re_obj.search("")  # force compile
 
293
        except lazy_regex.InvalidPattern:
 
294
            result = False
 
295
        return result
 
296
 
 
297
 
 
298
class ExceptionGlobster(object):
 
299
    """A Globster that supports exception patterns.
 
300
 
 
301
    Exceptions are ignore patterns prefixed with '!'.  Exception
 
302
    patterns take precedence over regular patterns and cause a
 
303
    matching filename to return None from the match() function.
 
304
    Patterns using a '!!' prefix are highest precedence, and act
 
305
    as regular ignores. '!!' patterns are useful to establish ignores
 
306
    that apply under paths specified by '!' exception patterns.
 
307
    """
 
308
 
 
309
    def __init__(self, patterns):
 
310
        ignores = [[], [], []]
 
311
        for p in patterns:
 
312
            if p.startswith(u'!!'):
 
313
                ignores[2].append(p[2:])
 
314
            elif p.startswith(u'!'):
 
315
                ignores[1].append(p[1:])
 
316
            else:
 
317
                ignores[0].append(p)
 
318
        self._ignores = [Globster(i) for i in ignores]
 
319
 
 
320
    def match(self, filename):
 
321
        """Searches for a pattern that matches the given filename.
 
322
 
 
323
        :return A matching pattern or None if there is no matching pattern.
 
324
        """
 
325
        double_neg = self._ignores[2].match(filename)
 
326
        if double_neg:
 
327
            return "!!%s" % double_neg
 
328
        elif self._ignores[1].match(filename):
 
329
            return None
 
330
        else:
 
331
            return self._ignores[0].match(filename)
 
332
 
 
333
 
 
334
class _OrderedGlobster(Globster):
 
335
    """A Globster that keeps pattern order."""
 
336
 
 
337
    def __init__(self, patterns):
 
338
        """Constructor.
 
339
 
 
340
        :param patterns: sequence of glob patterns
 
341
        """
 
342
        # Note: This could be smarter by running like sequences together
 
343
        self._regex_patterns = []
 
344
        for pat in patterns:
 
345
            pat = normalize_pattern(pat)
 
346
            t = Globster.identify(pat)
 
347
            self._add_patterns([pat], Globster.pattern_info[t]["translator"],
 
348
                               Globster.pattern_info[t]["prefix"])
 
349
 
 
350
 
 
351
_slashes = lazy_regex.lazy_compile(r'[\\/]+')
 
352
 
 
353
 
 
354
def normalize_pattern(pattern):
 
355
    """Converts backslashes in path patterns to forward slashes.
 
356
 
 
357
    Doesn't normalize regular expressions - they may contain escapes.
 
358
    """
 
359
    if not (pattern.startswith('RE:') or pattern.startswith('!RE:')):
 
360
        pattern = _slashes.sub('/', pattern)
 
361
    if len(pattern) > 1:
 
362
        pattern = pattern.rstrip('/')
 
363
    return pattern