add test test/test_dereference.py + memoryleaks in optiondescription's cache
[tiramisu.git] / tiramisu / option.py
index 20135d2..8f598b9 100644 (file)
@@ -1,5 +1,5 @@
 # -*- coding: utf-8 -*-
-"option types and option description for the configuration management"
+"option types and option description"
 # Copyright (C) 2012-2013 Team tiramisu (see AUTHORS for all contributors)
 #
 # This program is free software; you can redistribute it and/or modify
@@ -59,24 +59,35 @@ class BaseInformation(object):
 
     def impl_set_information(self, key, value):
         """updates the information's attribute
-        (wich is a dictionnary)
+        (which is a dictionary)
 
         :param key: information's key (ex: "help", "doc"
         :param value: information's value (ex: "the help string")
         """
-        self._impl_informations[key] = value
+        try:
+            self._impl_informations[key] = value
+        except AttributeError:
+            raise AttributeError(_('{0} has no attribute '
+                                   'impl_set_information').format(
+                                   self.__class__.__name__))
 
     def impl_get_information(self, key, default=None):
         """retrieves one information's item
 
         :param key: the item string (ex: "help")
         """
-        if key in self._impl_informations:
-            return self._impl_informations[key]
-        elif default is not None:
-            return default
-        else:
-            raise ValueError(_("Information's item not found: {0}").format(key))
+        try:
+            if key in self._impl_informations:
+                return self._impl_informations[key]
+            elif default is not None:
+                return default
+            else:
+                raise ValueError(_("Information's item"
+                                   "not found: {0}").format(key))
+        except AttributeError:
+            raise AttributeError(_('{0} has no attribute '
+                                   'impl_get_information').format(
+                                   self.__class__.__name__))
 
 
 class Option(BaseInformation):
