2019-02-26 19:22:33 +01:00
|
|
|
import difflib
|
|
|
|
import itertools
|
|
|
|
|
|
|
|
import voluptuous as vol
|
2022-06-17 03:46:20 +02:00
|
|
|
from esphome.schema_extractors import schema_extractor_extended
|
2019-02-26 19:22:33 +01:00
|
|
|
|
|
|
|
|
|
|
|
class ExtraKeysInvalid(vol.Invalid):
|
|
|
|
def __init__(self, *arg, **kwargs):
|
2021-03-07 20:03:16 +01:00
|
|
|
self.candidates = kwargs.pop("candidates")
|
2019-02-26 19:22:33 +01:00
|
|
|
vol.Invalid.__init__(self, *arg, **kwargs)
|
|
|
|
|
|
|
|
|
2019-04-22 21:56:30 +02:00
|
|
|
def ensure_multiple_invalid(err):
|
|
|
|
if isinstance(err, vol.MultipleInvalid):
|
|
|
|
return err
|
|
|
|
return vol.MultipleInvalid(err)
|
|
|
|
|
|
|
|
|
2019-02-26 19:22:33 +01:00
|
|
|
# pylint: disable=protected-access, unidiomatic-typecheck
|
|
|
|
class _Schema(vol.Schema):
|
|
|
|
"""Custom cv.Schema that prints similar keys on error."""
|
2021-03-07 20:03:16 +01:00
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self, schema, required=False, extra=vol.PREVENT_EXTRA, extra_schemas=None
|
|
|
|
):
|
2019-12-07 18:28:55 +01:00
|
|
|
super().__init__(schema, required=required, extra=extra)
|
2019-04-22 21:56:30 +02:00
|
|
|
# List of extra schemas to apply after validation
|
|
|
|
# Should be used sparingly, as it's not a very voluptuous-way/clean way of
|
|
|
|
# doing things.
|
|
|
|
self._extra_schemas = extra_schemas or []
|
|
|
|
|
|
|
|
def __call__(self, data):
|
2019-12-07 18:28:55 +01:00
|
|
|
res = super().__call__(data)
|
2019-04-22 21:56:30 +02:00
|
|
|
for extra in self._extra_schemas:
|
|
|
|
try:
|
|
|
|
res = extra(res)
|
|
|
|
except vol.Invalid as err:
|
2020-09-16 12:12:40 +02:00
|
|
|
# pylint: disable=raise-missing-from
|
2019-04-22 21:56:30 +02:00
|
|
|
raise ensure_multiple_invalid(err)
|
|
|
|
return res
|
|
|
|
|
2019-02-26 19:22:33 +01:00
|
|
|
def _compile_mapping(self, schema, invalid_msg=None):
|
2021-03-07 20:03:16 +01:00
|
|
|
invalid_msg = invalid_msg or "mapping value"
|
2019-02-26 19:22:33 +01:00
|
|
|
|
2019-04-22 21:56:30 +02:00
|
|
|
# Check some things that ESPHome's schemas do not allow
|
|
|
|
# mostly to keep the logic in this method sane (so these may be re-added if needed).
|
|
|
|
for key in schema:
|
|
|
|
if key is vol.Extra:
|
|
|
|
raise ValueError("ESPHome does not allow vol.Extra")
|
|
|
|
if isinstance(key, vol.Remove):
|
|
|
|
raise ValueError("ESPHome does not allow vol.Remove")
|
|
|
|
if isinstance(key, vol.primitive_types):
|
2021-03-07 20:03:16 +01:00
|
|
|
raise ValueError(
|
|
|
|
"All schema keys must be wrapped in cv.Required or cv.Optional"
|
|
|
|
)
|
2019-04-22 21:56:30 +02:00
|
|
|
|
2019-02-26 19:22:33 +01:00
|
|
|
# Keys that may be required
|
2019-12-07 18:28:55 +01:00
|
|
|
all_required_keys = {key for key in schema if isinstance(key, vol.Required)}
|
2019-02-26 19:22:33 +01:00
|
|
|
|
|
|
|
# Keys that may have defaults
|
2020-07-25 14:21:56 +02:00
|
|
|
# This is a list because sets do not guarantee insertion order
|
|
|
|
all_default_keys = [key for key in schema if isinstance(key, vol.Optional)]
|
2019-02-26 19:22:33 +01:00
|
|
|
|
2019-04-22 21:56:30 +02:00
|
|
|
# Recursively compile schema
|
2019-02-26 19:22:33 +01:00
|
|
|
_compiled_schema = {}
|
|
|
|
for skey, svalue in vol.iteritems(schema):
|
|
|
|
new_key = self._compile(skey)
|
|
|
|
new_value = self._compile(svalue)
|
|
|
|
_compiled_schema[skey] = (new_key, new_value)
|
|
|
|
|
2019-04-22 21:56:30 +02:00
|
|
|
# Sort compiled schema (probably not necessary for esphome, but leave it here just in case)
|
2021-03-07 20:03:16 +01:00
|
|
|
candidates = list(
|
|
|
|
vol.schema_builder._iterate_mapping_candidates(_compiled_schema)
|
|
|
|
)
|
2019-02-26 19:22:33 +01:00
|
|
|
|
|
|
|
# After we have the list of candidates in the correct order, we want to apply some
|
|
|
|
# optimization so that each
|
|
|
|
# key in the data being validated will be matched against the relevant schema keys only.
|
|
|
|
# No point in matching against different keys
|
|
|
|
additional_candidates = []
|
|
|
|
candidates_by_key = {}
|
|
|
|
for skey, (ckey, cvalue) in candidates:
|
|
|
|
if type(skey) in vol.primitive_types:
|
|
|
|
candidates_by_key.setdefault(skey, []).append((skey, (ckey, cvalue)))
|
2021-03-07 20:03:16 +01:00
|
|
|
elif (
|
|
|
|
isinstance(skey, vol.Marker)
|
|
|
|
and type(skey.schema) in vol.primitive_types
|
|
|
|
):
|
|
|
|
candidates_by_key.setdefault(skey.schema, []).append(
|
|
|
|
(skey, (ckey, cvalue))
|
|
|
|
)
|
2019-02-26 19:22:33 +01:00
|
|
|
else:
|
|
|
|
# These are wildcards such as 'int', 'str', 'Remove' and others which should be
|
|
|
|
# applied to all keys
|
|
|
|
additional_candidates.append((skey, (ckey, cvalue)))
|
|
|
|
|
|
|
|
key_names = []
|
|
|
|
for skey in schema:
|
2019-12-07 18:28:55 +01:00
|
|
|
if isinstance(skey, str):
|
2019-02-26 19:22:33 +01:00
|
|
|
key_names.append(skey)
|
2019-12-07 18:28:55 +01:00
|
|
|
elif isinstance(skey, vol.Marker) and isinstance(skey.schema, str):
|
2019-02-26 19:22:33 +01:00
|
|
|
key_names.append(skey.schema)
|
|
|
|
|
|
|
|
def validate_mapping(path, iterable, out):
|
|
|
|
required_keys = all_required_keys.copy()
|
|
|
|
|
|
|
|
# Build a map of all provided key-value pairs.
|
|
|
|
# The type(out) is used to retain ordering in case a ordered
|
|
|
|
# map type is provided as input.
|
|
|
|
key_value_map = type(out)()
|
|
|
|
for key, value in iterable:
|
|
|
|
key_value_map[key] = value
|
|
|
|
|
|
|
|
# Insert default values for non-existing keys.
|
|
|
|
for key in all_default_keys:
|
2021-03-07 20:03:16 +01:00
|
|
|
if (
|
|
|
|
not isinstance(key.default, vol.Undefined)
|
|
|
|
and key.schema not in key_value_map
|
|
|
|
):
|
2019-04-22 21:56:30 +02:00
|
|
|
# A default value has been specified for this missing key, insert it.
|
2019-02-26 19:22:33 +01:00
|
|
|
key_value_map[key.schema] = key.default()
|
|
|
|
|
|
|
|
error = None
|
|
|
|
errors = []
|
|
|
|
for key, value in key_value_map.items():
|
|
|
|
key_path = path + [key]
|
|
|
|
# Optimization. Validate against the matching key first, then fallback to the rest
|
2021-03-07 20:03:16 +01:00
|
|
|
relevant_candidates = itertools.chain(
|
|
|
|
candidates_by_key.get(key, []), additional_candidates
|
|
|
|
)
|
2019-02-26 19:22:33 +01:00
|
|
|
|
|
|
|
# compare each given key/value against all compiled key/values
|
|
|
|
# schema key, (compiled key, compiled value)
|
|
|
|
for skey, (ckey, cvalue) in relevant_candidates:
|
|
|
|
try:
|
|
|
|
new_key = ckey(key_path, key)
|
|
|
|
except vol.Invalid as e:
|
|
|
|
if len(e.path) > len(key_path):
|
|
|
|
raise
|
|
|
|
if not error or len(e.path) > len(error.path):
|
|
|
|
error = e
|
|
|
|
continue
|
|
|
|
# Backtracking is not performed once a key is selected, so if
|
|
|
|
# the value is invalid we immediately throw an exception.
|
|
|
|
exception_errors = []
|
|
|
|
try:
|
|
|
|
cval = cvalue(key_path, value)
|
2019-04-22 21:56:30 +02:00
|
|
|
out[new_key] = cval
|
2019-02-26 19:22:33 +01:00
|
|
|
except vol.MultipleInvalid as e:
|
|
|
|
exception_errors.extend(e.errors)
|
|
|
|
except vol.Invalid as e:
|
|
|
|
exception_errors.append(e)
|
|
|
|
|
|
|
|
if exception_errors:
|
|
|
|
for err in exception_errors:
|
|
|
|
if len(err.path) <= len(key_path):
|
|
|
|
err.error_type = invalid_msg
|
|
|
|
errors.append(err)
|
|
|
|
# If there is a validation error for a required
|
|
|
|
# key, this means that the key was provided.
|
|
|
|
# Discard the required key so it does not
|
|
|
|
# create an additional, noisy exception.
|
|
|
|
required_keys.discard(skey)
|
|
|
|
break
|
|
|
|
|
|
|
|
# Key and value okay, mark as found in case it was
|
|
|
|
# a Required() field.
|
|
|
|
required_keys.discard(skey)
|
|
|
|
|
|
|
|
break
|
|
|
|
else:
|
2019-04-22 21:56:30 +02:00
|
|
|
if self.extra == vol.ALLOW_EXTRA:
|
2019-02-26 19:22:33 +01:00
|
|
|
out[key] = value
|
|
|
|
elif self.extra != vol.REMOVE_EXTRA:
|
2019-12-07 18:28:55 +01:00
|
|
|
if isinstance(key, str) and key_names:
|
2019-02-26 19:22:33 +01:00
|
|
|
matches = difflib.get_close_matches(key, key_names)
|
2021-03-07 20:03:16 +01:00
|
|
|
errors.append(
|
|
|
|
ExtraKeysInvalid(
|
|
|
|
"extra keys not allowed",
|
|
|
|
key_path,
|
|
|
|
candidates=matches,
|
|
|
|
)
|
|
|
|
)
|
2019-02-26 19:22:33 +01:00
|
|
|
else:
|
2021-03-07 20:03:16 +01:00
|
|
|
errors.append(
|
|
|
|
vol.Invalid("extra keys not allowed", key_path)
|
|
|
|
)
|
2019-02-26 19:22:33 +01:00
|
|
|
|
|
|
|
# for any required keys left that weren't found and don't have defaults:
|
|
|
|
for key in required_keys:
|
2021-03-07 20:03:16 +01:00
|
|
|
msg = getattr(key, "msg", None) or "required key not provided"
|
2019-02-26 19:22:33 +01:00
|
|
|
errors.append(vol.RequiredFieldInvalid(msg, path + [key]))
|
|
|
|
if errors:
|
|
|
|
raise vol.MultipleInvalid(errors)
|
|
|
|
|
|
|
|
return out
|
|
|
|
|
|
|
|
return validate_mapping
|
2019-03-17 16:04:49 +01:00
|
|
|
|
2019-04-22 21:56:30 +02:00
|
|
|
def add_extra(self, validator):
|
|
|
|
validator = _Schema(validator)
|
|
|
|
self._extra_schemas.append(validator)
|
|
|
|
return self
|
|
|
|
|
2022-06-17 03:46:20 +02:00
|
|
|
@schema_extractor_extended
|
2019-04-22 21:56:30 +02:00
|
|
|
def extend(self, *schemas, **kwargs):
|
2021-03-07 20:03:16 +01:00
|
|
|
extra = kwargs.pop("extra", None)
|
2019-04-22 21:56:30 +02:00
|
|
|
if kwargs:
|
|
|
|
raise ValueError
|
|
|
|
if not schemas:
|
|
|
|
return self.extend({})
|
|
|
|
if len(schemas) != 1:
|
|
|
|
ret = self
|
|
|
|
for schema in schemas:
|
|
|
|
ret = ret.extend(schema)
|
|
|
|
return ret
|
|
|
|
|
|
|
|
schema = schemas[0]
|
2019-04-17 12:06:00 +02:00
|
|
|
if isinstance(schema, vol.Schema):
|
|
|
|
schema = schema.schema
|
2019-12-07 18:28:55 +01:00
|
|
|
ret = super().extend(schema, extra=extra)
|
2019-04-22 21:56:30 +02:00
|
|
|
return _Schema(ret.schema, extra=ret.extra, extra_schemas=self._extra_schemas)
|