~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/lazy_regex.py

(jameinel) Allow 'bzr serve' to interpret SIGHUP as a graceful shutdown.
 (bug #795025) (John A Meinel)

Show diffs side-by-side

added added

removed removed

Lines of Context:
12
12
#
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
"""Lazily compiled regex objects.
18
18
 
19
 
This module defines a class which creates proxy objects for regex compilation.
20
 
This allows overriding re.compile() to return lazily compiled objects.
 
19
This module defines a class which creates proxy objects for regex
 
20
compilation.  This allows overriding re.compile() to return lazily compiled
 
21
objects.  
 
22
 
 
23
We do this rather than just providing a new interface so that it will also
 
24
be used by existing Python modules that create regexs.
21
25
"""
22
26
 
23
27
import re
24
28
 
 
29
from bzrlib import errors
 
30
 
25
31
 
26
32
class LazyRegex(object):
27
33
    """A proxy around a real regex, which won't be compiled until accessed."""
42
48
    def __init__(self, args=(), kwargs={}):
43
49
        """Create a new proxy object, passing in the args to pass to re.compile
44
50
 
45
 
        :param args: The *args to pass to re.compile
46
 
        :param kwargs: The **kwargs to pass to re.compile
 
51
        :param args: The `*args` to pass to re.compile
 
52
        :param kwargs: The `**kwargs` to pass to re.compile
47
53
        """
48
54
        self._real_regex = None
49
55
        self._regex_args = args
58
64
 
59
65
    def _real_re_compile(self, *args, **kwargs):
60
66
        """Thunk over to the original re.compile"""
61
 
        return _real_re_compile(*args, **kwargs)
 
67
        try:
 
68
            return _real_re_compile(*args, **kwargs)
 
69
        except re.error, e:
 
70
            # raise InvalidPattern instead of re.error as this gives a
 
71
            # cleaner message to the user.
 
72
            raise errors.InvalidPattern('"' + args[0] + '" ' +str(e))
62
73
 
63
74
    def __getattr__(self, attr):
64
75
        """Return a member from the proxied regex object.
91
102
 
92
103
def reset_compile():
93
104
    """Restore the original function to re.compile().
94
 
    
 
105
 
95
106
    It is safe to call reset_compile() multiple times, it will always
96
107
    restore re.compile() to the value that existed at import time.
97
108
    Though the first call will reset back to the original (it doesn't