Validate configuration and produce human readable error messages.
Installation
pip install cfgv
Sample error messages
These are easier to see by example. Here's an example where I typo'd true
in a pre-commit configuration.
pre_commit.clientlib.InvalidConfigError:
==> File /home/asottile/workspace/pre-commit/.pre-commit-config.yaml
==> At Config()
==> At key: repos
==> At Repository(repo='https://github.com/pre-commit/pre-commit-hooks')
==> At key: hooks
==> At Hook(id='flake8')
==> At key: always_run
=====> Expected bool got str
API
cfgv.validate(value, schema)
Perform validation on the schema:
raises ValidationError on failure
returns the value on success (for convenience)
cfgv.apply_defaults(value, schema)
Returns a new value which sets all missing optional values to their defaults.
cfgv.remove_defaults(value, schema)
Returns a new value which removes all optional values that are set to their
defaults.
A schema validates a container -- cfgv provides Map and Array for
most normal cases.
writing your own schema container
If the built-in containers below don't quite satisfy your usecase, you can
always write your own. Containers use the following interface:
class Container(object):
def check(self, v):
"""check the passed in value (do not modify `v`)"""
def apply_defaults(self, v):
"""return a new value with defaults applied (do not modify `v`)"""
def remove_defaults(self, v):
"""return a new value with defaults removed (do not modify `v`)"""
Map(object_name, id_key, *items)
The most basic building block for creating a schema is a Map
object_name: will be displayed in error messages
id_key: will be used to identify the object in error messages. Set to
None if there is no identifying key for the object.
items: validator objects such as Required or Optional
Validator objects are used to validate key-value-pairs of a Map.
writing your own validator
If the built-in validators below don't quite satisfy your usecase, you can
always write your own. Validators use the following interface:
class Validator(object):
def check(self, dct):
"""check that your specific key has the appropriate value in `dct`"""
def apply_default(self, dct):
"""modify `dct` and set the default value if it is missing"""
def remove_default(self, dct):
"""modify `dct` and remove the default value if it is present"""
It may make sense to borrow functions from the built in validators. They
additionally use the following interface(s):
If condition_key is equal to the condition_value, the specific key
will be checked using the check function.
If ensure_absent is True and the condition check fails, the key will
be checked for absense.
Note that the condition_value is checked for equality, so any object
implementing __eq__ may be used. A few are provided out of the box
for this purpose, see equality helpers.