@@ -85,9 +96,10 @@ class Option(BaseInformation):
 
     Reminder: an Option object is **not** a container for the value
     """
-    __slots__ = ('_name', '_requires', '_multi', '_validator', '_default_multi',
-                 '_default', '_properties', '_callback', '_multitype',
-                 '_master_slaves', '_consistencies', '_empty')
+    __slots__ = ('_name', '_requires', '_multi', '_validator',
+                 '_default_multi', '_default', '_properties', '_callback',
+                 '_multitype', '_master_slaves', '_consistencies', '_empty',
+                 '_calc_properties', '__weakref__')
     _empty = ''
 
     def __init__(self, name, doc, default=None, default_multi=None,
@@ -117,8 +129,8 @@ class Option(BaseInformation):
         self._name = name
         self._impl_informations = {}
         self.impl_set_information('doc', doc)
-        validate_requires_arg(requires, self._name)
-        self._requires = requires
+        self._calc_properties, self._requires = validate_requires_arg(
+            requires, self._name)
         self._multi = multi
         self._consistencies = None
         if validator is not None:
@@ -132,15 +144,21 @@ class Option(BaseInformation):
         if not self._multi and default_multi is not None:
             raise ValueError(_("a default_multi is set whereas multi is False"
                              " in option: {0}").format(name))
-        if default_multi is not None and not self._validate(default_multi):
-            raise ValueError(_("invalid default_multi value {0} "
-                             "for option {1}").format(str(default_multi), name))
-        if callback is not None and (default is not None or default_multi is not None):
-            raise ValueError(_("defaut values not allowed if option: {0} "
+        if default_multi is not None:
+            try:
+                self._validate(default_multi)
+            except ValueError, err:
+                raise ValueError(_("invalid default_multi value {0} "
+                                   "for option {1}: {2}").format(
+                                   str(default_multi), name, err))
+        if callback is not None and (default is not None or
+                                     default_multi is not None):
+            raise ValueError(_("default value not allowed if option: {0} "
                              "is calculated").format(name))
         if callback is None and callback_params is not None:
             raise ValueError(_("params defined for a callback function but "
-                             "no callback defined yet for option {0}").format(name))
+                             "no callback defined"
+                             " yet for option {0}").format(name))
         if callback is not None:
             if type(callback) != FunctionType:
                 raise ValueError('callback must be a function')
@@ -161,14 +179,18 @@ class Option(BaseInformation):
             properties = tuple()
         if not isinstance(properties, tuple):
             raise TypeError(_('invalid properties type {0} for {1},'
-                            ' must be a tuple').format(type(properties), self._name))
-        self._properties = set(properties)  # 'hidden', 'disabled'...
+                            ' must be a tuple').format(
+                                                type(properties),
+                                                self._name))
+        self._properties = properties  # 'hidden', 'disabled'...
 
     def __eq__(self, other):
         "Option comparison"
         if not isinstance(other, Option):
             return False
-        slots = list(self.__slots__ + Option.__slots__ + BaseInformation.__slots__)
+        slots = list(self.__slots__ +
+                     Option.__slots__ +
+                     BaseInformation.__slots__)
         for var in slots:
             try:
                 val1 = getattr(self, var)
@@ -245,34 +267,38 @@ class Option(BaseInformation):
         if not validate:
             return
 
-        def _val_validator(val):
-            callback_params = deepcopy(self._validator[1])
-            callback_params.setdefault('', []).insert(0, val)
-            return carry_out_calculation(self._name, config=context,
-                                         callback=self._validator[0],
-                                         callback_params=callback_params)
-
-        def val_validator():
-            #add current value has first argument
-            if self.impl_is_multi():
-                for val in value:
-                    if not _val_validator(val):
-                        return False
-                return True
+        def val_validator(val):
+            if self._validator is not None:
+                callback_params = deepcopy(self._validator[1])
+                callback_params.setdefault('', []).insert(0, val)
+                return carry_out_calculation(self._name, config=context,
+                                             callback=self._validator[0],
+                                             callback_params=callback_params)
             else:
-                return _val_validator(value)
+                return True
+
+        def do_validation(_value, _index=None):
+            if _value is None:
+                return True
+            if not val_validator(_value):
+                raise ValueError(_("invalid value {0} "
+                                   "for option {1} for object {2}"
+                                   ).format(_value,
+                                            self._name,
+                                            self.__class__.__name__))
+            try:
+                self._validate(_value)
+            except ValueError, err:
+                raise ValueError(_("invalid value {0} for option {1}: {2}"
+                                   "").format(_value, self._name, err))
+            if context is not None:
+                descr._valid_consistency(self, _value, context, _index)
 
         # generic calculation
         if context is not None:
             descr = context.cfgimpl_get_description()
         if not self._multi:
-            if value is not None and ((self._validator is not None and
-                                       not val_validator()) or
-                                      not self._validate(value)):
-                raise ValueError(_("invalid value {0} for option {1}"
-                                   "").format(value, self._name))
-            if context is not None:
-                descr._valid_consistency(self, value, context, None)
+            do_validation(value)
         else:
             if not isinstance(value, list):
                 raise ValueError(_("invalid value {0} for option {1} "
@@ -280,13 +306,7 @@ class Option(BaseInformation):
                                                                   self._name))
             for index in range(0, len(value)):
                 val = value[index]
-                if val is not None and ((self._validator is not None and
-                                         not val_validator()) or
-                                        not self._validate(val)):
-                        raise ValueError(_("invalid value {0} for option {1}"
-                                           "").format(value, self._name))
-                if context is not None:
-                    descr._valid_consistency(self, val, context, index)
+                do_validation(val, index)
 
     def impl_getdefault(self, default_multi=False):
         "accessing the default value"
@@ -308,7 +328,8 @@ class Option(BaseInformation):
     def impl_is_empty_by_default(self):
         "no default value has been set yet"
         if ((not self.impl_is_multi() and self._default is None) or
-                (self.impl_is_multi() and (self._default == [] or None in self._default))):
+                (self.impl_is_multi() and (self._default == []
+                                      or None in self._default))):
             return True
         return False
 
@@ -337,9 +358,13 @@ class Option(BaseInformation):
         if self is opt:
             raise ValueError('cannot add consistency with itself')
         if self.impl_is_multi() != opt.impl_is_multi():
-            raise ValueError('options in consistency should be multi in two sides')
-        func = '_cons_{}'.format(func)
-        self._launch_consistency(func, self, self.impl_getdefault(), None, None, opt)
+            raise ValueError('options in consistency'
+                             ' should be multi in two sides')
+        func = '_cons_{0}'.format(func)
+        self._launch_consistency(func,
+                                 self,
+                                 self.impl_getdefault(),
+                                 None, None, opt)
         self._consistencies.append((func, opt))
         self.impl_validate(self.impl_getdefault())
 
@@ -390,10 +415,10 @@ class ChoiceOption(Option):
         return self._open_values
 
     def _validate(self, value):
-        if not self._open_values:
-            return value is None or value in self._values
-        else:
-            return True
+        if not self._open_values and not value in self._values:
+            raise ValueError(_('value {0} is not permitted, '
+                               'only {1} is allowed'
+                               '').format(value, self._values))
 
 
 class BoolOption(Option):
@@ -402,7 +427,8 @@ class BoolOption(Option):
     _opt_type = 'bool'
 
     def _validate(self, value):
-        return isinstance(value, bool)
+        if not isinstance(value, bool):
+            raise ValueError(_('value must be a boolean'))
 
 
 class IntOption(Option):
@@ -411,7 +437,8 @@ class IntOption(Option):
     _opt_type = 'int'
 
     def _validate(self, value):
-        return isinstance(value, int)
+        if not isinstance(value, int):
+            raise ValueError(_('value must be an integer'))
 
 
 class FloatOption(Option):
@@ -420,7 +447,8 @@ class FloatOption(Option):
     _opt_type = 'float'
 
     def _validate(self, value):
-        return isinstance(value, float)
+        if not isinstance(value, float):
+            raise ValueError(_('value must be a float'))
 
 
 class StrOption(Option):
@@ -429,7 +457,9 @@ class StrOption(Option):
     _opt_type = 'string'
 
     def _validate(self, value):
-        return isinstance(value, str)
+        if not isinstance(value, str):
+            raise ValueError(_('value must be a string, not '
+                               '{0}').format(type(value)))
 
 
 class UnicodeOption(Option):
@@ -439,7 +469,8 @@ class UnicodeOption(Option):
     _empty = u''
 
     def _validate(self, value):
-        return isinstance(value, unicode)
+        if not isinstance(value, unicode):
+            raise ValueError(_('value must be an unicode'))
 
 
 class SymLinkOption(object):
@@ -451,12 +482,13 @@ class SymLinkOption(object):
         self._name = name
         if not isinstance(opt, Option):
             raise ValueError(_('malformed symlinkoption '
-                               'must be an option for symlink {0}').format(name))
+                               'must be an option '
+                               'for symlink {0}').format(name))
         self._opt = opt
 
     def __getattr__(self, name):
         if name in ('_name', '_opt', '_consistencies'):
-            return object.__gettattr__(self, name)
+            return object.__getattr__(self, name)
         else:
             return getattr(self._opt, name)
 
@@ -470,6 +502,7 @@ class IPOption(Option):
                  requires=None, multi=False, callback=None,
                  callback_params=None, validator=None, validator_args=None,
                  properties=None, only_private=False):
+        self._only_private = only_private
         super(IPOption, self).__init__(name, doc, default=default,
                                        default_multi=default_multi,
                                        callback=callback,
@@ -479,16 +512,83 @@ class IPOption(Option):
                                        validator=validator,
                                        validator_args=validator_args,
                                        properties=properties)
-        self._only_private = only_private
 
     def _validate(self, value):
-        try:
-            ip = IP('{0}/32'.format(value))
-            if self._only_private:
-                return ip.iptype() == 'PRIVATE'
-            return True
-        except ValueError:
-            return False
+        ip = IP('{0}/32'.format(value))
+        if ip.iptype() == 'RESERVED':
+            raise ValueError(_("IP mustn't not be in reserved class"))
+        if self._only_private and not ip.iptype() == 'PRIVATE':
+            raise ValueError(_("IP must be in private class"))
+
+
+class PortOption(Option):
+    """represents the choice of a port
+    The port numbers are divided into three ranges:
+    the well-known ports,
+    the registered ports,
+    and the dynamic or private ports.
+    You can actived this three range.
+    Port number 0 is reserved and can't be used.
+    see: http://en.wikipedia.org/wiki/Port_numbers
+    """
+    __slots__ = ('_opt_type', '_allow_range', '_allow_zero', '_min_value',
+                 '_max_value')
+    _opt_type = 'port'
+
+    def __init__(self, name, doc, default=None, default_multi=None,
+                 requires=None, multi=False, callback=None,
+                 callback_params=None, validator=None, validator_args=None,
+                 properties=None, allow_range=False, allow_zero=False,
+                 allow_wellknown=True, allow_registred=True,
+                 allow_private=False):
+        self._allow_range = allow_range
+        self._min_value = None
+        self._max_value = None
+        ports_min = [0, 1, 1024, 49152]
+        ports_max = [0, 1023, 49151, 65535]
+        is_finally = False
+        for index, allowed in enumerate([allow_zero,
+                                         allow_wellknown,
+                                         allow_registred,
+                                         allow_private]):
+            if self._min_value is None:
+                if allowed:
+                    self._min_value = ports_min[index]
+            elif not allowed:
+                is_finally = True
+            elif allowed and is_finally:
+                raise ValueError(_('inconsistency in allowed range'))
+            if allowed:
+                self._max_value = ports_max[index]
+
+        if self._max_value is None:
+            raise ValueError(_('max value is empty'))
+
+        super(PortOption, self).__init__(name, doc, default=default,
+                                         default_multi=default_multi,
+                                         callback=callback,
+                                         callback_params=callback_params,
+                                         requires=requires,
+                                         multi=multi,
+                                         validator=validator,
+                                         validator_args=validator_args,
+                                         properties=properties)
+
+    def _validate(self, value):
+        if self._allow_range and ":" in str(value):
+            value = str(value).split(':')
+            if len(value) != 2:
+                raise ValueError('range must have two values only')
+            if not value[0] < value[1]:
+                raise ValueError('first port in range must be'
+                                 ' smaller than the second one')
+        else:
+            value = [value]
+
+        for val in value:
+            if not self._min_value <= int(val) <= self._max_value:
+                raise ValueError('port must be an between {0} and {1}'
+                                 ''.format(self._min_value, self._max_value))
 
 
 class NetworkOption(Option):
@@ -497,11 +597,9 @@ class NetworkOption(Option):
     _opt_type = 'network'
 
     def _validate(self, value):
-        try:
-            IP(value)
-            return True
-        except ValueError:
-            return False
+        ip = IP(value)
+        if ip.iptype() == 'RESERVED':
+            raise ValueError(_("network mustn't not be in reserved class"))
 
 
 class NetmaskOption(Option):
@@ -510,11 +608,7 @@ class NetmaskOption(Option):
     _opt_type = 'netmask'
 
     def _validate(self, value):
-        try:
-            IP('0.0.0.0/{}'.format(value))
-            return True
-        except ValueError:
-            return False
+        IP('0.0.0.0/{0}'.format(value))
 
     def _cons_network_netmask(self, optname, value, value_):
         #opts must be (netmask, network) options
@@ -537,16 +631,17 @@ class NetmaskOption(Option):
                         make_net=not make_net)
                 except ValueError:
                     if not make_net:
-                        msg = _("invalid network {0} ({1}) with netmask {2} ({3}),"
-                                " this network is an ip")
+                        msg = _("invalid network {0} ({1}) "
+                                "with netmask {2} ({3}),"
+                                " this network is an IP")
                 else:
                     if make_net:
-                        msg = _("invalid ip {0} ({1}) with netmask {2} ({3}),"
-                                " this ip is a network")
+                        msg = _("invalid IP {0} ({1}) with netmask {2} ({3}),"
+                                " this IP is a network")
 
         except ValueError:
             if make_net:
-                msg = _("invalid ip {0} ({1}) with netmask {2} ({3})")
+                msg = _("invalid IP {0} ({1}) with netmask {2} ({3})")
             else:
                 msg = _("invalid network {0} ({1}) with netmask {2} ({3})")
         if msg is not None:
@@ -587,7 +682,7 @@ class DomainnameOption(Option):
         if self._allow_ip is True:
             try:
                 IP('{0}/32'.format(value))
-                return True
+                return
             except ValueError:
                 pass
         if self._type == 'netbios':
@@ -603,10 +698,14 @@ class DomainnameOption(Option):
                 raise ValueError(_("invalid value for {0}, must have dot"
                                    "").format(self._name))
         if len(value) > length:
-            raise ValueError(_("invalid value's length for {0} (max {1})"
-                               "").format(self._name, length))
+            raise ValueError(_("invalid domainname's length for "
+                               " {0} (max {1})").format(self._name, length))
+        if len(value) == 1:
+            raise ValueError(_("invalid domainname's length for {0} (min 2)"
+                               "").format(self._name))
         regexp = r'^[a-z]([a-z\d{0}-])*[a-z\d]$'.format(extrachar)
-        return re.match(regexp, value) is not None
+        if re.match(regexp, value) is None:
+            raise ValueError(_('invalid domainname'))
 
 
 class OptionDescription(BaseInformation):
@@ -614,15 +713,17 @@ class OptionDescription(BaseInformation):
     The `OptionsDescription` objects lives in the `tiramisu.config.Config`.
     """
     __slots__ = ('_name', '_requires', '_cache_paths', '_group_type',
-                 '_properties', '_children', '_consistencies')
+                 '_properties', '_children', '_consistencies',
+                 '_calc_properties', '__weakref__')
 
     def __init__(self, name, doc, children, requires=None, properties=None):
         """
-        :param children: a list of options (including option descriptions)
+        :param children: a list of options (including optiondescriptions)
 
         """
         if not valid_name(name):
