Patchwork [1,of,5,v2] ui: add a configwith method

login
register
mail settings
Submitter Bryan O'Sullivan
Date Feb. 13, 2017, 6:39 a.m.
Message ID <0be0dffb7a83d1a973a0.1486967993@bryano-mbp.local>
Download mbox | patch
Permalink /patch/18431/
State Accepted
Headers show

Comments

Bryan O'Sullivan - Feb. 13, 2017, 6:39 a.m.
# HG changeset patch
# User Bryan O'Sullivan <bryano@fb.com>
# Date 1486964446 28800
#      Sun Feb 12 21:40:46 2017 -0800
# Node ID 0be0dffb7a83d1a973a0913230223cfd456a3148
# Parent  a0e3d808690d57d1c9dff840e0b8ee099526397b
ui: add a configwith method

This is a long-overdue generalization of the pattern in configint
and configbool.

Patch

diff --git a/mercurial/ui.py b/mercurial/ui.py
--- a/mercurial/ui.py
+++ b/mercurial/ui.py
@@ -402,6 +402,41 @@  class ui(object):
                                     % (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