1000
  7   qˆl–Ü4ý( ©”u( 	•íÀà™S�ÿ�þYŽ¬Ü¢#á�a	Hçð„›?ïåÂì 0×    q# Copyright (C) 2006-2011 Canonical Ltd

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

"""Tools for converting globs to regular expressions.

This module provides functions for converting shell-like globs to regular
expressions.
"""

import re

from . import (
    lazy_regex,
    )
from .trace import (
    mutter,
    warning,
    )


class Replacer:
    """Do a multiple-pattern substitution.

    The patterns and substitutions are combined into one, so the result of
    one replacement is never substituted again. Add the patterns and
    replacements via the add method and then call the object. The patterns
    must not contain capturing groups.
    """

    _expand = lazy_regex.lazy_compile('\\\\&')

    def __init__(self, source=None):
        self._pat = None
        if source:
            self._pats = list(source._pats)
            self._funs = list(source._funs)
        else:
            self._pats = []
            self._funs = []

    def add(self, pat, fun):
        r"""Add a pattern and replacement.

        The pattern must not contain capturing groups.
        The replacement might be either a string template in which \& will be
        replaced with the match, or a function that will get the matching text
        as argument. It does not get match object, because capturing is
        forbidden anyway.
        """
        self._pat = None
        self._pats.append(pat)
        self._funs.append(fun)

    def add_replacer(self, replacer):
        r"""Add all patterns from another replacer.

        All patterns and replacements from replacer are appended to the ones
        already defined.
        """
        self._pat = None
        self._pats.extend(replacer._pats)
        self._funs.extend(replacer._funs)

    def __call__(self, text):
        if not self._pat:
            self._pat = lazy_regex.lazy_compile(
                '|'.join(['(%s)' % p for p in self._pats]),
                re.UNICODE)
        return self._pat.sub(self._do_sub, text)

    def _do_sub(self, m):
        fun = self._funs[m.lastindex - 1]
        if hasattr(fun, '__call__'):
            return fun(m.group(0))
        else:
            return self._expand.sub(m.group(0), fun)


_sub_named = Replacer()
_sub_named.add(r'\[:digit:\]', r'\d')
_sub_named.add(r'\[:space:\]', r'\s')
_sub_named.add(r'\[:alnum:\]', r'\w')
_sub_named.add(r'\[:ascii:\]', r'\0-\x7f')
_sub_named.add(r'\[:blank:\]', r' \t')
_sub_named.add(r'\[:cntrl:\]', r'\0-\x1f\x7f-\x9f')


def _sub_group(m):
    if m[1] in ('!', '^'):
        return '[^' + _sub_named(m[2:-1]) + ']'
    return '[' + _sub_named(m[1:-1]) + ']'


def _invalid_regex(repl):
    def _(m):
        warning("'%s' not allowed within a regular expression. "
                "Replacing with '%s'" % (m, repl))
        return repl
    return _


def _trailing_backslashes_regex(m):
    """Check trailing backslashes.

    Does a head count on trailing backslashes to ensure there isn't an odd
    one on the end that would escape the brackets we wrap the RE in.
    """
    if (len(m) % 2) != 0:
        warning("Regular expressions cannot end with an odd number of '\\'. "
                "Dropping the final '\\'.")
        return m[:-1]
    return m


_sub_re = Replacer()
_sub_re.add('^RE:', '')
_sub_re.add('\\((?!\\?)', '(?:')
_sub_re.add('\\(\\?P<.*>', _invalid_regex('(?:'))
_sub_re.add('\\(\