add docstring and some docs

This commit is contained in:
gwen 2012-10-05 16:00:07 +02:00
parent 8ca58c508d
commit d3dc40033b
11 changed files with 398 additions and 547 deletions

View File

@ -104,7 +104,6 @@ method :
>>> config.get('bool') >>> config.get('bool')
True True
To find the right option, `get()` searches recursively into the whole To find the right option, `get()` searches recursively into the whole
tree. For example, to find an option which is in the `gc` namespace tree. For example, to find an option which is in the `gc` namespace
there are two possibilites. there are two possibilites.
@ -160,4 +159,3 @@ value has been changed and no bad side effect won't occur
>>> booloption.setoption(cfg, False, 'owner') >>> booloption.setoption(cfg, False, 'owner')
>>> cfg.bool >>> cfg.bool
>>> False >>> False

View File

@ -83,7 +83,7 @@ it is possible to
the order of the :ref:`optionapi#schema` specification entries, the order of the :ref:`optionapi#schema` specification entries,
- compare two configs (equality), - compare two configs (equality),
- export the whole config into a `dict` with :api:`config.make_dict()`, - export the whole config into a `dict` with :api:`config.make_dict()`,
- `validate()` an option value into a config, see :doc:`consistency`. .. - `validate()` an option value into a config, see :doc:`consistency`.
:api:`option.Option()` objects in a config are iterable in the pythonic :api:`option.Option()` objects in a config are iterable in the pythonic
way, that is something like `[(name, value) for name, value in config]`. way, that is something like `[(name, value) for name, value in config]`.
@ -100,4 +100,3 @@ To iter on groups in the same manner, use the
To iter on groups objects only. To iter on groups objects only.
All groups are returned if `group_type` is `None`, otherwise the groups All groups are returned if `group_type` is `None`, otherwise the groups
can be filtered by categories (families, or whatever). can be filtered by categories (families, or whatever).

View File

@ -6,6 +6,18 @@ The global configuration's consistency
:module: :api:`config.py` :module: :api:`config.py`
:tests: :api:`test_option_consistency.py` :tests: :api:`test_option_consistency.py`
Identical option names
----------------------
If an :api:`option.Option()` happens to be defined twice in the
:ref:`glossary#schema` (e.g. the :api:`option.OptionDescription()`),
that is the two options actually have the same name, an exception is raised.
The calculation is currently carried out in the samespace, for example
if `config.gc.name` is defined, another option in `gc` with the name
`name` is **not** allowed, whereas `config.whateverelse.name` is still
allowed.
Option's values type validation Option's values type validation
-------------------------------- --------------------------------
@ -59,7 +71,6 @@ in
- :api:`test_option_consistency.test_newoption_add_in_subdescr()` - :api:`test_option_consistency.test_newoption_add_in_subdescr()`
- :api:`test_option_consistency.test_newoption_add_in_config()` - :api:`test_option_consistency.test_newoption_add_in_config()`
Validation upon a whole configuration object Validation upon a whole configuration object
---------------------------------------------- ----------------------------------------------
@ -76,27 +87,3 @@ For example, the configuration paths have to be unique in the
Other hook are availables to validate upon a whole configuration at any Other hook are availables to validate upon a whole configuration at any
time. time.
Identical option names
----------------------
If an :api:`option.Option()` happens to be defined twice in the
:ref:`glossary#schema` (e.g. the :api:`option.OptionDescription()`),
that is the two options actually have the same name, an exception is raised.
The calculation is currently carried out in the samespace, for example
if `config.gc.name` is defined, another option in `gc` with the name
`name` is **not** allowed, whereas `config.whateverelse.name` is still
allowed.
.. the calculation was carried out by the requires, wich is not a goog idead
Type constraints with the `multi` type
----------------------------------------
By convention, if a multi option has somme requires, the constraints on
the multi type is in all the OptionGroup (a group has to be `multi`, and
a multi of the same length).
See :api:`test_option_consistency.test_multi_constraints()`

View File

