[PATCH 1 of 2] ui: add a context for temporary config changes

Siddharth Agarwal sid0 at fb.com
Sun Mar 20 21:00:52 EDT 2016


# HG changeset patch
# User Siddharth Agarwal <sid0 at fb.com>
# Date 1458522014 25200
#      Sun Mar 20 18:00:14 2016 -0700
# Node ID b190b4bd5de25c137286cbb21572e9e1160b415b
# Parent  ed75909c4c670a7d9db4a2bef9817a0d5f0b4d9c
ui: add a context for temporary config changes

This allows temporary config changes to be expressed as:

  with ui.tempconfig('section', 'name', 'value'):
      ... do stuff ...

and have it be exception-safe.

diff --git a/mercurial/ui.py b/mercurial/ui.py
--- a/mercurial/ui.py
+++ b/mercurial/ui.py
@@ -7,6 +7,7 @@
 
 from __future__ import absolute_import
 
+import contextlib
 import errno
 import getpass
 import inspect
@@ -251,6 +252,17 @@ class ui(object):
             cfg.set(section, name, value, source)
         self.fixconfig(section=section)
 
+    @contextlib.contextmanager
+    def tempconfig(self, section, name, value, source=''):
+        '''Context for setting a config within a section of code. This is
+        dynamically scope.'''
+        backup = self.backupconfig(section, name)
+        try:
+            self.setconfig(section, name, value, source)
+            yield
+        finally:
+            self.restoreconfig(backup)
+
     def _data(self, untrusted):
         return untrusted and self._ucfg or self._tcfg
 
diff --git a/tests/test-ui-config.py b/tests/test-ui-config.py
--- a/tests/test-ui-config.py
+++ b/tests/test-ui-config.py
@@ -96,3 +96,21 @@ try:
     testui.configint('values', 'intinvalid')
 except error.ConfigError:
     print 'intinvalid'
+
+print '---'
+
+# ui.tempconfig
+testui.setconfig('foo', 'bar', 'outside', 'outside-source')
+with testui.tempconfig('foo', 'bar', 'inside', 'inside-source'):
+    print 'config inside with: %s' % testui.config('foo', 'bar')
+    print 'configsource inside with: %s' % testui.configsource('foo', 'bar')
+print 'config outside with: %s' % testui.config('foo', 'bar')
+print 'configsource outside with: %s' % testui.configsource('foo', 'bar')
+
+print 'with exception:'
+try:
+    with testui.tempconfig('foo', 'bar', 'inside', 'inside-source'):
+        raise AssertionError('exception')
+except AssertionError:
+    print 'config outside with: %s' % testui.config('foo', 'bar')
+    print 'configsource outside with: %s' % testui.configsource('foo', 'bar')
diff --git a/tests/test-ui-config.py.out b/tests/test-ui-config.py.out
--- a/tests/test-ui-config.py.out
+++ b/tests/test-ui-config.py.out
@@ -47,3 +47,11 @@ None
 True
 boolinvalid
 intinvalid
+---
+config inside with: inside
+configsource inside with: inside-source
+config outside with: outside
+configsource outside with: outside-source
+with exception:
+config outside with: outside
+configsource outside with: outside-source


More information about the Mercurial-devel mailing list