-            raise ValueError(_("invalid name: {0} for option descr").format(name))
+            raise ValueError(_("invalid name: "
+                               " {0} for optiondescription").format(name))
         self._name = name
         self._impl_informations = {}
         self.impl_set_information('doc', doc)
@@ -637,16 +738,16 @@ class OptionDescription(BaseInformation):
                                       '{0}').format(child))
             old = child
         self._children = (tuple(child_names), tuple(children))
-        validate_requires_arg(requires, self._name)
-        self._requires = requires
+        self._calc_properties, self._requires = validate_requires_arg(requires, self._name)
         self._cache_paths = None
         self._consistencies = None
         if properties is None:
             properties = tuple()
         if not isinstance(properties, tuple):
             raise TypeError(_('invalid properties type {0} for {1},'
-                              ' must be a tuple').format(type(properties), self._name))
-        self._properties = set(properties)  # 'hidden', 'disabled'...
+                              ' must be a tuple').format(type(properties),
+                                                         self._name))
+        self._properties = properties  # 'hidden', 'disabled'...
         # the group_type is useful for filtering OptionDescriptions in a config
         self._group_type = groups.default
 
@@ -657,8 +758,9 @@ class OptionDescription(BaseInformation):
         try:
             return self._children[1][self._children[0].index(name)]
         except ValueError:
-            raise AttributeError(_('unknown Option {} in OptionDescription {}'
-                                 '').format(name, self._name))
+            raise AttributeError(_('unknown Option {0} '
+                                   'in OptionDescription {1}'
+                                   '').format(name, self._name))
 
     def impl_getkey(self, config):
         return tuple([child.impl_getkey(getattr(config, child._name))
@@ -685,7 +787,11 @@ class OptionDescription(BaseInformation):
     def impl_getchildren(self):
         return self._children[1]
 
-    def impl_build_cache(self, cache_path=None, cache_option=None, _currpath=None, _consistencies=None):
+    def impl_build_cache(self,
+                         cache_path=None,
+                         cache_option=None,
+                         _currpath=None,
+                         _consistencies=None):
         if _currpath is None and self._cache_paths is not None:
             return
         if _currpath is None:
@@ -695,8 +801,8 @@ class OptionDescription(BaseInformation):
         else:
             save = False
         if cache_path is None:
-            cache_path = [self._name]
-            cache_option = [self]
+            cache_path = []
+            cache_option = []
         for option in self.impl_getchildren():
             attr = option._name
             if attr.startswith('_cfgimpl'):
@@ -708,11 +814,16 @@ class OptionDescription(BaseInformation):
                     for consistency in option._consistencies:
                         func, opt = consistency
                         opts = (option, opt)
-                        _consistencies.setdefault(opt, []).append((func, opts))
-                        _consistencies.setdefault(option, []).append((func, opts))
+                        _consistencies.setdefault(opt,
+                                                  []).append((func, opts))
+                        _consistencies.setdefault(option,
+                                                  []).append((func, opts))
             else:
                 _currpath.append(attr)
-                option.impl_build_cache(cache_path, cache_option, _currpath, _consistencies)
+                option.impl_build_cache(cache_path,
+                                        cache_option,
+                                        _currpath,
+                                        _consistencies)
                 _currpath.pop()
         if save:
             #valid no duplicated option
@@ -731,13 +842,13 @@ class OptionDescription(BaseInformation):
         try:
             return self._cache_paths[0][self._cache_paths[1].index(path)]
         except ValueError:
-            raise AttributeError(_('no option for path {}').format(path))
+            raise AttributeError(_('no option for path {0}').format(path))
 
     def impl_get_path_by_opt(self, opt):
         try:
             return self._cache_paths[1][self._cache_paths[0].index(opt)]
         except ValueError:
-            raise AttributeError(_('no option {} found').format(opt))
+            raise AttributeError(_('no option {0} found').format(opt))
 
     # ____________________________________________________________
     def impl_set_group_type(self, group_type):
@@ -748,7 +859,8 @@ class OptionDescription(BaseInformation):
         """
         if self._group_type != groups.default:
             raise TypeError(_('cannot change group_type if already set '
-                            '(old {}, new {})').format(self._group_type, group_type))
+                            '(old {0}, new {1})').format(self._group_type,
+                                                         group_type))
         if isinstance(group_type, groups.GroupType):
             self._group_type = group_type
             if isinstance(group_type, groups.MasterGroupType):
@@ -759,10 +871,14 @@ class OptionDescription(BaseInformation):
                 master = None
                 for child in self.impl_getchildren():
                     if isinstance(child, OptionDescription):
-                        raise ValueError(_("master group {} shall not have "
+                        raise ValueError(_("master group {0} shall not have "
                                          "a subgroup").format(self._name))
+                    if isinstance(child, SymLinkOption):
+                        raise ValueError(_("master group {0} shall not have "
+                                         "a symlinkoption").format(self._name))
                     if not child.impl_is_multi():
-                        raise ValueError(_("not allowed option {0} in group {1}"
+                        raise ValueError(_("not allowed option {0} "
+                                         "in group {1}"
                                          ": this option is not a multi"
                                          "").format(child._name, self._name))
                     if child._name == self._name:
@@ -772,18 +888,20 @@ class OptionDescription(BaseInformation):
                     else:
                         slaves.append(child)
                 if master is None:
-                    raise ValueError(_('master group with wrong master name for {}'
-                                     '').format(self._name))
+                    raise ValueError(_('master group with wrong'
+                                       ' master name for {0}'
+                                       ).format(self._name))
                 master._master_slaves = tuple(slaves)
                 for child in self.impl_getchildren():
                     if child != master:
                         child._master_slaves = master
                         child._multitype = multitypes.slave
                 if not identical_master_child_name:
-                    raise ValueError(_("the master group: {} has not any "
-                                     "master child").format(self._name))
+                    raise ValueError(_("no child has same nom has master group"
+                                       " for: {0}").format(self._name))
         else:
-            raise ValueError(_('not allowed group_type : {0}').format(group_type))
+            raise ValueError(_('group_type : {0}'
+                               ' not allowed').format(group_type))
 
     def impl_get_group_type(self):
         return self._group_type
@@ -793,42 +911,102 @@ class OptionDescription(BaseInformation):
         if consistencies is not None:
             for consistency in consistencies:
                 opt_ = consistency[1]
-                ret = opt_[0]._launch_consistency(consistency[0], opt, value, context,
-                                                  index, opt_[1])
+                ret = opt_[0]._launch_consistency(consistency[0],
+                                                  opt,
+                                                  value,
+                                                  context,
+                                                  index,
+                                                  opt_[1])
                 if ret is False:
                     return False
         return True
 
 
 def validate_requires_arg(requires, name):
-    "check malformed requirements"
-    if requires is not None:
-        config_action = {}
-        for req in requires:
-            if not type(req) == tuple:
-                raise ValueError(_("malformed requirements type for option:"
-                                   " {0}, must be a tuple").format(name))
-            if not isinstance(req[0], Option):
-                raise ValueError(_('malformed requirements first argument '
-                                   'must be an option in option {0}').format(name))
-            if req[0].impl_is_multi():
-                raise ValueError(_('malformed requirements option {0} '
-                                   'should not be a multi').format(name))
-            if not req[0]._validate(req[1]):
+    """check malformed requirements
+    and tranform dict to internal tuple
+
+    :param requires: have a look at the
+                     :meth:`tiramisu.setting.Settings.apply_requires` method to
+                     know more about
+                     the description of the requires dictionary
+    """
+    if requires is None:
+        return None, None
+    ret_requires = {}
+    config_action = {}
+
+    for require in requires:
+        if not type(require) == dict:
+            raise ValueError(_("malformed requirements type for option:"
+                               " {0}, must be a dict").format(name))
+        valid_keys = ('option', 'expected', 'action', 'inverse', 'transitive',
+                      'same_action')
+        unknown_keys = frozenset(require.keys()) - frozenset(valid_keys)
+        if unknown_keys != frozenset():
+            raise ValueError('malformed requirements for option: {0}'
+                             ' unknown keys {1}, must only '
+                             '{2}'.format(name,
+                                          unknown_keys,
+                                          valid_keys))
+        try:
+            option = require['option']
+            expected = require['expected']
+            action = require['action']
+        except KeyError:
+            raise ValueError(_("malformed requirements for option: {0}"
+                               " require must have option, expected and"
+                               " action keys").format(name))
+        inverse = require.get('inverse', False)
+        if inverse not in [True, False]:
+            raise ValueError(_('malformed requirements for option: {0}'
+                               ' inverse must be boolean'))
+        transitive = require.get('transitive', True)
+        if transitive not in [True, False]:
+            raise ValueError(_('malformed requirements for option: {0}'
+                               ' transitive must be boolean'))
+        same_action = require.get('same_action', True)
+        if same_action not in [True, False]:
+            raise ValueError(_('malformed requirements for option: {0}'
+                               ' same_action must be boolean'))
+
+        if not isinstance(option, Option):
+            print option, type(option)
+            raise ValueError(_('malformed requirements '
+                               'must be an option in option {0}').format(name))
+        if option.impl_is_multi():
+            raise ValueError(_('malformed requirements option {0} '
+                               'should not be a multi').format(name))
+        if expected is not None:
+            try:
+                option._validate(expected)
+            except ValueError, err:
                 raise ValueError(_('malformed requirements second argument '
-                                   'must be valid for option {0}').format(name))
-            if len(req) == 3:
-                action = req[2]
-                inverse = False
-            elif len(req) in [4, 5]:
-                action = req[2]
-                inverse = req[3]
-            else:
-                raise ValueError(_("malformed requirements for option: {0}"
-                                 " invalid len").format(name))
-            if action in config_action:
-                if inverse != config_action[action]:
-                    raise ValueError(_("inconsistency in action types for option: {0}"
-                                     " action: {1}").format(name, action))
-            else:
-                config_action[action] = inverse
+                                   'must be valid for option {0}'
+                                   ': {1}').format(name, err))
+        if action in config_action:
+            if inverse != config_action[action]:
+                raise ValueError(_("inconsistency in action types"
+                                   " for option: {0}"
+                                   " action: {1}").format(name, action))
+        else:
+            config_action[action] = inverse
+        if action not in ret_requires:
+            ret_requires[action] = {}
+        if option not in ret_requires[action]:
+            ret_requires[action][option] = (option, [expected], action,
+                                            inverse, transitive, same_action)
+        else:
+            ret_requires[action][option][1].append(expected)
+    ret = []
+    for opt_requires in ret_requires.values():
+        ret_action = []
+        for require in opt_requires.values():
+            req = (require[0], tuple(require[1]),
+                                     require[2],
+                                     require[3],
+                                     require[4],
+                                     require[5])
+            ret_action.append(req)
+        ret.append(tuple(ret_action))
+    return frozenset(config_action.keys()), tuple(ret)