diff mercurial/extensions.py @ 34032:47e52f079a57

extensions: add wrappedfunction() context manager Several extensions exist that temporarily want to wrap a function (at least narrowhg, any many of the extensions in hg-experimental). That's why we have the unwrapfunction() that was introduced in 19578bb84731 (extensions: add unwrapfunction to undo wrapfunction, 2016-08-10). This patch adds a simple wrappedfunction() that returns a context manager. Differential Revision: https://phab.mercurial-scm.org/D472
author Martin von Zweigbergk <martinvonz@google.com>
date Mon, 21 Aug 2017 16:46:05 -0700
parents 0646608368a9
children 0e0ac8f09048
line wrap: on
line diff
--- a/mercurial/extensions.py	Tue Aug 29 18:20:50 2017 -0700
+++ b/mercurial/extensions.py	Mon Aug 21 16:46:05 2017 -0700
@@ -399,6 +399,21 @@
         raise AttributeError(r"type '%s' has no property '%s'" % (
             cls, propname))
 
+class wrappedfunction(object):
+    '''context manager for temporarily wrapping a function'''
+
+    def __init__(self, container, funcname, wrapper):
+        assert callable(wrapper)
+        self._container = container
+        self._funcname = funcname
+        self._wrapper = wrapper
+
+    def __enter__(self):
+        wrapfunction(self._container, self._funcname, self._wrapper)
+
+    def __exit__(self, exctype, excvalue, traceback):
+        unwrapfunction(self._container, self._funcname, self._wrapper)
+
 def wrapfunction(container, funcname, wrapper):
     '''Wrap the function named funcname in container