PageRenderTime 82ms CodeModel.GetById 40ms app.highlight 8ms RepoModel.GetById 32ms app.codeStats 0ms

/silversupport/util.py

https://bitbucket.org/ianb/silverlining/
Python | 84 lines | 75 code | 9 blank | 0 comment | 15 complexity | 0b7f9839dd0f308a288be57fc02e7d65 MD5 | raw file
 1import os
 2import string
 3from ConfigParser import ConfigParser
 4
 5__all__ = ['unique_name', 'asbool', 'read_config', 'fill_config_environ']
 6
 7
 8def unique_name(dest_dir, name):
 9    n = 0
10    result = name
11    while 1:
12        dest = os.path.join(dest_dir, result)
13        if not os.path.exists(dest):
14            return dest
15        n += 1
16        result = '%s_%03i' % (name, n)
17
18
19def asbool(obj, default=ValueError):
20    if isinstance(obj, (str, unicode)):
21        obj = obj.strip().lower()
22        if obj in ['true', 'yes', 'on', 'y', 't', '1']:
23            return True
24        elif obj in ['false', 'no', 'off', 'n', 'f', '0']:
25            return False
26        else:
27            if default is not ValueError:
28                return default
29            raise ValueError(
30                "String is not true/false: %r" % obj)
31    return bool(obj)
32
33
34def read_config(filename):
35    if not os.path.exists(filename):
36        raise ValueError('No file %s' % filename)
37    parser = ConfigParser()
38    parser.read([filename])
39    config = {}
40    for section in parser.sections():
41        for option in parser.options(section):
42            config.setdefault(section, {})[option] = parser.get(section, option)
43    return config
44
45
46def fill_config_environ(config, default=''):
47    """Fills in configuration values using string.Template
48    substitution of environ variables
49
50    If default is KeyError, then empty substitutions will raise KeyError
51    """
52    vars = _EnvironDict(os.environ, default)
53
54    def fill(value):
55        return string.Template(value).substitute(vars)
56    config = config.copy()
57    _recursive_dict_fill(config, fill)
58    return config
59
60
61def _recursive_dict_fill(obj, filler):
62    for key, value in obj.items():
63        if isinstance(value, basestring):
64            obj[key] = filler(value)
65        elif isinstance(value, dict):
66            _recursive_dict_fill(value, filler)
67
68
69class _EnvironDict(object):
70
71    def __init__(self, source, default=''):
72        self.source = source
73        self.default = default
74
75    def __getitem__(self, key):
76        if key in self.source:
77            obj = self.source[key]
78            if obj is None:
79                return ''
80            return obj
81        if self.default is KeyError:
82            raise KeyError(key)
83        else:
84            return self.default