Author: dmeyer
Date: Sun Oct 16 14:14:28 2005
New Revision: 7714
Added:
trunk/freevo-core/src/cfgparse.py
trunk/freevo-core/src/fxdparser.py
- copied, changed from r7699, /trunk/freevo/src/util/fxdparser.py
Modified:
trunk/freevo-core/src/conf.py
Log:
add self made config parser
Added: trunk/freevo-core/src/cfgparse.py
==============================================================================
--- (empty file)
+++ trunk/freevo-core/src/cfgparse.py Sun Oct 16 14:14:28 2005
@@ -0,0 +1,177 @@
+import os
+import re
+
+re_section = re.compile('\[(.*)\]')
+re_variable = re.compile('(.*?) *= *(.*)')
+
+class ParseError:
+ def __init__(self, error):
+ self.error = error
+
+ def __str__(self):
+ return self.error
+
+
+class Variable(object):
+ def __init__(self, key, value, pos, comment):
+ self.key = key
+ self.value = value
+ self.pos = pos
+ self.comment = comment
+
+
+class Section(object):
+ def __init__(self, name, pos, schema):
+ self.name = name
+ self.pos = pos
+ self.comment = []
+ self.dict = {}
+ self.prefix = ''
+ if self.name and self.name != 'general':
+ self.prefix = '%s_' % self.name.upper()
+ self.schema = {}
+ for key, type in schema.items():
+ if key.upper().startswith(self.prefix):
+ self.schema[key[len(self.prefix):]] = type
+
+ def set(self, key, value, comment=[]):
+ try:
+ if key.upper() in self.schema:
+ if self.schema[key.upper()] == bool:
+ if value in ('1', 1, 'True', 'TRUE', 'true', True):
+ value = True
+ elif value in ('0', 0, 'False', 'FALSE', 'false', False):
+ value = False
+ else:
+ raise ParseError
+ else:
+ value = self.schema[key.upper()](value)
+ except:
+ raise ParseError('%s in %s must be %s' % (key, self.name,
self.schema[key.upper()]))
+ if self.dict.has_key(key):
+ self.dict[key].value = value
+ if comment:
+ self.dict[key].comment = comment
+ else:
+ self.dict[key] = Variable(key, value, len(self.dict), comment)
+
+
+ def write(self, f):
+ if self.comment:
+ f.write('\n')
+ for c in self.comment:
+ f.write('%s\n' % c)
+ if self.name:
+ f.write('\n[%s]\n' % self.name)
+ if self.comment:
+ f.write('\n')
+ vars = self.dict.values()[:]
+ vars.sort(lambda x,y: cmp(x.pos, y.pos))
+ for v in vars:
+ for c in v.comment:
+ f.write('%s\n' % c)
+ f.write('%s = %s\n' % (v.key, v.value))
+ if v.comment:
+ f.write('\n')
+
+ def __getitem__(self, key):
+ return self.get(key)
+
+
+ def __setitem__(self, key, value):
+ return self.set(key, value)
+
+
+ def get(self, key, default=''):
+ try:
+ return self.dict[key].value
+ except KeyError:
+ return default
+
+
+ def getint(self, key, default=0):
+ return int(self.get(key, default))
+
+
+ def getboolean(self, key, default=True):
+ if self.get(key, str(default)).lower() in ('1', 'true', 'yes'):
+ return True
+ else:
+ return False
+
+ def variables(self):
+ return self.dict.keys()
+
+ def normalize(self):
+ ret = []
+ for v in self.dict.values():
+ ret.append(('%s%s' % (self.prefix, v.key.upper()), v.value))
+ return ret
+
+ def __iter__(self):
+ return self.dict.__iter__()
+
+class ConfigParser(object):
+ def __init__(self, schema={}):
+ self.__sections = { '': Section('', 0, schema) }
+ self.schema = schema
+
+ def read(self, filename):
+ f = open(filename)
+ comment = []
+ current = self.__sections['']
+
+ for lineno, line in enumerate(f.readlines()):
+ line = line.strip()
+ if line.startswith('#'):
+ comment.append(line)
+ elif re_section.match(line):
+ current = re_section.match(line).groups()[0].strip()
+ if not self.__sections.has_key(current):
+ s = Section(current, len(self.__sections), self.schema)
+ self.__sections[current] = s
+ current = self.__sections[current]
+ if comment:
+ current.comment = comment
+ comment = []
+ elif re_variable.match(line):
+ key, value = re_variable.match(line).groups()
+ current.set(key, value, comment)
+ comment = []
+ elif line:
+ f.close()
+ raise ParseError('invalid line %s in %s' % (lineno, filename))
+ f.close()
+
+ def write(self, f):
+ sections = self.__sections.values()[:]
+ sections.sort(lambda x,y: cmp(x.pos, y.pos))
+ for s in sections:
+ s.write(f)
+
+ def sections(self):
+ s = self.__sections.keys()
+ s.remove('')
+ return s
+
+ def variables(self):
+ return self.__sections[''].variables()
+
+ def __getitem__(self, section):
+ if self.__sections.has_key(section):
+ return self.__sections[section]
+ else:
+ return self.__sections[''][section]
+
+ def normalize(self):
+ ret = []
+ for s in self.__sections.values():
+ ret += s.normalize()
+ return ret
+
+# c = ConfigParser()
+# c.load('test.ini')
+# c.load('self.ini')
+# c['recordings'].set('hallo', 7)
+# print c['recordings']['hallo']
+# c.save('foo')
Modified: trunk/freevo-core/src/conf.py
==============================================================================
--- trunk/freevo-core/src/conf.py (original)
+++ trunk/freevo-core/src/conf.py Sun Oct 16 14:14:28 2005
@@ -56,7 +56,7 @@
# That's it, you shouldn't need to make changes after this point
-__all__ = [ 'Unicode', 'String', 'cachefile', 'datafile' ]
+__all__ = [ 'Config', 'Unicode', 'String', 'cachefile', 'datafile',
'SHAREDIR', 'DATADIR' ]
# Python imports
import os
@@ -64,59 +64,48 @@
import locale
import __builtin__
import logging
-import ConfigParser
+from cfgparse import ConfigParser
-class Section(object):
- def __init__(self, section, config):
- self.section = section
- self.config = config
-
- def getint(self, option, default=0):
- try:
- return self.config.getint(self.section, option)
- except ConfigParser.NoOptionError:
- return default
-
- def get(self, option, default=''):
- try:
- return self.config.get(self.section, option)
- except ConfigParser.NoOptionError:
- return default
-
- def getboolean(self, option, default=True):
- try:
- return self.config.getboolean(self.section, option)
- except ConfigParser.NoOptionError:
- return default
-
- def set(self, option, value):
- self.config.set(self.section, option, value)
-
-
-class Config(object):
- def __init__(self, filename):
- self.data = ConfigParser.ConfigParser()
- self.data.read(filename)
- self.filename = filename
-
- def save(self):
- f = open(self.filename, 'w')
- self.data.write(f)
- f.close()
-
- def __getitem__(self, section):
- if not self.data.has_section(section):
- self.data.add_section(section)
- return Section(section, self)
-
- def __getattr__(self, attr):
- return getattr(self.data, attr)
+# Directories were to search the config file
+cfgfilepath = [ '.', os.path.expanduser('~/.' + application), '/etc/' +
application ]
+SHAREDIR = ''
-# Directories were to search the config file
-cfgfilepath = [ '.', os.path.expanduser('~/.' + application),
- '/etc/' + application, '/usr/local/etc/' + application]
+class Config(ConfigParser):
+ def __init__(self, name, schema={}):
+ ConfigParser.__init__(self, schema)
+ if SHAREDIR and os.path.isfile(os.path.join(SHAREDIR, 'config', name)):
+ self.read(os.path.join(SHAREDIR, 'config', name))
+ self.filename = ''
+ self.name = name
+ for path in cfgfilepath:
+ if os.path.isfile(os.path.join(path, name)):
+ self.filename = os.path.join(path, name)
+ self.read(self.filename)
+ break
+
+ def save(self, filename=''):
+ filename = filename or self.filename
+ if not filename:
+ cfgfilepath.reverse()
+ for path in cfgfilepath:
+ if self.save(os.path.join(path, self.name)):
+ cfgfilepath.reverse()
+ return
+ cfgfilepath.reverse()
+ raise IOError('unable to save file')
+ else:
+ try:
+ if not os.path.isdir(os.path.dirname(filename)):
+ os.makedirs(os.path.dirname(filename))
+ f = open(filename, 'w')
+ except (IOError, OSError):
+ return False
+ self.write(f)
+ f.close()
+ self.filename = filename
+ return True
# find the currect encoding
try:
@@ -135,18 +124,13 @@
DATADIR = '/var/lib/' + application
LOGDIR = '/var/log/' + application
-# Directories were to search the config file
-_cfgfilepath = [ '.', os.path.expanduser('~/.' + application),
- '/etc/' + application, '/usr/local/etc/' + application]
-
# read the config file, if no file is found, the default values
# are used. FIXME: update the freevo.conf file
-for dirname in _cfgfilepath:
- conf = os.path.join(dirname, application + '.conf.new')
+for dirname in cfgfilepath:
+ conf = os.path.join(dirname, application + '.conf')
if os.path.isfile(conf):
c = Config(conf)
- break
-
+
# directory for 'share' files
base = os.path.normpath(os.path.join(os.path.dirname(__file__), '../../../..'))
SHAREDIR = os.path.join(base, 'share', application)
Copied: trunk/freevo-core/src/fxdparser.py (from r7699,
/trunk/freevo/src/util/fxdparser.py)
==============================================================================
--- /trunk/freevo/src/util/fxdparser.py (original)
+++ trunk/freevo-core/src/fxdparser.py Sun Oct 16 14:14:28 2005
@@ -6,7 +6,6 @@
#
# This file handles the basic fxd fileparsing. It is possible to register
# specific handlers for parsing the different subnodes after <freevo>.
-# The parsed fxd is stored in the vfs for faster access later.
#
# -----------------------------------------------------------------------------
# Freevo - A Home Theater PC framework
@@ -43,11 +42,8 @@
# xml support
from xml.utils import qp_xml
-# freevo utils
-import vfs
-import fileops
-import cache
-import sysconfig
+# freevo imports
+import conf
class XMLnode(object):
"""
@@ -72,30 +68,21 @@
"""
Class to parse and write fxd files
"""
- def __init__(self, filename, use_cache=True):
+ def __init__(self, filename):
"""
Load the file and parse it. If the file does not exists, create
an empty <freevo> node.
"""
qp_xml.Parser.__init__(self)
- self.use_cache = use_cache
self.filename = filename
- if not vfs.isfile(filename):
+ if not os.path.isfile(filename):
self.tree = XMLnode('freevo')
else:
self.tree = None
- if use_cache:
- cachename = vfs.getoverlay(filename + '.raw')
- if os.path.isfile(filename) and os.path.isfile(cachename) and \
- os.stat(cachename)[stat.ST_MTIME] >= \
- os.stat(filename)[stat.ST_MTIME]:
- self.tree = cache.load(cachename)
if not self.tree:
- f = vfs.open(filename)
+ f = open(filename)
self.tree = self.parse(f)
f.close()
- if self.tree and use_cache:
- cache.save(cachename, self.tree)
def add(self, node, parent=None, pos=None):
@@ -118,21 +105,18 @@
"""
if not filename:
filename = self.filename
- if vfs.isfile(filename):
- os.unlink(vfs.abspath(filename))
- f = vfs.codecs_open(filename, 'wb', sysconfig.ENCODING)
- f.write('<?xml version="1.0" encoding="%s" ?>\n' % sysconfig.ENCODING)
+ if os.path.isfile(filename):
+ os.unlink(filename)
+ f = codecs.open(filename, 'wb', conf.ENCODING)
+ f.write('<?xml version="1.0" encoding="%s" ?>\n' % conf.ENCODING)
self._dump_recurse(f, self.tree)
f.write('\n')
f.close()
- f = vfs.open(filename)
+ f = open(filename)
self.tree = self.parse(f)
f.close()
- if self.tree and self.use_cache:
- cache.save(vfs.getoverlay(filename + '.raw'), self.tree)
-
def _dump_recurse(self, f, elem, depth=0):
-------------------------------------------------------
This SF.Net email is sponsored by:
Power Architecture Resource Center: Free content, downloads, discussions,
and more. http://solutions.newsforge.com/ibmarch.tmpl
_______________________________________________
Freevo-cvslog mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/freevo-cvslog