@ -1,70 +0,0 @@
- abstract values from `gaspacho`
Les types possibles :
- sans valeur : `boolean`
- avec valeur : `unicode` (un texte libre), `integer` (un chiffre), `enum` (une liste de choix prédéfinies) et `list` (une liste de choix libres).
Les types sans valeurs sont les plus simples. Par exemple cette règle nattend
aucune valeur particulière Vérifier que Firefox est le navigateur par défaut.
Alors que celle-ci attend une adresse IP Configuration du serveur proxy manuelle.
Il existe un autre type (multi) qui permet de mêler plusieurs types.
Il sagit bien de définir ici le type de la règle (et uniquement de la règle).
- configuration levels in `creole`
*thu, 28 april 2011*
Exemple de niveau de configuration (dans l'ordre) :
1. - Coeur
2.
- Coeur
- gen_config
3.
- Coeur
- gen_config
- EAD
4.
- Coeur
- EAD
5.
- Coeur
- baculaconfig.py
(`fill` : calcule une valeur jusqu'à ce que l'utilisateur change la
valeur)
Gestion des ACL en écriture :
Le coeur charge les variables
- si auto : seul le coeur peut la modifier (cas 1) ;
- si fill : le coeur calcule une valeur tant que pas configuré par
l'utilisateur. L'utilisateur peut modifier (cas 2 ou 3) ;
- des variables modifiables que par gen_config (cas 2) ;
- des variables modifiables par gen_config ou l'EAD (cas 3) ;
- des variables d'autres applications (cas 4 et 5).
Gestion des ACLs en lecture :
- seule une application peut lire certaines variables (exemple un mot de
passe).

View File

@ -57,7 +57,7 @@ glossary
**forced on freeze** **forced on freeze**
A single option is frozen and we want the option to return something A single option is frozen and we want the option to return something
else than his value, for example his default value, see else than his value, typically his default value, see
:ref:`status#frozen` :ref:`status#frozen`
.. _`valueowner`: .. _`valueowner`:
@ -83,16 +83,6 @@ glossary
a disabled option has a different behaviour on regards to the access a disabled option has a different behaviour on regards to the access
of the value in the configuration, see :doc:`status` for more details. of the value in the configuration, see :doc:`status` for more details.
**fill option**
a fill option is like an automatic option except that it is
calculated only if a value hasn't been set.
**auto option**
an automatic option is an option thas is carried out by an external
calculation
.. _mandatory: .. _mandatory:
**mandatory option** **mandatory option**
@ -101,7 +91,6 @@ glossary
set, that is the default value cannot be `None`, see set, that is the default value cannot be `None`, see
:ref:`optionapi#optioninit` :ref:`optionapi#optioninit`
.. _consistency: .. _consistency:
**consistency** **consistency**

View File

@ -124,4 +124,3 @@ Represents a choice out of several objects. The option can also have the value
``__init__(self, name, doc, values, default=None, requires=None)`` ``__init__(self, name, doc, values, default=None, requires=None)``
``values`` is a list of values the option can possibly take. ``values`` is a list of values the option can possibly take.

View File

@ -1,82 +0,0 @@
#!/usr/bin/python
# unproudly borrowed from David Goodger's rst2html.py
"""
A minimal front end to the Docutils Publisher, producing HTML.
"""
try:
import locale
locale.setlocale(locale.LC_ALL, '')
except:
pass
from docutils.core import publish_cmdline, default_description
# ____________________________________________________________
from docutils import nodes, utils
from docutils.parsers.rst import roles
from docutils.writers import manpage
"""
description of the new roles:
`:api:` : link to the code
- code.py becomes api/code.html
- code.Code.code_test becomes api/code.Code.code_test.html
- code.Code() becomes api/code.Code.html
`:doc:`a link to an internal file
example become example.html
ref: link with anchor as in an external file
:ref:`toto#titi` becomes toto.html#titi
"""
from os.path import splitext
def api_reference_role(role, rawtext, text, lineno, inliner,
options={}, content=[]):
basename = text
if "(" in text:
basename = text.split("(")[0]
if ".py" in text:
basename = splitext(text)[0]
if "test_" in text:
refuri = "api/" + "tiramisu.test." + basename + '.html'
else:
refuri = "api/" + "tiramisu." + basename + '.html'
roles.set_classes(options)
node = nodes.reference(rawtext, utils.unescape(text), refuri=refuri,
**options)
return [node], []
roles.register_local_role('api', api_reference_role)
def doc_reference_role(role, rawtext, text, lineno, inliner,
options={}, content=[]):
refuri = text + '.html'
roles.set_classes(options)
node = nodes.reference(rawtext, utils.unescape(text), refuri=refuri,
**options)
return [node], []
roles.register_local_role('doc', doc_reference_role)
def ref_reference_role(role, rawtext, text, lineno, inliner,
options={}, content=[]):
fname, anchor = text.split('#')
refuri = fname + '.html#' + anchor
roles.set_classes(options)
node = nodes.reference(rawtext, utils.unescape(anchor), refuri=refuri,
**options)
return [node], []
roles.register_local_role('ref', ref_reference_role)
# ____________________________________________________________
description = ("Generates plain unix manual documents. " + default_description)
publish_cmdline(writer=manpage.Writer(), description=description)

View File

@ -67,11 +67,12 @@ Restricted access to an `Option()`
----------------------------------- -----------------------------------
Configuration options access statuses are defined at configuration level Configuration options access statuses are defined at configuration level
that corresponds to the :api:`option.Option()`'s `properties` attribute. that corresponds to the :api:`option.Option()`'s `properties` attribute,
for example
**hidden** **hidden**
This means that an option raises an `HiddenOptionError` if we try to access This means that an option raises an error if we try to access
the value of the option. the value of the option.
See `hide()` or `show()` in `Option()` that comes from See `hide()` or `show()` in `Option()` that comes from
@ -143,7 +144,12 @@ configuration option.
Special behaviors for an option Special behaviors for an option
--------------------------------- ---------------------------------
**auto** **mandatory**
A mandatory option shall return a value. If a value, or a default value
has not been set, a error is raised.
**has a callback**
This means that it is a calculated value and therefore automatically This means that it is a calculated value and therefore automatically
protected it cannot be modified by attribute access. protected it cannot be modified by attribute access.
@ -151,15 +157,12 @@ Special behaviors for an option
Its inner state is represented by :api:`option.Option.has_callback()` Its inner state is represented by :api:`option.Option.has_callback()`
and :api:`option.Option.hascallback_and_isfrozen()` and :api:`option.Option.hascallback_and_isfrozen()`
**fill** **force default**
if the configuration option has a default value, the default is if the configuration option has a default value, the default is
returned, otherwise the value is calculated. returned, otherwise the value is calculated.
Its inner state is represented by :api:`option.Option.has_callback()` Its inner state is represented by :api:`option.Option.force_default()`
`default` value owner
----------------------
Configuration options have default values that are stored in the Configuration options have default values that are stored in the
`Option()` object itself. Default values, the `default`, can be set in `Option()` object itself. Default values, the `default`, can be set in
@ -168,4 +171,3 @@ various ways.
If a default value is modified by overriding it, not only the value of If a default value is modified by overriding it, not only the value of
the option resets to the default that is proposed, but the owner is the option resets to the default that is proposed, but the owner is
modified too, it is reseted to `default`. modified too, it is reseted to `default`.

View File

@ -45,22 +45,11 @@ alors que gc est un groupe
:date: 12 avril :date: 12 avril
- faire un mode dégradé avec des warnings
- validations de longueur des maitres/esclaves ailleurs à sortir des requires - validations de longueur des maitres/esclaves ailleurs à sortir des requires
et à mettre dans des validators et à mettre dans des validators
:date: 3 avril 2012 :date: 3 avril 2012
- hide sur les sous-sous groupe : il faut que ça hide **tout** les sous-groupe
récursivement
groupes `master/slaves`:
faut-il coder les multi avec des requires, ou bien simplement
un groupe avec comme variable le nom du groupe ?
auto, fill, obligatoire
2012-03-22 2012-03-22
**groupe master** **groupe master**
@ -68,17 +57,10 @@ auto, fill, obligatoire
faire une api du genre : `Option().is_master()` faire une api du genre : `Option().is_master()`
pour cela, tester `if self.parent._name == self._name: return True` pour cela, tester `if self.parent._name == self._name: return True`
- mettre un attribut `auto` aux options de configuration, de manière à
ce qu'elles sachent quelle fonction eos appeler (que ça soit une info
dans l'option ou bien au niveau de la config ?)
le fait de détecter un "auto" vient du owner, mais il faut savoir
quelle fonction appeler
A documenter A documenter
------------- -------------
- les variables multiples - les variables multiples
- expliquer les urls du json dans la doc
- documenter le typage des options descriptions descr_type - documenter le typage des options descriptions descr_type
A ajouter A ajouter
@ -87,40 +69,5 @@ A ajouter
Option -> attribut help (en plus de doc) Option -> attribut help (en plus de doc)
get_help() (à mettre en class Type avec Doc aussi) get_help() (à mettre en class Type avec Doc aussi)
separator -> pas pour l'instant
fill, auto, obligatoire
nouveau type :
type option (dérivé de ChoiceOPtion) dans lequel il y a des nouvelles valeurs
possibles (pas de validations) ou plutôt une StringOption qui propose un choix
de valeurs par défault de type liste.
:date: 24 mars
- hide pour les sous-sous config (récursivement) et pas seulement une
seule sous-config (ou bien, quelque chose de réglable)
- validate global : vérifier à l'init de la conf qu'une variable
n'existe pas déjà, etc
:date: 26 janvier
- un attribut eosfunc pour auto + les paramètres à donner à la fonction
pareil pour le fill (function et paramètres)
reset
-------
**à discuter** : ça correspond exactement au override,
ou bien au opt.setoption(None, 'default')
**si la valeur par défaut est définie, un __get__ ne pourra jamais
renvoyer None.** ce qui est bloquant. Il faut pouvoir revenir à None.
pour supprimer la valeur d'une options (et revenir à la valeur par défault)
cfg.reset() (supprime _cfgimpl_value[name]) et _cfgimpl_value_owner[name])
reset()

