~ubuntu-branches/ubuntu/jaunty/pida/jaunty

« back to all changes in this revision

Viewing changes to pida/core/registry.py

  • Committer: Bazaar Package Importer
  • Author(s): Barry deFreese
  • Date: 2006-08-01 13:08:56 UTC
  • mfrom: (0.1.2 etch) (1.1.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20060801130856-v92ktopgdxc8rv7q
Tags: 0.3.1-2ubuntu1
* Re-sync with Debian
* Remove bashisms from debian/rules

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# -*- coding: utf-8 -*- 
 
2
 
 
3
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
 
4
#Copyright (c) 2005 Ali Afshar aafshar@gmail.com
 
5
 
 
6
#Permission is hereby granted, free of charge, to any person obtaining a copy
 
7
#of this software and associated documentation files (the "Software"), to deal
 
8
#in the Software without restriction, including without limitation the rights
 
9
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 
10
#copies of the Software, and to permit persons to whom the Software is
 
11
#furnished to do so, subject to the following conditions:
 
12
 
 
13
#The above copyright notice and this permission notice shall be included in
 
14
#all copies or substantial portions of the Software.
 
15
 
 
16
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 
17
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 
18
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 
19
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 
20
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 
21
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 
22
#SOFTWARE.
 
23
 
 
24
# pida import(s)
 
25
import base
 
26
import errors
 
27
 
 
28
# system import(s)
 
29
import os
 
30
import ConfigParser as configparser
 
31
 
 
32
 
 
33
class registry_item(base.pidacomponent):
 
34
    """A single item in the registry."""
 
35
 
 
36
    def init(self, name, doc, default):
 
37
        self.__name = name
 
38
        if doc is not None:
 
39
            doc = doc.replace('\n', ' ')
 
40
        self.__doc = doc
 
41
        self.__value = None
 
42
        self.__default = default
 
43
 
 
44
    def setdefault(self):
 
45
        self.value = self.__default
 
46
 
 
47
    def validate(self, value):
 
48
        return True
 
49
 
 
50
    def unserialize(self, data):
 
51
        return data
 
52
 
 
53
    def serialize(self):
 
54
        return '%s' % self.value
 
55
 
 
56
    def load(self, data):
 
57
        try:
 
58
            value = self.unserialize(data)
 
59
        except Exception, e:
 
60
            # Any unserialisation error is a failure
 
61
            return False
 
62
        try:
 
63
            self.value = value
 
64
            return True
 
65
        except errors.BadRegistryValueError:
 
66
            self.setdefault()
 
67
            return False
 
68
 
 
69
    def set_value(self, value):
 
70
        if self.validate(value):
 
71
            self.__value = value
 
72
        else:
 
73
            raise errors.BadRegistryValueError, value
 
74
 
 
75
    def get_value(self):
 
76
        return self.__value
 
77
 
 
78
    value = property(get_value, set_value)
 
79
 
 
80
    def get_name(self):
 
81
        return self.__name
 
82
    name = property(get_name)
 
83
 
 
84
    def get_doc(self):
 
85
        return self.__doc
 
86
 
 
87
    def set_doc(self, value):
 
88
        self.__doc = value
 
89
 
 
90
    doc = property(get_doc, set_doc)
 
91
 
 
92
    def get_default(self):
 
93
        return self.__default
 
94
 
 
95
    default = property(get_default)
 
96
 
 
97
    def __repr__(self):
 
98
        return ('Registry Value typ=%s name=%s value=%s default=%s '
 
99
                'doc=%s' % (self.__class__.__name__, self.__name,
 
100
                           self.__value, self.__default, self.doc))
 
101
                    
 
102
class registry_group(base.pidagroup):
 
103
    """A registry group."""
 
104
    
 
105
    group_type = lambda *a: registry_group(*a)
 
106
    def __create_component(self, name, doc, default, typ):
 
107
        return typ(name, doc, default)
 
108
    component_type = __create_component
 
109
 
 
110
    def init(self, name, doc):
 
111
        base.pidagroup.init(self, name)
 
112
        self.__doc = doc
 
113
 
 
114
    def get_doc(self):
 
115
        return self.__doc
 
116
    doc = property(get_doc)
 
117
 
 
118
 
 
119
class registry(base.pidamanager):
 
120
    """The pida registry."""
 
121
 
 
122
    group_type = registry_group
 
123
 
 
124
    file_intro = '# pida generated ini file'
 
125
 
 
126
    def __get_tempopts(self, filename):
 
127
        self.filename = filename
 
128
        tempopts = configparser.ConfigParser()
 
129
        if os.path.exists(self.filename):
 
130
            f = open(self.filename, 'r')
 
131
            tempopts.readfp(f)
 
132
            f.close()
 
133
        return tempopts
 
134
 
 
135
    def load(self, filename):
 
136
        tempopts = self.__get_tempopts(filename)
 
137
        for group, option in self.iter_items():
 
138
            if tempopts.has_option(group.name, option.name):
 
139
                data = tempopts.get(group.name, option.name)
 
140
                if not option.load(data):
 
141
                    option.setdefault()
 
142
            else:
 
143
                option.setdefault()
 
144
 
 
145
    def save(self):
 
146
        f = open(self.filename, 'w')
 
147
        f.write(self.file_intro)
 
148
        for group in self.iter_groups():
 
149
            f.write('\n[%s]\n' % group.name)
 
150
            for option in group:
 
151
                f.write('# %s\n' % option.name)
 
152
                f.write('# %s\n' % option.doc)
 
153
                f.write('# default value = %s\n' % option.default)
 
154
                f.write('%s = %s\n\n' % (option.name, option.value))
 
155
        f.close()
 
156
 
 
157
 
 
158
class types(object):
 
159
    """Types used by the registry."""
 
160
 
 
161
    class string(registry_item):
 
162
        """A plain string."""
 
163
 
 
164
    class directory(registry_item):
 
165
        def validate(self, value):
 
166
            return os.path.isdir(value)
 
167
        
 
168
    class directorycreating(directory):
 
169
        def validate(self, value):
 
170
            if Directory.validate(self, value):
 
171
                return True
 
172
            else:
 
173
                os.makedirs(value)
 
174
                return directory.validate(self, value)
 
175
 
 
176
    class file(registry_item):
 
177
        """"""
 
178
 
 
179
    class filemustexist(file):
 
180
 
 
181
        def validate(self, value):
 
182
            return os.path.exists(value)
 
183
 
 
184
    class filewhich(file):
 
185
    
 
186
        def setdefault(self):
 
187
            import distutils.spawn as spawn
 
188
            path = spawn.find_executable(self.default)
 
189
            if path:
 
190
                self.set(path)
 
191
            else:
 
192
                self.set('')
 
193
 
 
194
    class font(registry_item):
 
195
        """Font"""
 
196
 
 
197
    class boolean(registry_item):
 
198
        def unserialize(self, data):
 
199
            try:
 
200
                val = int(data)
 
201
            except ValueError:
 
202
                val = int(data[0].lower() in ['t'])
 
203
            except:
 
204
                raise errors.BadRegistryDataError
 
205
            return val
 
206
 
 
207
    class integer(registry_item):
 
208
        def unserialize(self, data):
 
209
            try:
 
210
                val = int(data)
 
211
            except:
 
212
                raise errors.BadRegistryDataError
 
213
            return val
 
214
 
 
215
    class list(registry_item):
 
216
        """"""
 
217
 
 
218
    class editor(list):
 
219
        # see #101
 
220
        choices = ['vim', 'culebra', 'emacs', 'scerpent']
 
221
 
 
222
    class color(registry_item):
 
223
        """"""
 
224
 
 
225
    class fileembedded(registry_item):
 
226
        """"""
 
227
 
 
228
    class password(registry_item):
 
229
        """A password item."""
 
230
 
 
231
    @staticmethod
 
232
    def intrange(lower, upper, step):
 
233
        # can't use class call
 
234
        classdict = {'lower': lower,
 
235
                     'upper': upper,
 
236
                     'step': step}
 
237
        return type('intrange', (types.integer,), classdict)
 
238
    
 
239
    @staticmethod
 
240
    def stringlist(*args):
 
241
        classdict = {'choices': args}
 
242
        return type('stringlist', (types.list,), classdict)
 
243
 
 
244
CONFIG_FILE_INTRO = (
 
245
    '#This is an automatically generated Pida config file.\n'
 
246
    '#Please edit it, your changes will be preserved (if valid).\n'
 
247
    '#If you want a fresh config file, delete it.\n\n'
 
248
    '#Notes:\n'
 
249
    '#Boolean values are 1 or 0\n'
 
250
    '#Blank lines are ignored as are lines beginning #\n'
 
251
    '#(comments).\n\n')
 
252
 
 
253