summaryrefslogtreecommitdiff
path: root/pecan/configuration.py
blob: bb0f4e15b6f0ff45870c34cb205aa83261cdddab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import re
import inspect
import os
import string

IDENTIFIER = re.compile(r'[a-z_](\w)*$', re.IGNORECASE)
STRING_FORMAT = re.compile(r'{pecan\.conf(?P<var>([.][a-z_][\w]*)+)+?}', re.IGNORECASE)

class ConfigString(object):
    def __init__(self, format_string):
        self.raw_string = format_string

    def __call__(self):
        retval = self.raw_string

        for candidate in STRING_FORMAT.finditer(self.raw_string):
            var = candidate.groupdict().get('var','')

            try:
                obj = _runtime_conf
                for dotted_part in var.split('.'):
                    if dotted_part == '':
                        continue
                    obj = getattr(obj, dotted_part)
                
                retval = retval.replace(candidate.group(), str(obj))

            except AttributeError, e:
                raise AttributeError, 'Cannot substitute \'%s\' using the current configuration' % candidate.group()

        return retval

    def __str__(self):
        return self.raw_string

    @staticmethod
    def contains_formatting(value):
        return STRING_FORMAT.match(value)

class Config(object):
    def __init__(self, conf_dict={}):
        self.update(conf_dict)

    def update(self, conf_dict):
        # first check the keys for correct

        if isinstance(conf_dict, dict):
            iterator = conf_dict.iteritems()
        else:
            iterator = iter(conf_dict)

        for k,v in iterator:
            if not IDENTIFIER.match(k):
                raise ValueError('\'%s\' is not a valid indentifier' % k)

            cur_val = self.__dict__.get(k)

            if isinstance(cur_val, Config):
                cur_val.update(conf_dict[k])
            else:
                self[k] = conf_dict[k]

    def update_with_module(self, module):
        self.update(conf_from_module(module))

    def __getitem__(self, key):
        return self.__dict__[key]

    def __setitem__(self, key, value):
        if isinstance(value, dict):
            self.__dict__[key] = Config(value)
        elif isinstance(value, str) and ConfigString.contains_formatting(value):
            self.__dict__[key] = ConfigString(value)
        else:
            self.__dict__[key] = value

    def __iter__(self):
        return self.__dict__.iteritems()

    def __dir__(self):
        return self.__dict__.keys()

    def __repr__(self):
        return 'Config(%s)' % str(self.__dict__)

    def __call__(self):
        for k,v in self:
            if isinstance(v, Config):
                v()
            elif hasattr(v, '__call__'):
                self.__dict__[k] = v()
        return self



def conf_from_module(module):
    if isinstance(module, str):
        module = import_module(module)

    module_dict = dict(inspect.getmembers(module))

    return conf_from_dict(module_dict)

def conf_from_file(filepath):
    abspath = os.path.abspath(os.path.expanduser(filepath))
    conf_dict = {}

    execfile(abspath, globals(), conf_dict)
    conf_dict['__file__'] = abspath

    return conf_from_dict(conf_dict)

def conf_from_dict(conf_dict):
    conf = Config()

    # set the configdir
    conf_dir = os.path.dirname(conf_dict.get('__file__', ''))
    if conf_dir == '':
        conf_dir = os.getcwd()

    conf['__confdir__'] = conf_dir + '/'

    for k,v in conf_dict.iteritems():
        if k.startswith('__'):
            continue
        elif inspect.ismodule(v):
            continue
        
        if isinstance(v, dict):
            conf[k] = Config(v)
        else:
            conf[k] = v
    conf()
    return conf

def import_module(conf):
    if '.' in conf:
        parts = conf.split('.')
        name = '.'.join(parts[:-1])
        fromlist = parts[-1:]

        try:
            module = __import__(name, fromlist=fromlist)
            conf_mod = getattr(module, parts[-1])
        except ImportError, e:
            raise ImportError('No module named %s' % conf)
        except AttributeError, e:
            raise ImportError('No module named %s' % conf)
    else:
        name = conf

        try:
            conf_mod =  __import__(name)
        except ImportError, e:
            raise ImportError('No module named %s' % conf)

    return conf_mod

def initconf():
    import default_config
    conf = conf_from_module(default_config)
    conf()
    return conf

def set_config(name):
    if '/' in name:
        _runtime_conf.update(conf_from_file(name))
    else:
        _runtime_conf.update_with_module(name)

_runtime_conf = initconf()