Limnoria/src/registry.py

285 lines
9.0 KiB
Python
Raw Normal View History

2004-01-13 07:07:31 +01:00
#!/usr/bin/env python
###
2004-01-13 16:56:58 +01:00
# Copyright (c) 2004, Jeremiah Fincher
2004-01-13 07:07:31 +01:00
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
__revision__ = "$Id$"
import copy
import utils
class RegistryException(Exception):
pass
class InvalidRegistryValue(RegistryException):
pass
class NonExistentRegistryEntry(RegistryException):
pass
2004-01-14 07:05:58 +01:00
cache = {}
def open(filename):
"""Initializes the module by loading the registry file into memory."""
cache.clear()
fd = utils.nonCommentNonEmptyLines(file(filename))
for line in fd:
line = line.rstrip()
(key, value) = line.split(': ', 1)
cache[key] = value
def close(registry, filename):
fd = file(filename, 'w')
for (name, value) in registry.getValues(askChildren=True):
fd.write('%s: %s\n' % (name, value))
fd.close()
2004-01-13 07:07:31 +01:00
class Value(object):
def __init__(self, default, help):
2004-01-13 16:56:58 +01:00
self.help = utils.normalizeWhitespace(help)
2004-01-13 07:07:31 +01:00
self.value = default
def set(self, s):
"""Override this with a function to convert a string to whatever type
you want, and set it to .value."""
# self.value = value
raise NotImplementedError
def get(self):
return self.value
def __str__(self):
return repr(self.value)
class Boolean(Value):
def set(self, s):
s = s.lower()
if s in ('true', 'on', 'enabled'):
self.value = True
elif s in ('false', 'off', 'disabled'):
self.value = False
else:
raise InvalidRegistryValue, 'Value must be True or False.'
class Integer(Value):
def set(self, s):
try:
self.value = int(s)
except ValueError:
raise InvalidRegistryValue, 'Value must be an integer.'
class String(Value):
def set(self, s):
if s and s[0] not in '\'"' and s[-1] not in '\'"':
s = repr(s)
try:
v = utils.safeEval(s)
if type(v) is not str:
raise ValueError
self.value = v
except ValueError: # This catches utils.safeEval(s) errors too.
raise InvalidRegistryValue, 'Value must be a string.'
class StringSurroundedBySpaces(String):
def set(self, s):
String.set(self, s)
if self.value.lstrip() == self.value:
self.value = ' ' + self.value
if self.value.rstrip() == self.value:
self.value += ' '
class Group(object):
def __init__(self):
self.__dict__['name'] = 'unset'
self.__dict__['values'] = {}
self.__dict__['children'] = {}
self.__dict__['originals'] = {}
2004-01-13 16:56:58 +01:00
def __nonExistentEntry(self, attr):
s = '%s is not a valid entry in %s' % (attr, self.name)
raise NonExistentRegistryEntry, s
2004-01-13 07:07:31 +01:00
def __getattr__(self, attr):
original = attr
attr = attr.lower()
if attr in self.values:
return self.values[attr].get()
elif attr in self.children:
return self.children[attr]
else:
2004-01-13 16:56:58 +01:00
self.__nonExistentEntry(original)
2004-01-13 07:07:31 +01:00
def __setattr__(self, attr, s):
original = attr
attr = attr.lower()
if attr in self.values:
self.values[attr].set(s)
elif attr in self.children and hasattr(self.children[attr], 'set'):
self.children[attr].set(s)
2004-01-13 07:07:31 +01:00
else:
2004-01-13 16:56:58 +01:00
self.__nonExistentEntry(original)
2004-01-13 07:07:31 +01:00
def get(self, attr):
return self.__getattr__(attr)
2004-01-13 16:56:58 +01:00
def help(self, attr):
original = attr
attr = attr.lower()
if attr in self.values:
return self.values[attr].help
elif attr in self.children and hasattr(self.children[attr], 'help'):
return self.children[attr].help
else:
self.__nonExistentEntry(original)
2004-01-13 07:07:31 +01:00
def setName(self, name):
self.__dict__['name'] = name
def getName(self):
return self.__dict__['name']
def register(self, name, value):
original = name
name = name.lower()
if name in self.values:
value.set(str(self.values[name]))
self.values[name] = value
2004-01-13 16:56:58 +01:00
self.originals[name] = original
2004-01-14 07:05:58 +01:00
if cache:
fullname = '%s.%s' % (self.name, name)
if fullname in cache:
value.set(cache[fullname])
2004-01-13 07:07:31 +01:00
def registerGroup(self, name, group=None):
original = name
name = name.lower()
if group is None:
group = Group()
if name in self.children:
group.__dict__['values'] = self.children[name].values
group.__dict__['children'] = self.children[name].children
self.children[name] = group
2004-01-13 16:56:58 +01:00
self.originals[name] = original
2004-01-14 07:05:58 +01:00
fullname = '%s.%s' % (self.name, name)
group.setName(fullname)
if cache and fullname in cache:
group.set(cache[fullname])
2004-01-13 07:07:31 +01:00
2004-01-14 07:05:58 +01:00
def getValues(self, askChildren=False):
2004-01-13 07:07:31 +01:00
L = []
items = self.values.items()
2004-01-14 15:18:56 +01:00
utils.sortBy(lambda (k, _): (k.lower(), len(k), k), items)
2004-01-13 07:07:31 +01:00
for (name, value) in items:
L.append(('%s.%s' % (self.getName(), name), str(value)))
2004-01-14 07:05:58 +01:00
if askChildren:
items = self.children.items()
2004-01-14 15:18:56 +01:00
utils.sortBy(lambda (k, _): (k.lower(), len(k), k), items)
2004-01-14 07:05:58 +01:00
for (_, child) in items:
L.extend(child.getValues(askChildren))
2004-01-13 07:07:31 +01:00
return L
class GroupWithDefault(Group):
def __init__(self, value):
Group.__init__(self)
self.__dict__['value'] = value
2004-01-13 16:56:58 +01:00
self.__dict__['help'] = value.help
2004-01-13 07:07:31 +01:00
2004-01-14 07:05:58 +01:00
def __makeChild(self, attr, s):
v = copy.copy(self.value)
v.set(s)
self.register(attr, v)
2004-01-13 07:07:31 +01:00
def __getattr__(self, attr):
try:
return Group.__getattr__(self, attr)
except NonExistentRegistryEntry:
return self.value.get()
def __setattr__(self, attr, s):
try:
Group.__setattr__(self, attr, s)
except NonExistentRegistryEntry:
2004-01-14 07:05:58 +01:00
self.__makeChild(attr, s)
def setName(self, name):
Group.setName(self, name)
for (k, v) in cache.iteritems():
if k.startswith(self.name):
(_, group) = rsplit(k, '.', 1)
self.__makeChild(group, v)
2004-01-13 07:07:31 +01:00
def set(self, *args):
if len(args) == 1:
self.value.set(args[0])
else:
assert len(args) == 2
(attr, s) = args
self.__setattr__(attr, s)
2004-01-13 07:07:31 +01:00
2004-01-14 07:05:58 +01:00
def getValues(self, askChildren=False):
L = Group.getValues(self, askChildren)
2004-01-13 07:07:31 +01:00
L.insert(0, (self.getName(), str(self.value)))
return L
if __name__ == '__main__':
supybot = Group()
supybot.setName('supybot')
supybot.register('throttleTime', Integer(1, """Determines the minimum
number of seconds the bot will wait between sending messages to the server.
"""))
supybot.registerGroup('plugins')
supybot.plugins.registerGroup('topic')
supybot.plugins.topic.registerGroup('separator',
GroupWithDefault(StringSurroundedBySpaces(' || ',
'Determines what separator the bot uses to separate topic entries.')))
supybot.plugins.topic.separator.set('#supybot', ' |||| ')
supybot.plugins.topic.separator.set(' <> ')
2004-01-13 07:07:31 +01:00
for (k, v) in supybot.getValues():
print '%s: %s' % (k, v)
2004-01-13 16:56:58 +01:00
2004-01-14 07:05:58 +01:00
print
print 'Asking children'
print
for (k, v) in supybot.getValues(askChildren=True):
print '%s: %s' % (k, v)
2004-01-13 16:56:58 +01:00
print supybot.help('throttleTime')
print supybot.plugins.topic.help('separator')
2004-01-13 07:07:31 +01:00
# vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78: