add option name's validation and rename Option method with objimpl_
[tiramisu.git] / tiramisu / config.py
index 84e16e4..a89f8e6 100644 (file)
@@ -21,7 +21,7 @@
 # the whole pypy projet is under MIT licence
 # ____________________________________________________________
 #from inspect import getmembers, ismethod
-from tiramisu.error import PropertiesOptionError, ConflictOptionError
+from tiramisu.error import PropertiesOptionError
 from tiramisu.option import OptionDescription, Option, SymLinkOption
 from tiramisu.setting import groups, Setting
 from tiramisu.value import Values
@@ -72,8 +72,8 @@ class SubConfig(object):
             return
         self._setattr(name, value)
 
-    def cfgimpl_reset_cache(self):
-        self.cfgimpl_get_context().cfgimpl_reset_cache()
+    def cfgimpl_reset_cache(self, only_expired=False, only=('values', 'settings')):
+        self.cfgimpl_get_context().cfgimpl_reset_cache(only_expired, only)
 
     def _setattr(self, name, value, force_permissive=False):
         if '.' in name:
@@ -84,7 +84,7 @@ class SubConfig(object):
             self.cfgimpl_get_values().setitem(child, value,
                                               force_permissive=force_permissive)
         else:
-            child.setoption(self.cfgimpl_get_context(), value)
+            child._setoption(self.cfgimpl_get_context(), value)
 
     def __delattr__(self, name):
         child = getattr(self._cfgimpl_descr, name)
@@ -114,11 +114,11 @@ class SubConfig(object):
         if name.startswith('_cfgimpl_') or name.startswith('cfgimpl_'):
             # if it were in __dict__ it would have been found already
             object.__getattr__(self, name)
-        opt_or_descr = getattr(self._cfgimpl_descr, name)
+        opt_or_descr = getattr(self.cfgimpl_get_description(), name)
         # symlink options
         if isinstance(opt_or_descr, SymLinkOption):
             rootconfig = self.cfgimpl_get_context()
-            path = rootconfig.cfgimpl_get_description().get_path_by_opt(opt_or_descr.opt)
+            path = rootconfig.cfgimpl_get_description().objimpl_get_path_by_opt(opt_or_descr.opt)
             return rootconfig._getattr(path, validate=validate,
                                        force_properties=force_properties,
                                        force_permissive=force_permissive)
@@ -127,12 +127,6 @@ class SubConfig(object):
                                                             True, False,
                                                             force_permissive=force_permissive,
                                                             force_properties=force_properties)
-            children = self.cfgimpl_get_description()._children
-            if opt_or_descr not in children[1]:
-                raise AttributeError(_("{0} with name {1} object has "
-                                     "no attribute {2}").format(self.__class__,
-                                                                opt_or_descr._name,
-                                                                name))
             return SubConfig(opt_or_descr, self._cfgimpl_context)
         else:
             return self.cfgimpl_get_values().getitem(opt_or_descr,
@@ -149,27 +143,27 @@ class SubConfig(object):
                                  force_properties=force_properties)
         return self, path[-1]
 
-    def getkey(self):
-        return self._cfgimpl_descr.getkey(self)
-
     def __hash__(self):
-        return hash(self.getkey())
+        return hash(self.cfgimpl_get_description().objimpl_getkey(self))
 
     def __eq__(self, other):
         "Config comparison"
         if not isinstance(other, Config):
             return False
-        return self.getkey() == other.getkey()
+        return self.cfgimpl_get_description().objimpl_getkey(self) == \
+            other.cfgimpl_get_description().objimpl_getkey(other)
 
     def __ne__(self, other):
         "Config comparison"
+        if not isinstance(other, Config):
+            return False
         return not self == other
 
     # ______________________________________________________________________
     def __iter__(self):
         """Pythonesque way of parsing group's ordered options.
         iteration only on Options (not OptionDescriptions)"""
-        for child in self._cfgimpl_descr._children[1]:
+        for child in self.cfgimpl_get_description().objimpl_getchildren():
             if not isinstance(child, OptionDescription):
                 try:
                     yield child._name, getattr(self, child._name)
@@ -181,7 +175,7 @@ class SubConfig(object):
     def iter_all(self):
         """A way of parsing options **and** groups.
         iteration on Options and OptionDescriptions."""
-        for child in self._cfgimpl_descr._children[1]:
+        for child in self.cfgimpl_get_description().objimpl_getchildren():
             try:
                 yield child._name, getattr(self, child._name)
             except GeneratorExit:
@@ -202,13 +196,11 @@ class SubConfig(object):
         if group_type is not None:
             if not isinstance(group_type, groups.GroupType):
                 raise TypeError(_("unknown group_type: {0}").format(group_type))
-        for child in self._cfgimpl_descr._children[1]:
+        for child in self.cfgimpl_get_description().objimpl_getchildren():
             if isinstance(child, OptionDescription):
                 try:
-                    if group_type is not None:
-                        if child.get_group_type() == group_type:
-                            yield child._name, getattr(self, child._name)
-                    else:
+                    if group_type is None or (group_type is not None and
+                                              child.objimpl_get_group_type() == group_type):
                         yield child._name, getattr(self, child._name)
                 except GeneratorExit:
                     raise StopIteration
@@ -230,31 +222,10 @@ class SubConfig(object):
 
     __repr__ = __str__
 
-    def getpaths(self, include_groups=False, allpaths=False):
-        """returns a list of all paths in self, recursively, taking care of
-        the context of properties (hidden/disabled)
-
-        :param include_groups: if true, OptionDescription are included
-        :param allpaths: all the options (event the properties protected ones)
-        :returns: list of all paths
-        """
-        paths = []
-        for path in self._cfgimpl_descr.getpaths(include_groups=include_groups):
-            if allpaths:
-                paths.append(path)
-            else:
-                try:
-                    getattr(self, path)
-                except PropertiesOptionError:
-                    pass
-                else:
-                    paths.append(path)
-        return paths
-
-    def getpath(self):
+    def cfgimpl_get_path(self):
         descr = self.cfgimpl_get_description()
         context_descr = self.cfgimpl_get_context().cfgimpl_get_description()
-        return context_descr.get_path_by_opt(descr)
+        return context_descr.objimpl_get_path_by_opt(descr)
 
     def find(self, bytype=None, byname=None, byvalue=None, type_='option'):
         """
@@ -268,7 +239,7 @@ class SubConfig(object):
         return self.cfgimpl_get_context()._find(bytype, byname, byvalue,
                                                 first=False,
                                                 type_=type_,
-                                                _subpath=self.getpath())
+                                                _subpath=self.cfgimpl_get_path())
 
     def find_first(self, bytype=None, byname=None, byvalue=None, type_='option'):
         """
@@ -282,7 +253,7 @@ class SubConfig(object):
         return self.cfgimpl_get_context()._find(bytype, byname, byvalue,
                                                 first=True,
                                                 type_=type_,
-                                                _subpath=self.getpath())
+                                                _subpath=self.cfgimpl_get_path())
 
     def make_dict(self, flatten=False, _currpath=None, withoption=None, withvalue=None):
         """export the whole config into a `dict`
@@ -293,7 +264,7 @@ class SubConfig(object):
         if withoption is None and withvalue is not None:
             raise ValueError(_("make_dict can't filtering with value without option"))
         if withoption is not None:
-            mypath = self.getpath()
+            mypath = self.cfgimpl_get_path()
             for path in self.cfgimpl_get_context()._find(bytype=Option,
                                                          byname=withoption,
                                                          byvalue=withvalue,
@@ -301,7 +272,7 @@ class SubConfig(object):
                                                          type_='path',
                                                          _subpath=mypath):
                 path = '.'.join(path.split('.')[:-1])
-                opt = self.cfgimpl_get_context().cfgimpl_get_description().get_opt_by_path(path)
+                opt = self.cfgimpl_get_context().cfgimpl_get_description().objimpl_get_opt_by_path(path)
                 if mypath is not None:
                     if mypath == path:
                         withoption = None
@@ -316,7 +287,7 @@ class SubConfig(object):
                 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().getchildren():
+            for opt in self.cfgimpl_get_description().objimpl_getchildren():
                 path = opt._name
                 self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten)
         if _currpath == []:
@@ -359,11 +330,13 @@ class Config(SubConfig):
         self._cfgimpl_build_all_paths()
 
     def _cfgimpl_build_all_paths(self):
-        self._cfgimpl_descr.build_cache()
+        self._cfgimpl_descr.objimpl_build_cache()
 
-    def cfgimpl_reset_cache(self, only_expired=False):
-        self.cfgimpl_get_values().reset_cache(only_expired=only_expired)
-        self.cfgimpl_get_settings().reset_cache(only_expired=only_expired)
+    def cfgimpl_reset_cache(self, only_expired=False, only=('values', 'settings')):
+        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)
 
     def unwrap_from_path(self, path):
         """convenience method to extract and Option() object from the Config()
@@ -377,38 +350,7 @@ class Config(SubConfig):
             return getattr(homeconfig._cfgimpl_descr, path)
         return getattr(self._cfgimpl_descr, path)
 
-    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.
-        """
-        #opts, paths = self.cfgimpl_get_description()._cache_paths
-        all_paths = [p.split(".") for p in self.getpaths(allpaths=True)]
-        for key, value in kwargs.iteritems():
-            key_p = key.split('.')
-            candidates = [p for p in all_paths if p[-len(key_p):] == key_p]
-            if len(candidates) == 1:
-                name = '.'.join(candidates[0])
-                homeconfig, name = self.cfgimpl_get_home_by_path(name)
-                getattr(homeconfig, name)
-                #except MandatoryError:
-                #    pass
-                #except PropertiesOptionError, e:
-                #    raise e  # HiddenOptionError or DisabledOptionError
-                child = getattr(homeconfig._cfgimpl_descr, name)
-                self.cfgimpl_get_values()[child] = value
-            elif len(candidates) > 1:
-                raise ConflictOptionError(
-                    _('more than one option that ends with {}').format(key))
-            else:
-                raise AttributeError(
-                    _('there is no option that matches {}'
-                      ' or the option is hidden or disabled').format(key))
-
-    def getpath(self):
+    def cfgimpl_get_path(self):
         return None
 
     def _find(self, bytype, byname, byvalue, first, type_='option',
@@ -502,11 +444,12 @@ def mandatory_warnings(config):
 
     :returns: generator of mandatory Option's path
     """
-    config.cfgimpl_reset_cache()
-    for path in config.cfgimpl_get_description().getpaths(include_groups=True):
+    #if value in cache, properties are not calculated
+    config.cfgimpl_reset_cache(only=('values',))
+    for path in config.cfgimpl_get_description().objimpl_getpaths(include_groups=True):
         try:
             config._getattr(path, force_properties=('mandatory',))
         except PropertiesOptionError, err:
             if err.proptype == ['mandatory']:
                 yield path
-    config.cfgimpl_reset_cache()
+    config.cfgimpl_reset_cache(only=('values',))