View File

@ -33,29 +33,40 @@ from tiramisu.autolib import carry_out_calculation
default_owner = 'user' default_owner = 'user'
# ____________________________________________________________ # ____________________________________________________________
class Config(object): class Config(object):
"properties attribute: the name of a property enables this property"
_cfgimpl_properties = ['hidden', 'disabled'] _cfgimpl_properties = ['hidden', 'disabled']
"mandatory means: a mandatory option has to have a value that is not None"
_cfgimpl_mandatory = True _cfgimpl_mandatory = True
_cfgimpl_frozen = True _cfgimpl_frozen = True
_cfgimpl_owner = default_owner _cfgimpl_owner = default_owner
_cfgimpl_toplevel = None _cfgimpl_toplevel = None
# TODO implement unicity by name
# _cfgimpl_unique_names = True
def __init__(self, descr, parent=None, **overrides): def __init__(self, descr, parent=None, **overrides):
""" Configuration option management master class
:param descr: describes the configuration schema
:type descr: an instance of ``option.OptionDescription``
:param overrides: can be used to set different default values
(see method ``override``)
:param parent: is None if the ``Config`` is root parent Config otherwise
:type parent: ``Config``
"""
self._cfgimpl_descr = descr self._cfgimpl_descr = descr
self._cfgimpl_value_owners = {} self._cfgimpl_value_owners = {}
self._cfgimpl_parent = parent self._cfgimpl_parent = parent
# `Config()` indeed takes care of the `Option()`'s values "`Config()` indeed is in charge of the `Option()`'s values"
self._cfgimpl_values = {} self._cfgimpl_values = {}
self._cfgimpl_previous_values = {} self._cfgimpl_previous_values = {}
# XXX warnings are a great idea, let's make up a better use of it "warnings are a great idea, let's make up a better use of it"
self._cfgimpl_warnings = [] self._cfgimpl_warnings = []
self._cfgimpl_toplevel = self._cfgimpl_get_toplevel() self._cfgimpl_toplevel = self._cfgimpl_get_toplevel()
# `freeze()` allows us to carry out this calculation again if necessary '`freeze()` allows us to carry out this calculation again if necessary'
self._cfgimpl_frozen = self._cfgimpl_toplevel._cfgimpl_frozen self._cfgimpl_frozen = self._cfgimpl_toplevel._cfgimpl_frozen
self._cfgimpl_build(overrides) self._cfgimpl_build(overrides)
def _validate_duplicates(self, children): def _validate_duplicates(self, children):
"""duplicates Option names in the schema
:type children: list of `Option` or `OptionDescription`
"""
duplicates = [] duplicates = []
for dup in children: for dup in children:
if dup._name not in duplicates: if dup._name not in duplicates:
@ -64,27 +75,12 @@ class Config(object):
raise ConflictConfigError('duplicate option name: ' raise ConflictConfigError('duplicate option name: '
'{0}'.format(dup._name)) '{0}'.format(dup._name))
# TODO implement unicity by name
# def _validate_duplicates_for_names(self, children):
# "validates duplicates names agains the whole config"
# rootconfig = self._cfgimpl_get_toplevel()
# if self._cfgimpl_unique_names:
# for dup in children:
# try:
# print dup._name
# try:
# print rootconfig.get(dup._name)
# except AttributeError:
# pass
# raise NotFoundError
# #rootconfig.get(dup._name)
# except NotFoundError:
# pass # no identical names, it's fine
# else:
# raise ConflictConfigError('duplicate option name: '
# '{0}'.format(dup._name))
def _cfgimpl_build(self, overrides): def _cfgimpl_build(self, overrides):
"""
- builds the config object from the schema
- settles various default values for options
:param overrides: dict of options name:default values
"""
self._validate_duplicates(self._cfgimpl_descr._children) self._validate_duplicates(self._cfgimpl_descr._children)
for child in self._cfgimpl_descr._children: for child in self._cfgimpl_descr._children:
if isinstance(child, Option): if isinstance(child, Option):
@ -106,8 +102,8 @@ class Config(object):
self.override(overrides) self.override(overrides)
def cfgimpl_update(self): def cfgimpl_update(self):
"dynamically adds `Option()` or `OptionDescription()`" """dynamically adds `Option()` or `OptionDescription()`
# Nothing is static. Everything evolve. """
# FIXME this is an update for new options in the schema only # FIXME this is an update for new options in the schema only
# see the update_child() method of the descr object # see the update_child() method of the descr object
for child in self._cfgimpl_descr._children: for child in self._cfgimpl_descr._children:
@ -126,23 +122,33 @@ class Config(object):
self._cfgimpl_values[child._name] = Config(child, parent=self) self._cfgimpl_values[child._name] = Config(child, parent=self)
def override(self, overrides): def override(self, overrides):
"""
overrides default values. This marks the overridden values as defaults.
:param overrides: is a dictionary of path strings to values.
"""
for name, value in overrides.iteritems(): for name, value in overrides.iteritems():
homeconfig, name = self._cfgimpl_get_home_by_path(name) homeconfig, name = self._cfgimpl_get_home_by_path(name)
homeconfig.setoption(name, value, 'default') homeconfig.setoption(name, value, 'default')
def cfgimpl_set_owner(self, owner): def cfgimpl_set_owner(self, owner):
":param owner: sets the default value for owner at the Config level"
self._cfgimpl_owner = owner self._cfgimpl_owner = owner
for child in self._cfgimpl_descr._children: for child in self._cfgimpl_descr._children:
if isinstance(child, OptionDescription): if isinstance(child, OptionDescription):
self._cfgimpl_values[child._name].cfgimpl_set_owner(owner) self._cfgimpl_values[child._name].cfgimpl_set_owner(owner)
# ____________________________________________________________ # ____________________________________________________________
# properties methods
def _cfgimpl_has_properties(self): def _cfgimpl_has_properties(self):
"has properties means the Config's properties attribute is not empty"
return bool(len(self._cfgimpl_properties)) return bool(len(self._cfgimpl_properties))
def _cfgimpl_has_property(self, propname): def _cfgimpl_has_property(self, propname):
"""has property propname in the Config's properties attribute
:param property: string wich is the name of the property"""
return propname in self._cfgimpl_properties return propname in self._cfgimpl_properties
def cfgimpl_enable_property(self, propname): def cfgimpl_enable_property(self, propname):
"puts property propname in the Config's properties attribute"
if self._cfgimpl_parent != None: if self._cfgimpl_parent != None:
raise MethodCallError("this method root_hide() shall not be" raise MethodCallError("this method root_hide() shall not be"
"used with non-root Config() object") "used with non-root Config() object")
@ -150,21 +156,16 @@ class Config(object):
self._cfgimpl_properties.append(propname) self._cfgimpl_properties.append(propname)
def cfgimpl_disable_property(self, propname): def cfgimpl_disable_property(self, propname):
"deletes property propname in the Config's properties attribute"
if self._cfgimpl_parent != None: if self._cfgimpl_parent != None:
raise MethodCallError("this method root_hide() shall not be" raise MethodCallError("this method root_hide() shall not be"
"used with non-root Config() object") "used with non-root Config() object")
if self._cfgimpl_has_property(propname): if self._cfgimpl_has_property(propname):
self._cfgimpl_properties.remove(propname) self._cfgimpl_properties.remove(propname)
def cfgimpl_non_mandatory(self):
if self._cfgimpl_parent != None:
raise MethodCallError("this method root_mandatory machin() shall not be"
"used with non-root Confit() object")
rootconfig = self._cfgimpl_get_toplevel()
rootconfig._cfgimpl_mandatory = False
# ____________________________________________________________ # ____________________________________________________________
# attribute methods
def __setattr__(self, name, value): def __setattr__(self, name, value):
"attribute notation mechanism for the setting of the value of an option"
if name.startswith('_cfgimpl_'): if name.startswith('_cfgimpl_'):
self.__dict__[name] = value self.__dict__[name] = value
return return
@ -176,6 +177,7 @@ class Config(object):
self.setoption(name, value, self._cfgimpl_owner) self.setoption(name, value, self._cfgimpl_owner)
def _validate(self, name, opt_or_descr): def _validate(self, name, opt_or_descr):
"validation for the setattr and the getattr"
apply_requires(opt_or_descr, self) apply_requires(opt_or_descr, self)
if not isinstance(opt_or_descr, Option) and \ if not isinstance(opt_or_descr, Option) and \
not isinstance(opt_or_descr, OptionDescription): not isinstance(opt_or_descr, OptionDescription):
@ -191,6 +193,7 @@ class Config(object):
properties) properties)
def _is_empty(self, opt): def _is_empty(self, opt):
"convenience method to know if an option is empty"
if (not opt.is_multi() and self._cfgimpl_values[opt._name] == None) or \ if (not opt.is_multi() and self._cfgimpl_values[opt._name] == None) or \
(opt.is_multi() and (self._cfgimpl_values[opt._name] == [] or \ (opt.is_multi() and (self._cfgimpl_values[opt._name] == [] or \
None in self._cfgimpl_values[opt._name])): None in self._cfgimpl_values[opt._name])):
@ -198,6 +201,7 @@ class Config(object):
return False return False
def __getattr__(self, name): def __getattr__(self, name):
"attribute notation mechanism for accessing the value of an option"
# attribute access by passing a path, # attribute access by passing a path,
# for instance getattr(self, "creole.general.family.adresse_ip_eth0") # for instance getattr(self, "creole.general.family.adresse_ip_eth0")
if '.' in name: if '.' in name:
@ -267,15 +271,12 @@ class Config(object):
return self._cfgimpl_values[name] return self._cfgimpl_values[name]
# def __dir__(self):
# #from_type = dir(type(self))
# from_dict = list(self.__dict__)
# extras = list(self._cfgimpl_values)
# return sorted(set(extras + from_dict))
def unwrap_from_name(self, name): def unwrap_from_name(self, name):
# didn't have to stoop so low: `self.get()` must be the proper method """convenience method to extract and Option() object from the Config()
# **and it is slow**: it recursively searches into the namespaces **and it is slow**: it recursively searches into the namespaces
:returns: Option()
"""
paths = self.getpaths(allpaths=True) paths = self.getpaths(allpaths=True)
opts = dict([(path, self.unwrap_from_path(path)) for path in paths]) opts = dict([(path, self.unwrap_from_path(path)) for path in paths])
all_paths = [p.split(".") for p in self.getpaths()] all_paths = [p.split(".") for p in self.getpaths()]
@ -285,15 +286,19 @@ class Config(object):
raise NotFoundError("name: {0} not found".format(name)) raise NotFoundError("name: {0} not found".format(name))
def unwrap_from_path(self, path): def unwrap_from_path(self, path):
# didn't have to stoop so low, `geattr(self, path)` is much better """convenience method to extract and Option() object from the Config()
# **fast**: finds the option directly in the appropriate namespace and it is **fast**: finds the option directly in the appropriate
namespace
:returns: Option()
"""
if '.' in path: if '.' in path:
homeconfig, path = self._cfgimpl_get_home_by_path(path) homeconfig, path = self._cfgimpl_get_home_by_path(path)
return getattr(homeconfig._cfgimpl_descr, path) return getattr(homeconfig._cfgimpl_descr, path)
return getattr(self._cfgimpl_descr, path) return getattr(self._cfgimpl_descr, path)
def __delattr__(self, name): def __delattr__(self, name):
# if you use delattr you are responsible for all bad things happening "if you use delattr you are responsible for all bad things happening"
if name.startswith('_cfgimpl_'): if name.startswith('_cfgimpl_'):
del self.__dict__[name] del self.__dict__[name]
return return
@ -304,8 +309,13 @@ class Config(object):
self._cfgimpl_values[name] = getattr(opt, 'default', None) self._cfgimpl_values[name] = getattr(opt, 'default', None)
def setoption(self, name, value, who=None): def setoption(self, name, value, who=None):
#who is **not necessarily** a owner, because it cannot be a list """effectively modifies the value of an Option()
#FIXME : sortir le setoption pour les multi, ca ne devrait pas être la (typically called by the __setattr__)
:param who: is an owner's name
who is **not necessarily** a owner, because it cannot be a list
:type who: string
"""
child = getattr(self._cfgimpl_descr, name) child = getattr(self._cfgimpl_descr, name)
if who == None: if who == None:
if child.is_multi(): if child.is_multi():
@ -343,6 +353,13 @@ class Config(object):
child.setoption(homeconfig, value, who) child.setoption(homeconfig, value, who)
def set(self, **kwargs): def set(self, **kwargs):
"""
"do what I mean"-interface to option setting. Searches all paths
starting from that config for matches of the optional arguments
and sets the found option if the match is not ambiguous.
:param kwargs: dict of name strings to values.
"""
all_paths = [p.split(".") for p in self.getpaths(allpaths=True)] all_paths = [p.split(".") for p in self.getpaths(allpaths=True)]
for key, value in kwargs.iteritems(): for key, value in kwargs.iteritems():
key_p = key.split('.') key_p = key.split('.')
@ -366,6 +383,12 @@ class Config(object):
' or the option is hidden or disabled'% (key, )) ' or the option is hidden or disabled'% (key, ))
def get(self, name): def get(self, name):
"""
much like the attribute access way, except that
the search for the option is performed recursively in the whole
configuration tree.
**carefull**: very slow !
"""
paths = self.getpaths(allpaths=True) paths = self.getpaths(allpaths=True)
pathsvalues = [] pathsvalues = []
for path in paths: for path in paths:
@ -379,62 +402,64 @@ class Config(object):
raise NotFoundError("option {0} not found in config".format(name)) raise NotFoundError("option {0} not found in config".format(name))
def _cfgimpl_get_home_by_path(self, path): def _cfgimpl_get_home_by_path(self, path):
"""returns tuple (config, name)""" """:returns: tuple (config, name)"""
path = path.split('.') path = path.split('.')
for step in path[:-1]: for step in path[:-1]:
self = getattr(self, step) self = getattr(self, step)
return self, path[-1] return self, path[-1]
def _cfgimpl_get_toplevel(self): def _cfgimpl_get_toplevel(self):
":returns: root config"
while self._cfgimpl_parent is not None: while self._cfgimpl_parent is not None:
self = self._cfgimpl_parent self = self._cfgimpl_parent
return self return self
def _cfgimpl_get_path(self): def _cfgimpl_get_path(self):
"the path in the attribute access meaning."
subpath = [] subpath = []
obj = self obj = self
while obj._cfgimpl_parent is not None: while obj._cfgimpl_parent is not None:
subpath.insert(0, obj._cfgimpl_descr._name) subpath.insert(0, obj._cfgimpl_descr._name)
obj = obj._cfgimpl_parent obj = obj._cfgimpl_parent
return ".".join(subpath) return ".".join(subpath)
# ______________________________________________________________________
def cfgimpl_previous_value(self, path): def cfgimpl_previous_value(self, path):
"stores the previous value"
home, name = self._cfgimpl_get_home_by_path(path) home, name = self._cfgimpl_get_home_by_path(path)
return home._cfgimpl_previous_values[name] return home._cfgimpl_previous_values[name]
def get_previous_value(self, name): def get_previous_value(self, name):
"for the time being, only the previous Option's value is accessible"
return self._cfgimpl_previous_values[name] return self._cfgimpl_previous_values[name]
# ______________________________________________________________________
def add_warning(self, warning): def add_warning(self, warning):
"Config implements its own warning pile. Could be useful"
self._cfgimpl_get_toplevel()._cfgimpl_warnings.append(warning) self._cfgimpl_get_toplevel()._cfgimpl_warnings.append(warning)
def get_warnings(self): def get_warnings(self):
"Config implements its own warning pile"
return self._cfgimpl_get_toplevel()._cfgimpl_warnings return self._cfgimpl_get_toplevel()._cfgimpl_warnings
# ____________________________________________________________ # ____________________________________________________________
# freeze and read-write statuses # Config()'s status
def cfgimpl_freeze(self): def cfgimpl_freeze(self):
"cannot modify the frozen `Option`'s"
rootconfig = self._cfgimpl_get_toplevel() rootconfig = self._cfgimpl_get_toplevel()
rootconfig._cfgimpl_frozen = True rootconfig._cfgimpl_frozen = True
self._cfgimpl_frozen = True self._cfgimpl_frozen = True
def cfgimpl_unfreeze(self): def cfgimpl_unfreeze(self):
"can modify the Options that are frozen"
rootconfig = self._cfgimpl_get_toplevel() rootconfig = self._cfgimpl_get_toplevel()
rootconfig._cfgimpl_frozen = False rootconfig._cfgimpl_frozen = False
self._cfgimpl_frozen = False self._cfgimpl_frozen = False
def is_frozen(self): def is_frozen(self):
# it should be the same value as self._cfgimpl_frozen... "freeze flag at Config level"
rootconfig = self._cfgimpl_get_toplevel() rootconfig = self._cfgimpl_get_toplevel()
return rootconfig._cfgimpl_frozen return rootconfig._cfgimpl_frozen
def is_mandatory(self):
rootconfig = self._cfgimpl_get_toplevel()
return rootconfig._cfgimpl_mandatory
def cfgimpl_read_only(self): def cfgimpl_read_only(self):
# convenience method to freeze, hidde and disable "convenience method to freeze, hidde and disable"
self.cfgimpl_freeze() self.cfgimpl_freeze()
rootconfig = self._cfgimpl_get_toplevel() rootconfig = self._cfgimpl_get_toplevel()
rootconfig.cfgimpl_disable_property('hidden') rootconfig.cfgimpl_disable_property('hidden')
@ -442,12 +467,35 @@ class Config(object):
rootconfig._cfgimpl_mandatory = True rootconfig._cfgimpl_mandatory = True
def cfgimpl_read_write(self): def cfgimpl_read_write(self):
# convenience method to freeze, hidde and disable "convenience method to freeze, hidde and disable"
self.cfgimpl_freeze() self.cfgimpl_freeze()
rootconfig = self._cfgimpl_get_toplevel() rootconfig = self._cfgimpl_get_toplevel()
rootconfig.cfgimpl_enable_property('hidden') rootconfig.cfgimpl_enable_property('hidden')
rootconfig.cfgimpl_enable_property('disabled') rootconfig.cfgimpl_enable_property('disabled')
rootconfig._cfgimpl_mandatory = False rootconfig._cfgimpl_mandatory = False
def cfgimpl_non_mandatory(self):
"""mandatory at the Config level means that the Config raises an error
if a mandatory option is found"""
if self._cfgimpl_parent != None:
raise MethodCallError("this method root_mandatory shall"
" not be used with non-root Confit() object")
rootconfig = self._cfgimpl_get_toplevel()
rootconfig._cfgimpl_mandatory = False
def cfgimpl_mandatory(self):
"""mandatory at the Config level means that the Config raises an error
if a mandatory option is found"""
if self._cfgimpl_parent != None:
raise MethodCallError("this method root_mandatory shall"
" not be used with non-root Confit() object")
rootconfig = self._cfgimpl_get_toplevel()
rootconfig._cfgimpl_mandatory = True
def is_mandatory(self):
"all mandatory Options shall have a value"
rootconfig = self._cfgimpl_get_toplevel()
return rootconfig._cfgimpl_mandatory
# ____________________________________________________________ # ____________________________________________________________
def getkey(self): def getkey(self):
return self._cfgimpl_descr.getkey(self) return self._cfgimpl_descr.getkey(self)
@ -456,13 +504,15 @@ class Config(object):
return hash(self.getkey()) return hash(self.getkey())
def __eq__(self, other): def __eq__(self, other):
"Config comparison"
return self.getkey() == other.getkey() return self.getkey() == other.getkey()
def __ne__(self, other): def __ne__(self, other):
"Config comparison"
return not self == other return not self == other
# ______________________________________________________________________
def __iter__(self): def __iter__(self):
# iteration only on Options (not OptionDescriptions) "iteration only on Options (not OptionDescriptions)"
for child in self._cfgimpl_descr._children: for child in self._cfgimpl_descr._children:
if isinstance(child, Option): if isinstance(child, Option):
try: try:
@ -485,8 +535,9 @@ class Config(object):
yield child._name, getattr(self, child._name) yield child._name, getattr(self, child._name)
except: except:
pass # hidden, disabled option pass # hidden, disabled option
# ______________________________________________________________________
def __str__(self, indent=""): def __str__(self, indent=""):
"Config's string representation"
lines = [] lines = []
children = [(child._name, child) children = [(child._name, child)
for child in self._cfgimpl_descr._children] for child in self._cfgimpl_descr._children]
@ -520,12 +571,14 @@ class Config(object):
paths.append(path) paths.append(path)
except PropertiesOptionError: except PropertiesOptionError:
if allpaths: if allpaths:
paths.append(path) # hidden or disabled or mandatory option added paths.append(path) # option which have properties added
else: else:
paths.append(path) paths.append(path)
return paths return paths
def make_dict(config, flatten=False): def make_dict(config, flatten=False):
"""export the whole config into a `dict`
:returns: dict of Option's name (or path) and values"""
paths = config.getpaths() paths = config.getpaths()
pathsvalues = [] pathsvalues = []
for path in paths: for path in paths:
@ -542,6 +595,11 @@ def make_dict(config, flatten=False):
return options return options
def mandatory_warnings(config): def mandatory_warnings(config):
"""convenience function to trace Options that are mandatory and
where no value has been set
:returns: generator of mandatory Option's path
"""
mandatory = config._cfgimpl_get_toplevel()._cfgimpl_mandatory mandatory = config._cfgimpl_get_toplevel()._cfgimpl_mandatory
config._cfgimpl_get_toplevel()._cfgimpl_mandatory = True config._cfgimpl_get_toplevel()._cfgimpl_mandatory = True
for path in config._cfgimpl_descr.getpaths(include_groups=True): for path in config._cfgimpl_descr.getpaths(include_groups=True):

