summaryrefslogtreecommitdiff
path: root/extras/ConfigPersist.py
blob: 42dca3792b6a42d13393ba2c8816b0cd8d501d7b (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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# ConfigPersist.py
# Functions for using ConfigObj for data persistence
# Copyright (C) 2005 Michael Foord
# E-mail: fuzzyman AT voidspace DOT org DOT uk

# Released subject to the BSD License
# Please see http://www.voidspace.org.uk/python/license.shtml

# Scripts maintained at http://www.voidspace.org.uk/python/index.shtml
# For information about bugfixes, updates and support, please join the
# ConfigObj mailing list:
# http://lists.sourceforge.net/lists/listinfo/configobj-develop
# Comments, suggestions and bug reports welcome.

"""
Functions for doing data persistence with ConfigObj.

It requires access to the validate module and ConfigObj.
"""

__version__ = '0.1.0'

__all__ = (
    'add_configspec',
    'write_configspec',
    'add_typeinfo',
    'typeinfo_to_configspec',
    'vtor',
    'store',
    'restore',
    'save_configspec',
    '__version__'
    )

from configobj import ConfigObj

try:
    from validate import Validator
except ImportError:
    vtor = None
else:
    vtor = Validator()

def add_configspec(config):
    """
    A function that adds a configspec to a ConfigObj.
    
    Will only work for ConfigObj instances using basic datatypes :
    
        * floats
        * strings
        * ints
        * booleans
        * Lists of the above
    """
    config.configspec = {}
    for entry in config:
        val = config[entry]
        if isinstance(val, dict):
            # a subsection
            add_configspec(val)
        elif isinstance(val, bool):
            config.configspec[entry] = 'boolean'
        elif isinstance(val, int):
            config.configspec[entry] = 'integer'
        elif isinstance(val, float):
            config.configspec[entry] = 'float'
        elif isinstance(val, str):
            config.configspec[entry] = 'string'
        elif isinstance(val, (list, tuple)):
            list_type = None
            out_list = []
            for mem in val:
                if isinstance(mem, str):
                    this = 'string'
                elif isinstance(mem, bool):
                    this = 'boolean'
                elif isinstance(mem, int):
                    this = 'integer'
                elif isinstance(mem, float):
                    this = 'float'
                else:
                    raise TypeError('List member  "%s" is an innapropriate type.' % mem)
                if list_type and this != list_type:
                    list_type = 'mixed'
                elif list_type is None:
                    list_type = this
                out_list.append(this)
            if list_type is None:
                l = 'list(%s)'
            else:
                list_type = {'integer': 'int', 'boolean': 'bool',
                             'mixed': 'mixed', 'float': 'float',
                            'string': 'string' }[list_type]
                l = '%s_list(%%s)' % list_type
            config.configspec[entry] = l % str(out_list)[1:-1]
        #
        else:
            raise TypeError('Value "%s" is an innapropriate type.' % val)

def write_configspec(config):
    """Return the configspec (of a ConfigObj) as a list of lines."""
    out = []
    for entry in config:
        val = config[entry]
        if isinstance(val, dict):
            # a subsection
            m = config.main._write_marker('', val.depth, entry, '')
            out.append(m)
            out += write_configspec(val)
        else:
            name = config.main._quote(entry, multiline=False)
            out.append("%s = %s" % (name, config.configspec[entry]))
    #
    return out

def add_typeinfo(config):
    """
    Turns the configspec attribute of each section into a member of the
    section. (Called ``__types__``).
    
    You must have already called ``add_configspec`` on the ConfigObj.
    """
    for entry in config.sections:
        add_typeinfo(config[entry])
    config['__types__'] = config.configspec

def typeinfo_to_configspec(config):
    """Turns the '__types__' member of each section into a configspec."""
    for entry in config.sections:
        if entry == '__types__':
            continue
        typeinfo_to_configspec(config[entry])
    config.configspec = config['__types__']
    del config['__types__']

def store(config):
    """"
    Passed a ConfigObj instance add type info and save.
    
    Returns the result of calling ``config.write()``.
    """
    add_configspec(config)
    add_typeinfo(config)
    return config.write()

def restore(stored):
    """
    Restore a ConfigObj saved using the ``store`` function.
    
    Takes a filename or list of lines, returns the ConfigObj instance.
    
    Uses the built-in Validator instance of this module (vtor).
    
    Raises an ImportError if the validate module isn't available
    """
    if vtor is None:
        raise ImportError('Failed to import the validate module.')
    config = ConfigObj(stored)
    typeinfo_to_configspec(config)
    config.validate(vtor)
    return config

def save_configspec(config):
    """Creates a configspec and returns it as a list of lines."""
    add_configspec(config)
    return write_configspec(config)

def _test():
    """
    A dummy function for the sake of doctest.
    
    First test add_configspec
    >>> from configobj import ConfigObj
    >>> from validate import Validator
    >>> vtor = Validator()
    >>> config = ConfigObj()
    >>> config['member 1'] = 3
    >>> config['member 2'] = 3.0
    >>> config['member 3'] = True
    >>> config['member 4'] = [3, 3.0, True]
    >>> add_configspec(config)
    >>> assert config.configspec == { 'member 2': 'float',
    ...    'member 3': 'boolean', 'member 1': 'integer',
    ...    'member 4': "mixed_list('integer', 'float', 'boolean')"}
    >>> assert config.validate(vtor) == True
    
    Next test write_configspec - including a nested section
    >>> config['section 1'] = config.copy()
    >>> add_configspec(config)
    >>> a = config.write()
    >>> configspec = write_configspec(config)
    >>> b = ConfigObj(a, configspec=configspec)
    >>> assert b.validate(vtor) == True
    >>> assert b == config
    
    Next test add_typeinfo and typeinfo_to_configspec
    >>> orig = ConfigObj(config)
    >>> add_typeinfo(config)
    >>> a = ConfigObj(config.write())
    >>> typeinfo_to_configspec(a)
    >>> assert a.validate(vtor) == True
    >>> assert a == orig
    >>> typeinfo_to_configspec(config)
    >>> assert config.validate(vtor) == True
    >>> assert config == orig
    
    Test store and restore
    >>> a = store(config)
    >>> b = restore(a)
    >>> assert b == orig
    
    Test save_configspec
    >>> a = save_configspec(orig)
    >>> b = ConfigObj(b, configspec=a)
    >>> b.validate(vtor)
    1
    """

if __name__ == '__main__':
    # run the code tests in doctest format
    #
    import doctest
    doctest.testmod()

"""
ISSUES
======

TODO
====


CHANGELOG
=========

2005/09/07
----------

Module created.

"""