[PATCH 2 of 4 V2] ui: add context manager to override config

Laurent Charignon lcharignon at fb.com
Wed May 13 19:26:05 CDT 2015


# HG changeset patch
# User Laurent Charignon <lcharignon at fb.com>
# Date 1431561984 25200
#      Wed May 13 17:06:24 2015 -0700
# Node ID 480dbca00f19fb90b59f9c6fd511e4806fb642c4
# Parent  92b5fa4e1be509cd7206e8f04c3dc3d1cefa58bf
ui: add context manager to override config

By leveraging this feature of python 2.5, we can make our code base cleaner
and prevent mistakes where some code forget to change the config value back
after overriding it.

diff --git a/mercurial/ui.py b/mercurial/ui.py
--- a/mercurial/ui.py
+++ b/mercurial/ui.py
@@ -9,6 +9,7 @@
 import errno, getpass, os, socket, sys, tempfile, traceback
 import config, scmutil, util, error, formatter
 from node import hex
+from contextlib import contextmanager
 
 samplehgrcs = {
     'user':
@@ -221,6 +222,21 @@
         return (self._ocfg.backup(section, item),
                 self._tcfg.backup(section, item),
                 self._ucfg.backup(section, item),)
+
+    @contextmanager
+    def configoverride(self, section, item, value, source=','):
+        """
+        Example use:
+        with ui.configoverride(self, 'experimental', 'crecord', False):
+            # Some code where you override the config experimental.crecord to
+            # be false
+        # experimental.crecord is back to its original value before the with
+        """
+        backup = self.backupconfig(section, item)
+        self.setconfig(section, item, value, source)
+        yield
+        self.restoreconfig(backup)
+
     def restoreconfig(self, data):
         self._ocfg.restore(data[0])
         self._tcfg.restore(data[1])


More information about the Mercurial-devel mailing list