Mercurial > hg
changeset 19065:2c4cd1c42365
ui: add a configbytes method, for space configuration
This accepts a floating point number, followed by optional whitespace,
followed by an optional one- or two-letter unit specifier (for
bytes, kilobytes, megabytes, or gigabytes).
author | Bryan O'Sullivan <bryano@fb.com> |
---|---|
date | Thu, 18 Apr 2013 12:58:28 -0700 |
parents | 743daa601445 |
children | 2cad301a7f06 |
files | mercurial/ui.py |
diffstat | 1 files changed, 40 insertions(+), 1 deletions(-) [+] |
line wrap: on
line diff
--- a/mercurial/ui.py Thu Apr 18 23:53:39 2013 +0200 +++ b/mercurial/ui.py Thu Apr 18 12:58:28 2013 -0700 @@ -6,7 +6,7 @@ # GNU General Public License version 2 or any later version. from i18n import _ -import errno, getpass, os, socket, sys, tempfile, traceback +import errno, getpass, os, re, socket, sys, tempfile, traceback import config, scmutil, util, error, formatter class ui(object): @@ -262,6 +262,45 @@ raise error.ConfigError(_("%s.%s is not an integer ('%s')") % (section, name, v)) + def configbytes(self, section, name, default=0, untrusted=False): + """parse a configuration element as a quantity in bytes + + Units can be specified as b (bytes), k or kb (kilobytes), m or + mb (megabytes), g or gb (gigabytes). + + >>> u = ui(); s = 'foo' + >>> u.setconfig(s, 'val1', '42') + >>> u.configbytes(s, 'val1') + 42 + >>> u.setconfig(s, 'val2', '42.5 kb') + >>> u.configbytes(s, 'val2') + 43520 + >>> u.configbytes(s, 'unknown', '7 MB') + 7340032 + >>> u.setconfig(s, 'invalid', 'somevalue') + >>> u.configbytes(s, 'invalid') + Traceback (most recent call last): + ... + ConfigError: foo.invalid is not a byte quantity ('somevalue') + """ + + orig = string = self.config(section, name) + if orig is None: + if not isinstance(default, str): + return default + orig = string = default + multiple = 1 + m = re.match(r'([^kmbg]+?)\s*([kmg]?)b?$', string, re.I) + if m: + string, key = m.groups() + key = key.lower() + multiple = dict(k=1024, m=1048576, g=1073741824).get(key, 1) + try: + return int(float(string) * multiple) + except ValueError: + raise error.ConfigError(_("%s.%s is not a byte quantity ('%s')") + % (section, name, orig)) + def configlist(self, section, name, default=None, untrusted=False): """parse a configuration element as a list of comma/space separated strings