ui: add a configwith method
authorBryan O'Sullivan <bryano@fb.com>
Sun, 12 Feb 2017 21:40:46 -0800
changeset 30926 120682fce099
parent 30925 82f1ef8b4477
child 30927 8fa3ab6221b9
ui: add a configwith method This is a long-overdue generalization of the pattern in configint and configbool.
mercurial/ui.py
--- a/mercurial/ui.py	Mon Feb 13 22:15:28 2017 +0530
+++ b/mercurial/ui.py	Sun Feb 12 21:40:46 2017 -0800
@@ -402,6 +402,41 @@
                                     % (section, name, v))
         return b
 
+    def configwith(self, convert, section, name, default=None,
+                   desc=None, untrusted=False):
+        """parse a configuration element with a conversion function
+
+        >>> u = ui(); s = 'foo'
+        >>> u.setconfig(s, 'float1', '42')
+        >>> u.configwith(float, s, 'float1')
+        42.0
+        >>> u.setconfig(s, 'float2', '-4.2')
+        >>> u.configwith(float, s, 'float2')
+        -4.2
+        >>> u.configwith(float, s, 'unknown', 7)
+        7
+        >>> u.setconfig(s, 'invalid', 'somevalue')
+        >>> u.configwith(float, s, 'invalid')
+        Traceback (most recent call last):
+            ...
+        ConfigError: foo.invalid is not a valid float ('somevalue')
+        >>> u.configwith(float, s, 'invalid', desc='womble')
+        Traceback (most recent call last):
+            ...
+        ConfigError: foo.invalid is not a valid womble ('somevalue')
+        """
+
+        v = self.config(section, name, None, untrusted)
+        if v is None:
+            return default
+        try:
+            return convert(v)
+        except ValueError:
+            if desc is None:
+                desc = convert.__name__
+            raise error.ConfigError(_("%s.%s is not a valid %s ('%s')")
+                                    % (section, name, desc, v))
+
     def configint(self, section, name, default=None, untrusted=False):
         """parse a configuration element as an integer