Author: dmeyer
Date: Sun Feb 11 10:22:34 2007
New Revision: 9206
Added:
trunk/core/src/xmlconfig.py
- copied, changed from r9204, /trunk/core/src/conf.py
Modified:
trunk/core/src/conf.py
Log:
put xmlconfig in extra file so we don't need to import freevo.conf on setup
Modified: trunk/core/src/conf.py
==============================================================================
--- trunk/core/src/conf.py (original)
+++ trunk/core/src/conf.py Sun Feb 11 10:22:34 2007
@@ -54,7 +54,7 @@
# That's it, you shouldn't need to make changes after this point
-__all__ = [ 'datafile', 'SHAREDIR', 'cfgfilepath', 'xmlconfig' ]
+__all__ = [ 'datafile', 'SHAREDIR', 'cfgfilepath' ]
# Python imports
import os
@@ -95,123 +95,6 @@
return msg + KaaConfig._cfg_string(self, prefix, print_desc)
-def xmlconfig(configfile, sources):
- import kaa.distribution.xmlconfig
- import kaa.xml
-
- def get_parent(tree, name, position=''):
- for child in tree:
- if child.name == 'group':
- # print 'have', child.getattr('name')
- if position + child.name == name:
- raise RuntimeError('bad tree')
- if name.startswith(position + child.getattr('name')):
- # print 'deeper'
- return get_parent(child, name, position +
child.getattr('name') + '.')
- for name in name[len(position):].strip(' .').split('.'):
- # print 'create', name
- node = kaa.xml.Node('group', name=name)
- tree.add_child(node)
- tree = node
- return tree
-
- hashkey = [ f+str(os.stat(f)[stat.ST_MTIME]) for f in sources ]
- hashkey = md5.new(''.join(hashkey)).hexdigest()
-
- if os.path.isfile(configfile):
- fd = open(configfile)
- fd.readline()
- if fd.readline() == '# -*- hash: %s\n' % hashkey:
- fd.close()
- return True
- fd.close()
-
- modules = []
- for cfg in sources:
- # load cxml file
- m = kaa.xml.Document(cfg, 'config')
- if m.getattr('name'):
- # FIXME: ugly hack
- # No idea why this is needed, m.unlink() should do the
- # trick. One day I will understand the memory management
- # from libxml2.
- m._doc._doc = True
- m.unlink()
- if not m.getattr('name').endswith('plugin'):
- modules.append(m)
- continue
- # list of plugins
- for plugin in m.children:
- if plugin.name == 'group':
- # unlink node to add later to a new doc
- plugin.unlink()
- name = '%s.%s' % (m.getattr('name'), plugin.getattr('name'))
- plugin.setattr('name', name)
- modules.append(plugin)
-
- def valfunc(node):
- name = node.getattr('name')
- if name.startswith('plugin'):
- return '2%s' % name
- if node.hasattr('plugin') or '.plugin.' in name:
- return '1%s' % name
- if 'gui' in name:
- return '3%s' % name
- return '0%s' % name
-
- # sort modules somehow
- modules.sort(lambda x,y: cmp(valfunc(x), valfunc(y)))
-
- if modules[0].getattr('name') == '':
- tree = modules.pop(0)
- else:
- doc = '<?xml version="1.0"?><config name=""></config>'
- tree = kaa.xml.Document(doc, 'config')
-
- for m in modules:
- parent = get_parent(tree, m.getattr('name'))
- if m.hasattr('plugin'):
- node = kaa.xml.Node('var')
- node.setattr('name', 'activate')
- node.setattr('default', m.getattr('plugin'))
- parent.add_child(node)
- parent.setattr('is_plugin', 'yes')
- for child in m:
- child.unlink()
- parent.add_child(child)
-
- if configfile.endswith('.cxml'):
- return tree.save(configfile)
- out = open(configfile, 'w')
- out.write('# -*- coding: iso-8859-1 -*-\n')
- out.write('# -*- hash: %s\n' % hashkey)
- out.write('# auto generated file\n\n')
- out.write('from kaa.config import Var, Group, Dict, List, Config\n\n')
- out.write('config = ')
- kaa.distribution.xmlconfig.Parser().parse(tree, out)
-
- def find_plugins(node, position=''):
- for child in node:
- if child.hasattr('is_plugin'):
- name = "%s%s" % (position, child.getattr('name'))
- out.write('\'%s\', ' % name.strip('. ,'))
- if child.name == 'group':
- find_plugins(child, position + child.getattr('name') + '.')
-
- out.write('\nplugins = [')
- find_plugins(tree)
- out.write(']\n')
-
- def find_code(node):
- for child in node:
- if child.name == 'code':
- out.write(kaa.distribution.xmlconfig.format_content(child) +
'\n\n')
- if child.name == 'group':
- find_code(child)
- find_code(tree)
- out.close()
-
-
# set basic env variables
if not os.environ.has_key('HOME') or not os.environ['HOME'] or
os.environ['HOME'] == '/':
os.environ['HOME'] = '/root'
@@ -240,7 +123,7 @@
DATADIR = '/var/lib/' + application
if os.getuid():
DATADIR = os.path.expanduser('~/.' + application + '/data')
-if not os.path.isdir(DATADIR) and not 'setup.py' in sys.argv[:2]:
+if not os.path.isdir(DATADIR):
os.makedirs(DATADIR)
# create and setup the root logger object.
@@ -271,21 +154,20 @@
if logfiletmpl.startswith('freevo-'):
logfiletmpl = logfiletmpl[7:]
-if not 'setup.py' in sys.argv[:2]:
+try:
logdir = '/var/log/' + application
logfile = '%s/%s-%s' % (logdir, logfiletmpl, os.getuid())
- try:
- if not os.path.isdir(logdir):
- os.makedirs(logdir)
- handler = RotatingFileHandler(logfile, maxBytes=1000000, backupCount=2)
- except (OSError, IOError):
- logdir = os.path.expanduser('~/.' + application + '/log')
- logfile = '%s/%s' % (logdir, logfiletmpl)
- if not os.path.isdir(logdir):
- os.makedirs(logdir)
- handler = RotatingFileHandler(logfile, maxBytes=1000000, backupCount=2)
- handler.setFormatter(formatter)
- logger.addHandler(handler)
+ if not os.path.isdir(logdir):
+ os.makedirs(logdir)
+ handler = RotatingFileHandler(logfile, maxBytes=1000000, backupCount=2)
+except (OSError, IOError):
+ logdir = os.path.expanduser('~/.' + application + '/log')
+ logfile = '%s/%s' % (logdir, logfiletmpl)
+ if not os.path.isdir(logdir):
+ os.makedirs(logdir)
+ handler = RotatingFileHandler(logfile, maxBytes=1000000, backupCount=2)
+handler.setFormatter(formatter)
+logger.addHandler(handler)
# set log level
logger.setLevel(logging.WARNING)
Copied: trunk/core/src/xmlconfig.py (from r9204, /trunk/core/src/conf.py)
==============================================================================
--- /trunk/core/src/conf.py (original)
+++ trunk/core/src/xmlconfig.py Sun Feb 11 10:22:34 2007
@@ -1,33 +1,17 @@
# -*- coding: iso-8859-1 -*-
# -----------------------------------------------------------------------------
-# sysconfig.py - Basic configuration for some utils used in Freevo
+# xmlconfig.py - Handling of cxml config files
# -----------------------------------------------------------------------------
# $Id$
#
-# Most modules in the util directory doesn't need Freevo. So it is possible
-# to use them in a different project (licence is GPL). But the modules need
-# a very simple configuration, like were to store cache files and some need
-# the virtual filesystem (util.vfs) to work and this has it's own data
-# directory. A different problem is the python encoding handling. It is
-# fixed to 'ascii' (you can change it in site.py, but that doesn't always
-# work and is a bad solution).
-#
-# This module provides some basic settings to solve that problems. It reads
-# a config file and stores everything in a struct. It will create necessary
-# directories for caching.
-#
-# If you want to use an util module in a different project, you may also
-# need this file. The name freevo in the config file can be changed at the
-# beginning of this file.
-#
# -----------------------------------------------------------------------------
# Freevo - A Home Theater PC framework
-# Copyright (C) 2002-2005 Krister Lagerstrom, Dirk Meyer, et al.
+# Copyright (C) 2007 Dirk Meyer, et al.
#
# First Edition: Dirk Meyer <[EMAIL PROTECTED]>
# Maintainer: Dirk Meyer <[EMAIL PROTECTED]>
#
-# Please see the file doc/CREDITS for a complete list of authors.
+# Please see the file AUTHORS for a complete list of authors.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
@@ -45,59 +29,18 @@
#
# -----------------------------------------------------------------------------
-# Application name. This name is used to locate the config file.
-# Possible locations are ., ~/application, /etc/application and
-# /usr/local/etc/application. The name of the config file is
-# application.conf.
-application = 'freevo'
-
-
-# That's it, you shouldn't need to make changes after this point
+__all__ = [ 'xmlconfig' ]
-__all__ = [ 'datafile', 'SHAREDIR', 'cfgfilepath', 'xmlconfig' ]
-
-# Python imports
+# python imports
import os
import stat
import md5
-import sys
-import locale
-import logging
-from logging.handlers import RotatingFileHandler
-import gettext
-import gc
# kaa imports
-from kaa.strutils import ENCODING
-from kaa.config import Var, Group, Dict, List
-from kaa.config import Config as KaaConfig
-from kaa.notifier import Timer
-
-class Config(KaaConfig):
- def __init__(self, app, schema, desc=u'', name=''):
- KaaConfig.__init__(self, schema, desc, name)
- self._app = app
-
- def load(self):
- KaaConfig.load(self, '/etc/freevo/%s.conf' % self._app)
- # if started as user add personal config file
- if os.getuid() > 0:
- cfgdir = os.path.expanduser('~/.freevo')
- KaaConfig.load(self, os.path.join(cfgdir, '%s.conf' % self._app))
-
- def _cfg_string(self, prefix, print_desc=True):
- cfgfile = '/etc/freevo/%s.conf' % self._app
- msg = ''
- if os.getuid() > 0 and os.path.isfile(cfgfile):
- msg = '#
*************************************************************\n'
- msg += '# Please also check the system wide config file\n# %s\n' %
cfgfile
- msg += '#
*************************************************************\n\n'
- return msg + KaaConfig._cfg_string(self, prefix, print_desc)
-
+import kaa.distribution.xmlconfig
+import kaa.xml
def xmlconfig(configfile, sources):
- import kaa.distribution.xmlconfig
- import kaa.xml
def get_parent(tree, name, position=''):
for child in tree:
@@ -210,104 +153,3 @@
find_code(child)
find_code(tree)
out.close()
-
-
-# set basic env variables
-if not os.environ.has_key('HOME') or not os.environ['HOME'] or
os.environ['HOME'] == '/':
- os.environ['HOME'] = '/root'
-if not os.environ.has_key('USER') or not os.environ['USER']:
- os.environ['USER'] = 'root'
-
-# Directories were to search the config file
-cfgfilepath = [ '.', os.path.expanduser('~/.' + application), '/etc/' +
application ]
-
-# directory for 'share' files
-base = os.path.normpath(os.path.join(os.path.dirname(__file__), '../../../..'))
-SHAREDIR = os.path.abspath(os.path.join(base, 'share', application))
-
-# get path with translations
-i18npath = os.path.join(base, 'share/locale')
-try:
- # try translation file based on application name
- i18n = gettext.translation(os.path.basename(sys.argv[0]), i18npath,
fallback=False)
-except IOError:
- # try freevo translation file and use fallback to avoid crashing
- i18n = gettext.translation('freevo', i18npath, fallback=True)
-
-i18n.install(unicode=True)
-
-# create needed directories.
-DATADIR = '/var/lib/' + application
-if os.getuid():
- DATADIR = os.path.expanduser('~/.' + application + '/data')
-if not os.path.isdir(DATADIR) and not 'setup.py' in sys.argv[:2]:
- os.makedirs(DATADIR)
-
-# create and setup the root logger object.
-# using logging.getLogger() gives the root logger, calling
-# logging.getLogger('foo') returns a new logger with the same default
-# settings.
-logger = logging.getLogger()
-
-# remove handler, we want to set the look and avoid
-# duplicate handlers
-for l in logger.handlers[:]:
- logger.removeHandler(l)
-
-# set stdout logging
-# TODO: find a way to shut down that logger later when the user
-# wants to visible debug in the terminal
-formatter = logging.Formatter('%(levelname)s %(module)s'+\
- '(%(lineno)s): %(message)s')
-handler = logging.StreamHandler()
-handler.setFormatter(formatter)
-logger.addHandler(handler)
-
-# set file logger
-formatter = logging.Formatter('%(asctime)s %(levelname)-8s [%(name)6s] '+\
- '%(filename)s %(lineno)s: '+\
- '%(message)s')
-logfiletmpl = os.path.splitext(os.path.basename(sys.argv[0]))[0]
-if logfiletmpl.startswith('freevo-'):
- logfiletmpl = logfiletmpl[7:]
-
-if not 'setup.py' in sys.argv[:2]:
- logdir = '/var/log/' + application
- logfile = '%s/%s-%s' % (logdir, logfiletmpl, os.getuid())
- try:
- if not os.path.isdir(logdir):
- os.makedirs(logdir)
- handler = RotatingFileHandler(logfile, maxBytes=1000000, backupCount=2)
- except (OSError, IOError):
- logdir = os.path.expanduser('~/.' + application + '/log')
- logfile = '%s/%s' % (logdir, logfiletmpl)
- if not os.path.isdir(logdir):
- os.makedirs(logdir)
- handler = RotatingFileHandler(logfile, maxBytes=1000000, backupCount=2)
- handler.setFormatter(formatter)
- logger.addHandler(handler)
-
-# set log level
-logger.setLevel(logging.WARNING)
-
-def garbage_collect():
- """
- Run garbage collector. It is not nice that we have to do this,
- but without we have a memory leak.
- """
- # run gc
- gc.collect()
- for g in gc.garbage:
- # print information about garbage gc can't collect
- logger.warning('Unable to free %s' % g)
-
-
-# start garbage_collect every 5 seconds
-Timer(garbage_collect).start(5)
-
-
-def datafile(name):
- """
- Return a datafile based on the name. The result is an absolute path.
- """
- return os.path.join(DATADIR, name)
-------------------------------------------------------------------------
Using Tomcat but need to do more? Need to support web services, security?
Get stuff done quickly with pre-integrated technology to make your job easier.
Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo
http://sel.as-us.falkag.net/sel?cmd=lnk&kid=120709&bid=263057&dat=121642
_______________________________________________
Freevo-cvslog mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/freevo-cvslog