[PATCH 1 of 5 v2] ui: add a configwith method
Bryan O'Sullivan
bos at serpentine.com
Mon Feb 13 06:39:53 UTC 2017
# HG changeset patch
# User Bryan O'Sullivan <bryano at 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.
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
More information about the Mercurial-devel
mailing list