comparison mercurial/ui.py @ 30480:b0a8337ba9af

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.
author Kostia Balytskyi <ikostia@fb.com>
date Mon, 21 Nov 2016 16:22:26 -0800
parents 39d13b8c101d
children 20a42325fdef
comparison
equal deleted inserted replaced
30479:798bcb1274dd 30480:b0a8337ba9af
5 # This software may be used and distributed according to the terms of the 5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version. 6 # GNU General Public License version 2 or any later version.
7 7
8 from __future__ import absolute_import 8 from __future__ import absolute_import
9 9
10 import contextlib
10 import errno 11 import errno
11 import getpass 12 import getpass
12 import inspect 13 import inspect
13 import os 14 import os
14 import re 15 import re
1191 return 1192 return
1192 msg += ("\n(compatibility will be dropped after Mercurial-%s," 1193 msg += ("\n(compatibility will be dropped after Mercurial-%s,"
1193 " update your code.)") % version 1194 " update your code.)") % version
1194 self.develwarn(msg, stacklevel=2, config='deprec-warn') 1195 self.develwarn(msg, stacklevel=2, config='deprec-warn')
1195 1196
1197 @contextlib.contextmanager
1198 def configoverride(self, overrides, source=""):
1199 """Context manager for temporary config overrides
1200 `overrides` must be a dict of the following structure:
1201 {(section, name) : value}"""
1202 backups = {}
1203 for (section, name), value in overrides.items():
1204 backups[(section, name)] = self.backupconfig(section, name)
1205 self.setconfig(section, name, value, source)
1206 yield
1207 for __, backup in backups.items():
1208 self.restoreconfig(backup)
1209 # just restoring ui.quiet config to the previous value is not enough
1210 # as it does not update ui.quiet class member
1211 if ('ui', 'quiet') in overrides:
1212 self.fixconfig(section='ui')
1213
1196 class paths(dict): 1214 class paths(dict):
1197 """Represents a collection of paths and their configs. 1215 """Represents a collection of paths and their configs.
1198 1216
1199 Data is initially derived from ui instances and the config files they have 1217 Data is initially derived from ui instances and the config files they have
1200 loaded. 1218 loaded.