tiramisu/tiramisu/config.py

677 lines
28 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
2013-08-23 11:16:26 +02:00
"options handler global entry point"
2013-02-21 17:07:00 +01:00
# Copyright (C) 2012-2013 Team tiramisu (see AUTHORS for all contributors)
#
# 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
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
2012-10-05 16:00:07 +02:00
# The original `Config` design model is unproudly borrowed from
# the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
# the whole pypy projet is under MIT licence
# ____________________________________________________________
2013-08-20 09:47:12 +02:00
from time import time
2013-05-02 11:34:57 +02:00
from tiramisu.error import PropertiesOptionError, ConfigError
from tiramisu.option import OptionDescription, Option, SymLinkOption, \
BaseInformation
2013-08-20 22:45:11 +02:00
from tiramisu.setting import groups, Settings, default_encoding, storage_type
2013-02-22 11:09:17 +01:00
from tiramisu.value import Values
2013-04-13 23:09:05 +02:00
from tiramisu.i18n import _
2013-02-22 11:09:17 +01:00
2013-08-20 22:45:11 +02:00
def gen_id(config):
return str(id(config)) + str(time())
class SubConfig(BaseInformation):
2013-04-03 12:20:26 +02:00
"sub configuration management entry"
__slots__ = ('_impl_context', '_impl_descr', '_impl_path')
2013-04-03 12:20:26 +02:00
def __init__(self, descr, context, subpath=None):
2012-10-05 16:00:07 +02:00
""" Configuration option management master class
2013-02-19 11:24:17 +01:00
2012-10-05 16:00:07 +02:00
:param descr: describes the configuration schema
:type descr: an instance of ``option.OptionDescription``
2013-02-07 16:20:21 +01:00
:param context: the current root config
:type context: `Config`
:type subpath: `str` with the path name
2012-10-05 16:00:07 +02:00
"""
# main option description
2013-04-16 11:51:48 +02:00
if not isinstance(descr, OptionDescription):
raise TypeError(_('descr must be an optiondescription, not {0}'
).format(type(descr)))
self._impl_descr = descr
# sub option descriptions
2013-05-02 11:34:57 +02:00
if not isinstance(context, SubConfig):
raise ValueError('context must be a SubConfig')
self._impl_context = context
self._impl_path = subpath
2013-05-02 11:34:57 +02:00
def cfgimpl_reset_cache(self, only_expired=False, only=('values',
'settings')):
self.cfgimpl_get_context().cfgimpl_reset_cache(only_expired, only)
2013-02-07 16:20:21 +01:00
2013-05-02 11:34:57 +02:00
def cfgimpl_get_home_by_path(self, path, force_permissive=False,
force_properties=None):
2012-10-05 16:00:07 +02:00
""":returns: tuple (config, name)"""
path = path.split('.')
for step in path[:-1]:
self = self._getattr(step,
force_permissive=force_permissive,
force_properties=force_properties)
return self, path[-1]
def __hash__(self):
return hash(self.cfgimpl_get_description().impl_getkey(self))
def __eq__(self, other):
2013-05-14 17:40:42 +02:00
"Config's comparison"
2012-12-05 09:41:53 +01:00
if not isinstance(other, Config):
2012-11-30 15:08:34 +01:00
return False
return self.cfgimpl_get_description().impl_getkey(self) == \
other.cfgimpl_get_description().impl_getkey(other)
def __ne__(self, other):
2013-05-14 17:40:42 +02:00
"Config's comparison"
if not isinstance(other, Config):
return True
return not self == other
2013-02-25 16:24:30 +01:00
2012-10-05 16:00:07 +02:00
# ______________________________________________________________________
def __iter__(self):
2012-11-20 17:14:58 +01:00
"""Pythonesque way of parsing group's ordered options.
iteration only on Options (not OptionDescriptions)"""
for child in self.cfgimpl_get_description().impl_getchildren():
if not isinstance(child, OptionDescription):
try:
yield child._name, getattr(self, child._name)
2013-03-25 14:21:30 +01:00
except GeneratorExit:
raise Exception('ca passe ici')
2013-03-25 14:21:30 +01:00
raise StopIteration
2013-04-16 12:04:20 +02:00
except PropertiesOptionError:
2013-02-25 16:24:30 +01:00
pass # option with properties
2013-03-07 11:02:18 +01:00
def iter_all(self):
"""A way of parsing options **and** groups.
iteration on Options and OptionDescriptions."""
for child in self.cfgimpl_get_description().impl_getchildren():
2013-03-07 11:02:18 +01:00
try:
yield child._name, getattr(self, child._name)
2013-03-25 14:21:30 +01:00
except GeneratorExit:
raise StopIteration
2013-04-16 12:04:20 +02:00
except PropertiesOptionError:
2013-03-07 11:02:18 +01:00
pass # option with properties
def iter_groups(self, group_type=None):
2012-11-20 17:14:58 +01:00
"""iteration on groups objects only.
All groups are returned if `group_type` is `None`, otherwise the groups
can be filtered by categories (families, or whatever).
2013-02-21 17:07:00 +01:00
2012-12-10 14:38:25 +01:00
:param group_type: if defined, is an instance of `groups.GroupType`
or `groups.MasterGroupType` that lives in
2013-02-07 16:20:21 +01:00
`setting.groups`
2012-11-20 17:14:58 +01:00
"""
if group_type is not None and not isinstance(group_type,
groups.GroupType):
raise TypeError(_("unknown group_type: {0}").format(group_type))
for child in self.cfgimpl_get_description().impl_getchildren():
if isinstance(child, OptionDescription):
2012-11-06 15:19:36 +01:00
try:
if group_type is None or (group_type is not None and
child.impl_get_group_type()
2013-05-02 11:34:57 +02:00
== group_type):
2012-11-06 15:19:36 +01:00
yield child._name, getattr(self, child._name)
2013-03-25 14:21:30 +01:00
except GeneratorExit:
raise StopIteration
2013-04-16 12:04:20 +02:00
except PropertiesOptionError:
2012-12-06 18:14:57 +01:00
pass
2012-10-05 16:00:07 +02:00
# ______________________________________________________________________
2013-04-03 12:20:26 +02:00
2012-11-28 10:14:16 +01:00
def __str__(self):
2012-10-05 16:00:07 +02:00
"Config's string representation"
lines = []
2012-11-28 10:14:16 +01:00
for name, grp in self.iter_groups():
lines.append("[{0}]".format(name))
2012-11-28 10:14:16 +01:00
for name, value in self:
try:
lines.append("{0} = {1}".format(name, value))
except UnicodeEncodeError:
lines.append("{0} = {1}".format(name,
value.encode(default_encoding)))
2013-04-16 12:04:20 +02:00
except PropertiesOptionError:
2012-11-28 10:14:16 +01:00
pass
return '\n'.join(lines)
2012-11-28 10:14:16 +01:00
__repr__ = __str__
2013-05-02 11:34:57 +02:00
def cfgimpl_get_context(self):
return self._impl_context
2013-05-02 11:34:57 +02:00
def cfgimpl_get_description(self):
if self._impl_descr is None:
2013-08-20 12:08:02 +02:00
raise ConfigError(_('no option description found for this config'
' (may be metaconfig without meta)'))
2013-05-02 11:34:57 +02:00
else:
return self._impl_descr
2013-05-02 11:34:57 +02:00
def cfgimpl_get_settings(self):
return self.cfgimpl_get_context()._impl_settings
2013-05-02 11:34:57 +02:00
def cfgimpl_get_values(self):
return self.cfgimpl_get_context()._impl_values
2013-05-02 11:34:57 +02:00
# ____________________________________________________________
# attribute methods
def __setattr__(self, name, value):
"attribute notation mechanism for the setting of the value of an option"
if name.startswith('_impl_'):
2013-05-02 11:34:57 +02:00
#self.__dict__[name] = value
object.__setattr__(self, name, value)
return
self._setattr(name, value)
def _setattr(self, name, value, force_permissive=False):
if '.' in name:
homeconfig, name = self.cfgimpl_get_home_by_path(name)
return homeconfig.__setattr__(name, value)
child = getattr(self.cfgimpl_get_description(), name)
if not isinstance(child, SymLinkOption):
if self._impl_path is None:
path = name
else:
path = self._impl_path + '.' + name
self.cfgimpl_get_values().setitem(child, value, path,
2013-05-02 11:34:57 +02:00
force_permissive=force_permissive)
else:
context = self.cfgimpl_get_context()
2013-08-21 18:34:32 +02:00
path = context.cfgimpl_get_description().impl_get_path_by_opt(
child._opt)
2013-05-02 11:34:57 +02:00
context._setattr(path, value, force_permissive=force_permissive)
def __delattr__(self, name):
child = getattr(self.cfgimpl_get_description(), name)
self.cfgimpl_get_values().__delitem__(child)
2013-05-02 11:34:57 +02:00
def __getattr__(self, name):
return self._getattr(name)
def _getattr(self, name, force_permissive=False, force_properties=None,
validate=True):
"""
attribute notation mechanism for accessing the value of an option
:param name: attribute name
:return: option's value if name is an option name, OptionDescription
otherwise
"""
# attribute access by passing a path,
# for instance getattr(self, "creole.general.family.adresse_ip_eth0")
if '.' in name:
2013-08-21 18:34:32 +02:00
homeconfig, name = self.cfgimpl_get_home_by_path(
name, force_permissive=force_permissive,
force_properties=force_properties)
2013-05-02 11:34:57 +02:00
return homeconfig._getattr(name, force_permissive=force_permissive,
force_properties=force_properties,
validate=validate)
# special attributes
if name.startswith('_impl_') or name.startswith('cfgimpl_') \
or name.startswith('impl_'):
2013-05-02 11:34:57 +02:00
# if it were in __dict__ it would have been found already
return object.__getattribute__(self, name)
opt_or_descr = getattr(self.cfgimpl_get_description(), name)
# symlink options
if self._impl_path is None:
subpath = name
else:
subpath = self._impl_path + '.' + name
2013-05-02 11:34:57 +02:00
if isinstance(opt_or_descr, SymLinkOption):
context = self.cfgimpl_get_context()
2013-08-21 18:34:32 +02:00
path = context.cfgimpl_get_description().impl_get_path_by_opt(
opt_or_descr._opt)
2013-05-02 11:34:57 +02:00
return context._getattr(path, validate=validate,
force_properties=force_properties,
force_permissive=force_permissive)
elif isinstance(opt_or_descr, OptionDescription):
2013-08-21 18:34:32 +02:00
self.cfgimpl_get_settings().validate_properties(
opt_or_descr, True, False, path=subpath,
force_permissive=force_permissive,
2013-08-21 18:34:32 +02:00
force_properties=force_properties)
return SubConfig(opt_or_descr, self.cfgimpl_get_context(), subpath)
2013-05-02 11:34:57 +02:00
else:
2013-08-21 18:34:32 +02:00
return self.cfgimpl_get_values().getitem(
opt_or_descr, path=subpath,
2013-08-21 18:34:32 +02:00
validate=validate,
force_properties=force_properties,
force_permissive=force_permissive)
2013-04-03 12:20:26 +02:00
def find(self, bytype=None, byname=None, byvalue=None, type_='option'):
2013-04-04 11:24:00 +02:00
"""
finds a list of options recursively in the config
:param bytype: Option class (BoolOption, StrOption, ...)
:param byname: filter by Option._name
:param byvalue: filter by the option's value
:returns: list of matching Option objects
"""
return self.cfgimpl_get_context()._find(bytype, byname, byvalue,
first=False,
type_=type_,
2013-08-20 12:08:02 +02:00
_subpath=self.cfgimpl_get_path()
)
2013-04-03 12:20:26 +02:00
2013-05-02 11:34:57 +02:00
def find_first(self, bytype=None, byname=None, byvalue=None,
2013-07-17 23:02:50 +02:00
type_='option', display_error=True):
2013-04-04 11:24:00 +02:00
"""
finds an option recursively in the config
:param bytype: Option class (BoolOption, StrOption, ...)
:param byname: filter by Option._name
:param byvalue: filter by the option's value
:returns: list of matching Option objects
"""
2013-08-21 18:34:32 +02:00
return self.cfgimpl_get_context()._find(
bytype, byname, byvalue, first=True, type_=type_,
_subpath=self.cfgimpl_get_path(), display_error=display_error)
2013-04-04 11:24:00 +02:00
2013-05-02 11:34:57 +02:00
def _find(self, bytype, byname, byvalue, first, type_='option',
2013-07-17 23:02:50 +02:00
_subpath=None, check_properties=True, display_error=True):
2013-05-02 11:34:57 +02:00
"""
convenience method for finding an option that lives only in the subtree
:param first: return only one option if True, a list otherwise
:return: find list or an exception if nothing has been found
"""
def _filter_by_name():
try:
2013-08-20 12:08:02 +02:00
if byname is None or path == byname or \
2013-08-21 18:34:32 +02:00
path.endswith('.' + byname):
2013-05-02 11:34:57 +02:00
return True
except IndexError:
pass
return False
def _filter_by_value():
if byvalue is None:
return True
try:
value = getattr(self, path)
if value == byvalue:
return True
2013-08-20 12:08:02 +02:00
except PropertiesOptionError: # a property is a restriction
# upon the access of the value
2013-05-02 11:34:57 +02:00
pass
return False
def _filter_by_type():
if bytype is None:
return True
if isinstance(option, bytype):
return True
return False
#def _filter_by_attrs():
# if byattrs is None:
# return True
# for key, val in byattrs.items():
# print "----", path, key
# if path == key or path.endswith('.' + key):
# if value == val:
# return True
# else:
# return False
# return False
if type_ not in ('option', 'path', 'context', 'value'):
2013-08-20 12:08:02 +02:00
raise ValueError(_('unknown type_ type {0}'
'for _find').format(type_))
2013-05-02 11:34:57 +02:00
find_results = []
opts, paths = self.cfgimpl_get_description()._cache_paths
for index in range(0, len(paths)):
option = opts[index]
if isinstance(option, OptionDescription):
continue
path = paths[index]
if _subpath is not None and not path.startswith(_subpath + '.'):
continue
if not _filter_by_name():
continue
if not _filter_by_value():
continue
#remove option with propertyerror, ...
if check_properties:
try:
value = getattr(self, path)
except PropertiesOptionError:
# a property restricts the access of the value
continue
if not _filter_by_type():
continue
#if not _filter_by_attrs():
# continue
if type_ == 'value':
retval = value
elif type_ == 'path':
retval = path
elif type_ == 'option':
retval = option
elif type_ == 'context':
retval = self.cfgimpl_get_context()
if first:
return retval
else:
find_results.append(retval)
if find_results == []:
2013-07-17 23:02:50 +02:00
if display_error:
2013-08-20 12:08:02 +02:00
raise AttributeError(_("no option found in config"
" with these criteria"))
2013-07-17 23:02:50 +02:00
else:
2013-07-17 23:05:43 +02:00
#translation is slow
2013-07-17 23:02:50 +02:00
raise AttributeError()
2013-05-02 11:34:57 +02:00
else:
return find_results
def make_dict(self, flatten=False, _currpath=None, withoption=None,
withvalue=None):
"""exports the whole config into a `dict`, for example:
2013-05-23 17:51:50 +02:00
>>> print cfg.make_dict()
{'od2.var4': None, 'od2.var5': None, 'od2.var6': None}
2013-05-23 17:51:50 +02:00
:param flatten: returns a dict(name=value) instead of a dict(path=value)
::
>>> print cfg.make_dict(flatten=True)
{'var5': None, 'var4': None, 'var6': None}
2013-05-23 17:51:50 +02:00
:param withoption: returns the options that are present in the very same
`OptionDescription` than the `withoption` itself::
>>> print cfg.make_dict(withoption='var1')
2013-08-20 12:08:02 +02:00
{'od2.var4': None, 'od2.var5': None,
'od2.var6': None,
'od2.var1': u'value',
'od1.var1': None,
'od1.var3': None,
'od1.var2': None}
2013-05-23 17:51:50 +02:00
:param withvalue: returns the options that have the value `withvalue`
::
2013-08-20 12:08:02 +02:00
>>> print c.make_dict(withoption='var1',
withvalue=u'value')
{'od2.var4': None,
'od2.var5': None,
'od2.var6': None,
2013-05-23 17:51:50 +02:00
'od2.var1': u'value'}
2013-05-23 14:55:52 +02:00
:returns: dict of Option's name (or path) and values
"""
2013-04-04 11:24:00 +02:00
pathsvalues = []
if _currpath is None:
_currpath = []
if withoption is None and withvalue is not None:
2013-05-02 11:34:57 +02:00
raise ValueError(_("make_dict can't filtering with value without "
"option"))
2013-04-04 11:24:00 +02:00
if withoption is not None:
mypath = self.cfgimpl_get_path()
for path in self.cfgimpl_get_context()._find(bytype=Option,
byname=withoption,
byvalue=withvalue,
first=False,
type_='path',
_subpath=mypath):
2013-04-04 11:24:00 +02:00
path = '.'.join(path.split('.')[:-1])
2013-08-21 18:34:32 +02:00
opt = self.cfgimpl_get_context().cfgimpl_get_description(
).impl_get_opt_by_path(path)
2013-04-04 11:24:00 +02:00
if mypath is not None:
if mypath == path:
withoption = None
withvalue = None
break
else:
tmypath = mypath + '.'
if not path.startswith(tmypath):
2013-04-14 12:01:32 +02:00
raise AttributeError(_('unexpected path {0}, '
2013-05-02 11:34:57 +02:00
'should start with {1}'
'').format(path, mypath))
2013-04-04 11:24:00 +02:00
path = path[len(tmypath):]
self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten)
#withoption can be set to None below !
if withoption is None:
for opt in self.cfgimpl_get_description().impl_getchildren():
2013-04-04 11:24:00 +02:00
path = opt._name
self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten)
if _currpath == []:
options = dict(pathsvalues)
return options
return pathsvalues
def _make_sub_dict(self, opt, path, pathsvalues, _currpath, flatten):
if isinstance(opt, OptionDescription):
try:
pathsvalues += getattr(self, path).make_dict(flatten,
2013-08-20 12:08:02 +02:00
_currpath +
path.split('.'))
except PropertiesOptionError:
pass # this just a hidden or disabled option
2013-04-04 11:24:00 +02:00
else:
try:
value = self._getattr(opt._name)
if flatten:
name = opt._name
else:
name = '.'.join(_currpath + [opt._name])
pathsvalues.append((name, value))
except PropertiesOptionError:
pass # this just a hidden or disabled option
2013-04-03 12:20:26 +02:00
2013-05-02 11:34:57 +02:00
def cfgimpl_get_path(self):
descr = self.cfgimpl_get_description()
context_descr = self.cfgimpl_get_context().cfgimpl_get_description()
return context_descr.impl_get_path_by_opt(descr)
2013-04-03 12:20:26 +02:00
2013-05-21 18:42:56 +02:00
class CommonConfig(SubConfig):
"abstract base class for the Config and the MetaConfig"
__slots__ = ('_impl_values', '_impl_settings', '_impl_meta')
2013-04-03 12:20:26 +02:00
2013-08-20 22:45:11 +02:00
def _init_storage(self, config_id, is_persistent):
if config_id is None:
config_id = gen_id(self)
import_lib = 'tiramisu.storage.{0}.storage'.format(storage_type)
return __import__(import_lib, globals(), locals(), ['Storage'],
2013-08-21 18:34:32 +02:00
-1).Storage(config_id, is_persistent)
2013-08-20 22:45:11 +02:00
def _impl_build_all_paths(self):
self.cfgimpl_get_description().impl_build_cache()
def read_only(self):
2013-05-14 17:40:42 +02:00
"read only is a global config's setting, see `settings.py`"
self.cfgimpl_get_settings().read_only()
def read_write(self):
2013-05-14 17:40:42 +02:00
"read write is a global config's setting, see `settings.py`"
self.cfgimpl_get_settings().read_write()
def getowner(self, path):
2013-05-14 17:40:42 +02:00
"""convenience method to retrieve an option's owner
from the config itself
"""
opt = self.cfgimpl_get_description().impl_get_opt_by_path(path)
return self.cfgimpl_get_values().getowner(opt)
2013-04-03 12:20:26 +02:00
def unwrap_from_path(self, path, force_permissive=False):
2013-04-03 12:20:26 +02:00
"""convenience method to extract and Option() object from the Config()
and it is **fast**: finds the option directly in the appropriate
namespace
:returns: Option()
"""
if '.' in path:
2013-08-20 12:08:02 +02:00
homeconfig, path = self.cfgimpl_get_home_by_path(
2013-08-21 18:34:32 +02:00
path, force_permissive=force_permissive)
2013-05-02 11:34:57 +02:00
return getattr(homeconfig.cfgimpl_get_description(), path)
return getattr(self.cfgimpl_get_description(), path)
2013-04-03 12:20:26 +02:00
def cfgimpl_get_path(self):
2013-04-04 11:24:00 +02:00
return None
2013-04-03 12:20:26 +02:00
2013-05-02 11:34:57 +02:00
def cfgimpl_get_meta(self):
return self._impl_meta
2013-04-03 12:20:26 +02:00
2013-05-02 11:34:57 +02:00
# ____________________________________________________________
2013-05-21 18:42:56 +02:00
class Config(CommonConfig):
2013-05-02 11:34:57 +02:00
"main configuration management entry"
__slots__ = tuple()
2013-04-03 12:20:26 +02:00
2013-08-20 22:45:11 +02:00
def __init__(self, descr, config_id=None, is_persistent=False):
2013-05-02 11:34:57 +02:00
""" Configuration option management master class
2012-10-12 11:35:07 +02:00
2013-05-02 11:34:57 +02:00
:param descr: describes the configuration schema
:type descr: an instance of ``option.OptionDescription``
:param context: the current root config
:type context: `Config`
"""
2013-08-20 22:45:11 +02:00
storage = self._init_storage(config_id, is_persistent)
self._impl_settings = Settings(self, storage)
self._impl_values = Values(self, storage)
super(Config, self).__init__(descr, self)
self._impl_build_all_paths()
self._impl_meta = None
self._impl_informations = {}
2012-10-12 11:35:07 +02:00
2013-08-20 12:08:02 +02:00
def cfgimpl_reset_cache(self,
only_expired=False,
only=('values', 'settings')):
2013-05-02 11:34:57 +02:00
if 'values' in only:
self.cfgimpl_get_values().reset_cache(only_expired=only_expired)
if 'settings' in only:
self.cfgimpl_get_settings().reset_cache(only_expired=only_expired)
2013-02-22 11:09:17 +01:00
2013-05-21 18:42:56 +02:00
class MetaConfig(CommonConfig):
__slots__ = ('_impl_children',)
2013-05-02 11:34:57 +02:00
2013-08-20 22:45:11 +02:00
def __init__(self, children, meta=True, config_id=None, is_persistent=False):
if not isinstance(children, list):
raise ValueError(_("metaconfig's children must be a list"))
self._impl_descr = None
self._impl_path = None
2013-05-02 11:34:57 +02:00
if meta:
for child in children:
2013-05-21 18:42:56 +02:00
if not isinstance(child, CommonConfig):
2013-08-20 12:08:02 +02:00
raise ValueError(_("metaconfig's children "
"must be config, not {0}"
).format(type(child)))
if self._impl_descr is None:
self._impl_descr = child.cfgimpl_get_description()
elif not self._impl_descr is child.cfgimpl_get_description():
2013-08-20 12:08:02 +02:00
raise ValueError(_('all config in metaconfig must '
'have the same optiondescription'))
2013-05-02 11:34:57 +02:00
if child.cfgimpl_get_meta() is not None:
raise ValueError(_("child has already a metaconfig's"))
child._impl_meta = self
2013-05-02 11:34:57 +02:00
2013-08-20 22:45:11 +02:00
if config_id is None:
config_id = gen_id(self)
self._impl_children = children
2013-08-20 22:45:11 +02:00
storage = self._init_storage(config_id, is_persistent)
self._impl_settings = Settings(self, storage)
self._impl_values = Values(self, storage)
self._impl_meta = None
self._impl_informations = {}
def cfgimpl_get_children(self):
return self._impl_children
2013-05-02 11:34:57 +02:00
def cfgimpl_get_context(self):
2013-05-14 17:40:42 +02:00
"a meta config is a config wich has a setting, that is itself"
2013-05-02 11:34:57 +02:00
return self
2013-08-20 12:08:02 +02:00
def cfgimpl_reset_cache(self,
only_expired=False,
only=('values', 'settings')):
2013-05-02 11:34:57 +02:00
if 'values' in only:
self.cfgimpl_get_values().reset_cache(only_expired=only_expired)
if 'settings' in only:
self.cfgimpl_get_settings().reset_cache(only_expired=only_expired)
for child in self._impl_children:
2013-05-02 11:34:57 +02:00
child.cfgimpl_reset_cache(only_expired=only_expired, only=only)
2013-05-02 11:34:57 +02:00
def set_contexts(self, path, value):
for child in self._impl_children:
try:
2013-05-02 11:34:57 +02:00
if not isinstance(child, MetaConfig):
setattr(child, path, value)
else:
child.set_contexts(path, value)
except PropertiesOptionError:
pass
2013-07-17 23:02:50 +02:00
def find_first_contexts(self, byname=None, bypath=None, byvalue=None,
type_='context', display_error=True):
2013-05-02 11:34:57 +02:00
ret = []
try:
if bypath is None and byname is not None and \
self.cfgimpl_get_description() is not None:
bypath = self._find(bytype=None, byvalue=None, byname=byname,
first=True, type_='path',
check_properties=False)
except ConfigError:
pass
for child in self._impl_children:
2013-05-02 11:34:57 +02:00
try:
if not isinstance(child, MetaConfig):
if bypath is not None:
if byvalue is not None:
if getattr(child, bypath) == byvalue:
ret.append(child)
else:
#not raise
getattr(child, bypath)
ret.append(child)
else:
ret.append(child.find_first(byname=byname,
byvalue=byvalue,
2013-07-17 23:02:50 +02:00
type_=type_,
display_error=False))
2013-05-02 11:34:57 +02:00
else:
ret.extend(child.find_first_contexts(byname=byname,
bypath=bypath,
byvalue=byvalue,
2013-07-17 23:02:50 +02:00
type_=type_,
display_error=False))
2013-05-02 11:34:57 +02:00
except AttributeError:
pass
return ret
def mandatory_warnings(config):
2012-10-05 16:00:07 +02:00
"""convenience function to trace Options that are mandatory and
where no value has been set
:returns: generator of mandatory Option's path
2013-05-21 18:42:56 +02:00
2012-10-05 16:00:07 +02:00
"""
#if value in cache, properties are not calculated
config.cfgimpl_reset_cache(only=('values',))
2013-08-21 18:34:32 +02:00
for path in config.cfgimpl_get_description().impl_getpaths(
include_groups=True):
try:
config._getattr(path, force_properties=frozenset(('mandatory',)))
except PropertiesOptionError, err:
if err.proptype == ['mandatory']:
yield path
config.cfgimpl_reset_cache(only=('values',))