[PATCH RFC] ui: add configoverride context manager
Kostia Balytskyi
ikostia at fb.com
Sun Nov 20 16:13:09 UTC 2016
# HG changeset patch
# User Kostia Balytskyi <ikostia at fb.com>
# Date 1479658212 28800
# Sun Nov 20 08:10:12 2016 -0800
# Node ID b226d57bafe182f379b144ec4f6374fedfc124ef
# Parent 141b0d27e9e1e846215ead5314237536efc1a185
ui: add configoverride context manager
I feel like this idea might've been discussed before, so please
feel free to point me to the right mailing list entry to read
about why it should not be done.
We have a common pattern of the following code:
backup = ui.backupconfig(section, name)
try:
ui.setconfig(section, name, temporaryvalue, source)
do_something()
finally:
ui.restoreconfig(backup)
IMO, this looks better:
with ui.configoverride([(section, name, temporaryvalue)], source):
do_something()
Especially this becomes more convenient when one has to backup multiple
config values before doing something. In such case, adding a new value
to backup requires codemod in three places.
Note that this contextmanager does not have to be a member ui class,
but it felt like the right place to me.
I have tested it manually, but I am not sure how an automated test
can be written here.
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
@@ -1193,6 +1194,26 @@ class ui(object):
" update your code.)") % version
self.develwarn(msg, stacklevel=2, config='deprec-warn')
+ @contextlib.contextmanager
+ def configoverride(self, overrides, source="", quiet=None):
+ """Context manager for temporary config overrides
+ `overrides` must be a list of three-element tuples:
+ [(section, name, value)].
+ `quiet` is an optional override for `ui.quiet`"""
+ backups = {}
+ for override in overrides:
+ section, name, value = override
+ backups[(section, name)] = self.backupconfig(section, name)
+ self.setconfig(section, name, value, source)
+ if quiet is not None:
+ backupquiet = self.quiet
+ self.quiet = quiet
+ yield
+ for __, backup in backups.items():
+ self.restoreconfig(backup)
+ if quiet is not None:
+ self.quiet = backupquiet
+
class paths(dict):
"""Represents a collection of paths and their configs.
More information about the Mercurial-devel
mailing list