View File

@ -31,9 +31,14 @@ for act1, act2 in requires_actions:
available_actions.extend([act1, act2]) available_actions.extend([act1, act2])
reverse_actions[act1] = act2 reverse_actions[act1] = act2
reverse_actions[act2] = act1 reverse_actions[act2] = act1
# ____________________________________________________________ # ____________________________________________________________
# OptionDescription authorized group_type values # OptionDescription authorized group_type values
"""
Three available group_types : `default`, `family`, `group` and
`master` (for master~slave group type). Notice that for a
master~slave group, the name of the group and the name of the
master option are identical.
"""
group_types = ['default', 'family', 'group', 'master'] group_types = ['default', 'family', 'group', 'master']
# ____________________________________________________________ # ____________________________________________________________
# multi types # multi types
@ -86,8 +91,13 @@ class Multi(list):
# ____________________________________________________________ # ____________________________________________________________
# #
class Option(HiddenBaseType, DisabledBaseType): class Option(HiddenBaseType, DisabledBaseType):
#reminder: an Option object is **not** a container for the value """
Abstract base class for configuration option's
reminder: an Option object is **not** a container for the value
"""
"freeze means: cannot modify the value of an Option once set"
_frozen = False _frozen = False
"if an Option has been frozen, shall return the default value"
_force_default_on_freeze = False _force_default_on_freeze = False
def __init__(self, name, doc, default=None, default_multi=None, def __init__(self, name, doc, default=None, default_multi=None,
requires=None, mandatory=False, multi=False, callback=None, requires=None, mandatory=False, multi=False, callback=None,
@ -145,41 +155,53 @@ class Option(HiddenBaseType, DisabledBaseType):
return True return True
def getdefault(self): def getdefault(self):
"accessing the default value"
return self.default return self.default
def is_empty_by_default(self): def is_empty_by_default(self):
"no default value has been set yet"
if ((not self.is_multi() and self.default == None) or if ((not self.is_multi() and self.default == None) or
(self.is_multi() and self.default == []) or None in self.default): (self.is_multi() and self.default == []) or None in self.default):
return True return True
return False return False
def force_default(self): def force_default(self):
"if an Option has been frozen, shall return the default value"
self._force_default_on_freeze = True self._force_default_on_freeze = True
def hascallback_and_isfrozen(): def hascallback_and_isfrozen():
return self._frozen and self.has_callback() return self._frozen and self.has_callback()
def is_forced_on_freeze(self): def is_forced_on_freeze(self):
"if an Option has been frozen, shall return the default value"
return self._frozen and self._force_default_on_freeze return self._frozen and self._force_default_on_freeze
def getdoc(self): def getdoc(self):
"accesses the Option's doc"
return self.doc return self.doc
def getcallback(self): def getcallback(self):
"a callback is only a link, the name of an external hook"
return self.callback return self.callback
def has_callback(self): def has_callback(self):
"to know if a callback has been defined or not"
if self.callback == None: if self.callback == None:
return False return False
else: else:
return True return True
def getcallback_params(self): def getcallback_params(self):
"if a callback has been defined, returns his arity"
return self.callback_params return self.callback_params
def setowner(self, config, owner): def setowner(self, config, owner):
# config *must* be only the **parent** config (not the toplevel config) """
# owner is a **real* owner, a list is actually allowable here :param config: *must* be only the **parent** config
(not the toplevel config)
:param owner: is a **real* owner, that is a name or a list
which is allowable here
"""
name = self._name name = self._name
if self.is_multi(): if self.is_multi():
if not type(owner) == list: if not type(owner) == list:
@ -188,11 +210,14 @@ class Option(HiddenBaseType, DisabledBaseType):
config._cfgimpl_value_owners[name] = owner config._cfgimpl_value_owners[name] = owner
def getowner(self, config): def getowner(self, config):
# config *must* be only the **parent** config (not the toplevel config) "config *must* be only the **parent** config (not the toplevel config)"
return config._cfgimpl_value_owners[self._name] return config._cfgimpl_value_owners[self._name]
def setoption(self, config, value, who): def setoption(self, config, value, who):
"who is **not necessarily** a owner because it cannot be a list" """changes the option's value with the value_owner's who
:param config: the parent config is necessary here to store the value
:param who : is **not necessarily** a owner because it cannot be a list
:type who: string """
name = self._name name = self._name
if not self.validate(value): if not self.validate(value):
raise ConfigError('invalid value %s for option %s' % (value, name)) raise ConfigError('invalid value %s for option %s' % (value, name))
@ -245,19 +270,17 @@ class Option(HiddenBaseType, DisabledBaseType):
def getkey(self, value): def getkey(self, value):
return value return value
# ____________________________________________________________ # ____________________________________________________________
"freeze utility"
def freeze(self): def freeze(self):
self._frozen = True self._frozen = True
return True return True
def unfreeze(self): def unfreeze(self):
self._frozen = False self._frozen = False
def is_frozen(self): def is_frozen(self):
return self._frozen return self._frozen
# ____________________________________________________________ # ____________________________________________________________
def is_multi(self): def is_multi(self):
return self.multi return self.multi
def is_mandatory(self): def is_mandatory(self):
return self._mandatory return self._mandatory
@ -356,9 +379,14 @@ class ArbitraryOption(Option):
return self.default return self.default
class OptionDescription(HiddenBaseType, DisabledBaseType): class OptionDescription(HiddenBaseType, DisabledBaseType):
"Config's schema (organisation) and container of Options"
"the group_type is an attribute useful for iteration on groups in a config"
group_type = 'default' group_type = 'default'
def __init__(self, name, doc, children, requires=None): def __init__(self, name, doc, children, requires=None):
"""
:param children: is a list of option descriptions (including
``OptionDescription`` instances for nested namespaces).
"""
self._name = name self._name = name
self.doc = doc self.doc = doc
self._children = children self._children = children
@ -415,8 +443,8 @@ class OptionDescription(HiddenBaseType, DisabledBaseType):
paths.append('.'.join(currpath + [attr])) paths.append('.'.join(currpath + [attr]))
return paths return paths
# ____________________________________________________________ # ____________________________________________________________
def set_group_type(self, group_type): def set_group_type(self, group_type):
":param group_type: string in group_types"
if group_type in group_types: if group_type in group_types:
self.group_type = group_type self.group_type = group_type
else: else:
@ -426,29 +454,24 @@ class OptionDescription(HiddenBaseType, DisabledBaseType):
def get_group_type(self): def get_group_type(self):
return self.group_type return self.group_type
# ____________________________________________________________ # ____________________________________________________________
"actions API"
def hide(self): def hide(self):
super(OptionDescription, self).hide() super(OptionDescription, self).hide()
# FIXME : AND THE SUBCHILDREN ?
for child in self._children: for child in self._children:
if isinstance(child, OptionDescription): if isinstance(child, OptionDescription):
child.hide() child.hide()
def show(self): def show(self):
# FIXME : AND THE SUBCHILDREN ??
super(OptionDescription, self).show() super(OptionDescription, self).show()
for child in self._children: for child in self._children:
if isinstance(child, OptionDescription): if isinstance(child, OptionDescription):
child.show() child.show()
# ____________________________________________________________
def disable(self): def disable(self):
super(OptionDescription, self).disable() super(OptionDescription, self).disable()
# FIXME : AND THE SUBCHILDREN ?
for child in self._children: for child in self._children:
if isinstance(child, OptionDescription): if isinstance(child, OptionDescription):
child.disable() child.disable()
def enable(self): def enable(self):
# FIXME : AND THE SUBCHILDREN ?
super(OptionDescription, self).enable() super(OptionDescription, self).enable()
for child in self._children: for child in self._children:
if isinstance(child, OptionDescription): if isinstance(child, OptionDescription):
@ -456,7 +479,7 @@ class OptionDescription(HiddenBaseType, DisabledBaseType):
# ____________________________________________________________ # ____________________________________________________________
def validate_requires_arg(requires, name): def validate_requires_arg(requires, name):
# malformed requirements "malformed requirements"
config_action = [] config_action = []
for req in requires: for req in requires:
if not type(req) == tuple and len(req) != 3: if not type(req) == tuple and len(req) != 3:
@ -474,6 +497,7 @@ def validate_requires_arg(requires, name):
config_action.append(action) config_action.append(action)
def build_actions(requires): def build_actions(requires):
"action are hide, show, enable, disable..."
trigger_actions = {} trigger_actions = {}
for require in requires: for require in requires:
action = require[2] action = require[2]
@ -481,6 +505,7 @@ def build_actions(requires):
return trigger_actions return trigger_actions
def apply_requires(opt, config): def apply_requires(opt, config):
"carries out the jit (just in time requirements between options"
if hasattr(opt, '_requires') and opt._requires is not None: if hasattr(opt, '_requires') and opt._requires is not None:
rootconfig = config._cfgimpl_get_toplevel() rootconfig = config._cfgimpl_get_toplevel()
validate_requires_arg(opt._requires, opt._name) validate_requires_arg(opt._requires, opt._name)
@ -508,4 +533,3 @@ def apply_requires(opt, config):
# no callback has been triggered, then just reverse the action # no callback has been triggered, then just reverse the action
if not matches: if not matches:
getattr(opt, reverse_actions[action])() getattr(opt, reverse_actions[action])()