mirror of
https://github.com/pre-commit/pre-commit.git
synced 2026-02-17 08:14:42 +04:00
Add jsonschema extension to populate defaults.
This commit is contained in:
parent
5f4996645c
commit
b23ad5d6a3
2 changed files with 83 additions and 0 deletions
32
pre_commit/jsonschema_extensions.py
Normal file
32
pre_commit/jsonschema_extensions.py
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
|
||||
import copy
|
||||
import jsonschema
|
||||
import jsonschema.validators
|
||||
|
||||
|
||||
# From https://github.com/Julian/jsonschema/blob/master/docs/faq.rst
|
||||
def extend_with_default(validator_class):
|
||||
validate_properties = validator_class.VALIDATORS["properties"]
|
||||
|
||||
def set_defaults(validator, properties, instance, schema):
|
||||
for error in validate_properties(
|
||||
validator, properties, instance, schema,
|
||||
):
|
||||
yield error
|
||||
|
||||
for property, subschema in properties.iteritems():
|
||||
if "default" in subschema:
|
||||
instance.setdefault(property, subschema["default"])
|
||||
|
||||
return jsonschema.validators.extend(
|
||||
validator_class, {"properties" : set_defaults},
|
||||
)
|
||||
|
||||
|
||||
DefaultingValidator = extend_with_default(jsonschema.Draft4Validator)
|
||||
|
||||
|
||||
def apply_defaults(obj, schema):
|
||||
obj = copy.deepcopy(obj)
|
||||
DefaultingValidator(schema).validate(obj)
|
||||
return obj
|
||||
Loading…
Add table
Add a link
Reference in a new issue