| 1 |
[](https://github.com/asottile/cfgv/actions/workflows/main.yml) |
| 2 |
[](https://results.pre-commit.ci/latest/github/asottile/cfgv/main) |
| 3 |
|
| 4 |
cfgv |
| 5 |
==== |
| 6 |
|
| 7 |
Validate configuration and produce human readable error messages. |
| 8 |
|
| 9 |
## Installation |
| 10 |
|
| 11 |
```bash |
| 12 |
pip install cfgv |
| 13 |
``` |
| 14 |
|
| 15 |
## Sample error messages |
| 16 |
|
| 17 |
These are easier to see by example. Here's an example where I typo'd `true` |
| 18 |
in a [pre-commit](https://pre-commit.com) configuration. |
| 19 |
|
| 20 |
``` |
| 21 |
pre_commit.clientlib.InvalidConfigError: |
| 22 |
==> File /home/asottile/workspace/pre-commit/.pre-commit-config.yaml |
| 23 |
==> At Config() |
| 24 |
==> At key: repos |
| 25 |
==> At Repository(repo='https://github.com/pre-commit/pre-commit-hooks') |
| 26 |
==> At key: hooks |
| 27 |
==> At Hook(id='flake8') |
| 28 |
==> At key: always_run |
| 29 |
=====> Expected bool got str |
| 30 |
``` |
| 31 |
|
| 32 |
## API |
| 33 |
|
| 34 |
### `cfgv.validate(value, schema)` |
| 35 |
|
| 36 |
Perform validation on the schema: |
| 37 |
- raises `ValidationError` on failure |
| 38 |
- returns the value on success (for convenience) |
| 39 |
|
| 40 |
### `cfgv.apply_defaults(value, schema)` |
| 41 |
|
| 42 |
Returns a new value which sets all missing optional values to their defaults. |
| 43 |
|
| 44 |
### `cfgv.remove_defaults(value, schema)` |
| 45 |
|
| 46 |
Returns a new value which removes all optional values that are set to their |
| 47 |
defaults. |
| 48 |
|
| 49 |
### `cfgv.load_from_filename(filename, schema, load_strategy, exc_tp=ValidationError)` |
| 50 |
|
| 51 |
Load a file given the `load_strategy`. Reraise any errors as `exc_tp`. All |
| 52 |
defaults will be populated in the resulting value. |
| 53 |
|
| 54 |
Most useful when used with `functools.partial` as follows: |
| 55 |
|
| 56 |
```python |
| 57 |
load_my_cfg = functools.partial( |
| 58 |
cfgv.load_from_filename, |
| 59 |
schema=MY_SCHEMA, |
| 60 |
load_strategy=json.loads, |
| 61 |
exc_tp=MyError, |
| 62 |
) |
| 63 |
``` |
| 64 |
|
| 65 |
## Making a schema |
| 66 |
|
| 67 |
A schema validates a container -- `cfgv` provides `Map` and `Array` for |
| 68 |
most normal cases. |
| 69 |
|
| 70 |
### writing your own schema container |
| 71 |
|
| 72 |
If the built-in containers below don't quite satisfy your usecase, you can |
| 73 |
always write your own. Containers use the following interface: |
| 74 |
|
| 75 |
```python |
| 76 |
class Container(object): |
| 77 |
def check(self, v): |
| 78 |
"""check the passed in value (do not modify `v`)""" |
| 79 |
|
| 80 |
def apply_defaults(self, v): |
| 81 |
"""return a new value with defaults applied (do not modify `v`)""" |
| 82 |
|
| 83 |
def remove_defaults(self, v): |
| 84 |
"""return a new value with defaults removed (do not modify `v`)""" |
| 85 |
``` |
| 86 |
|
| 87 |
### `Map(object_name, id_key, *items)` |
| 88 |
|
| 89 |
The most basic building block for creating a schema is a `Map` |
| 90 |
|
| 91 |
- `object_name`: will be displayed in error messages |
| 92 |
- `id_key`: will be used to identify the object in error messages. Set to |
| 93 |
`None` if there is no identifying key for the object. |
| 94 |
- `items`: validator objects such as `Required` or `Optional` |
| 95 |
|
| 96 |
Consider the following schema: |
| 97 |
|
| 98 |
```python |
| 99 |
Map( |
| 100 |
'Repo', 'url', |
| 101 |
Required('url', check_any), |
| 102 |
) |
| 103 |
``` |
| 104 |
|
| 105 |
In an error message, the map may be displayed as: |
| 106 |
|
| 107 |
- `Repo(url='https://github.com/pre-commit/pre-commit')` |
| 108 |
- `Repo(url=MISSING)` (if the key is not present) |
| 109 |
|
| 110 |
### `Array(of, allow_empty=True)` |
| 111 |
|
| 112 |
Used to nest maps inside of arrays. For arrays of scalars, see `check_array`. |
| 113 |
|
| 114 |
- `of`: A `Map` / `Array` or other sub-schema. |
| 115 |
- `allow_empty`: when `False`, `Array` will ensure at least one element. |
| 116 |
|
| 117 |
When validated, this will check that each element adheres to the sub-schema. |
| 118 |
|
| 119 |
### `KeyValueMap(object_name, key_check_fn, value_schema)` |
| 120 |
|
| 121 |
Used to make a schema representing a homogenous mapping where the keys are |
| 122 |
of a specific type and the values match a schema |
| 123 |
|
| 124 |
- `object_name`: will be displayed in error messages |
| 125 |
- `key_check_fn`: a [check function](#check-functions) for the key |
| 126 |
- `value_schema`: a `Map` / `Array` or other sub-schema. |
| 127 |
|
| 128 |
## Validator objects |
| 129 |
|
| 130 |
Validator objects are used to validate key-value-pairs of a `Map`. |
| 131 |
|
| 132 |
### writing your own validator |
| 133 |
|
| 134 |
If the built-in validators below don't quite satisfy your usecase, you can |
| 135 |
always write your own. Validators use the following interface: |
| 136 |
|
| 137 |
```python |
| 138 |
class Validator(object): |
| 139 |
def check(self, dct): |
| 140 |
"""check that your specific key has the appropriate value in `dct`""" |
| 141 |
|
| 142 |
def apply_default(self, dct): |
| 143 |
"""modify `dct` and set the default value if it is missing""" |
| 144 |
|
| 145 |
def remove_default(self, dct): |
| 146 |
"""modify `dct` and remove the default value if it is present""" |
| 147 |
``` |
| 148 |
|
| 149 |
It may make sense to _borrow_ functions from the built in validators. They |
| 150 |
additionally use the following interface(s): |
| 151 |
|
| 152 |
- `self.key`: the key to check |
| 153 |
- `self.check_fn`: the [check function](#check-functions) |
| 154 |
- `self.default`: a default value to set. |
| 155 |
|
| 156 |
### `Required(key, check_fn)` |
| 157 |
|
| 158 |
Ensure that a key is present in a `Map` and adheres to the |
| 159 |
[check function](#check-functions). |
| 160 |
|
| 161 |
### `RequiredRecurse(key, schema)` |
| 162 |
|
| 163 |
Similar to `Required`, but uses a [schema](#making-a-schema). |
| 164 |
|
| 165 |
### `Optional(key, check_fn, default)` |
| 166 |
|
| 167 |
If a key is present, check that it adheres to the |
| 168 |
[check function](#check-functions). |
| 169 |
|
| 170 |
- `apply_defaults` will set the `default` if it is not present. |
| 171 |
- `remove_defaults` will remove the value if it is equal to `default`. |
| 172 |
|
| 173 |
### `OptionalRecurse(key, schema, default)` |
| 174 |
|
| 175 |
Similar to `Optional` but uses a [schema](#making-a-schema). |
| 176 |
|
| 177 |
- `apply_defaults` will set the `default` if it is not present and then |
| 178 |
validate it with the schema. |
| 179 |
- `remove_defaults` will remove defaults using the schema, and then remove the |
| 180 |
value it if it is equal to `default`. |
| 181 |
|
| 182 |
### `OptionalNoDefault(key, check_fn)` |
| 183 |
|
| 184 |
Like `Optional`, but does not `apply_defaults` or `remove_defaults`. |
| 185 |
|
| 186 |
### `Conditional(key, check_fn, condition_key, condition_value, ensure_absent=False)` |
| 187 |
|
| 188 |
- If `condition_key` is equal to the `condition_value`, the specific `key` |
| 189 |
will be checked using the [check function](#check-functions). |
| 190 |
- If `ensure_absent` is `True` and the condition check fails, the `key` will |
| 191 |
be checked for absense. |
| 192 |
|
| 193 |
Note that the `condition_value` is checked for equality, so any object |
| 194 |
implementing `__eq__` may be used. A few are provided out of the box |
| 195 |
for this purpose, see [equality helpers](#equality-helpers). |
| 196 |
|
| 197 |
### `ConditionalOptional(key, check_fn, default, condition_key, condition_value, ensure_absent=False)` |
| 198 |
|
| 199 |
Similar to ``Conditional`` and ``Optional``. |
| 200 |
|
| 201 |
### `ConditionalRecurse(key, schema, condition_key, condition_value, ensure_absent=True)` |
| 202 |
|
| 203 |
Similar to `Conditional`, but uses a [schema](#making-a-schema). |
| 204 |
|
| 205 |
### `NoAdditionalKeys(keys)` |
| 206 |
|
| 207 |
Use in a mapping to ensure that only the `keys` specified are present. |
| 208 |
|
| 209 |
## Equality helpers |
| 210 |
|
| 211 |
Equality helpers at the very least implement `__eq__` for their behaviour. |
| 212 |
|
| 213 |
They may also implement `def describe_opposite(self):` for use in the |
| 214 |
`ensure_absent=True` error message (otherwise, the `__repr__` will be used). |
| 215 |
|
| 216 |
### `Not(val)` |
| 217 |
|
| 218 |
Returns `True` if the value is not equal to `val`. |
| 219 |
|
| 220 |
### `In(*values)` |
| 221 |
|
| 222 |
Returns `True` if the value is contained in `values`. |
| 223 |
|
| 224 |
### `NotIn(*values)` |
| 225 |
|
| 226 |
Returns `True` if the value is not contained in `values`. |
| 227 |
|
| 228 |
## Check functions |
| 229 |
|
| 230 |
A number of check functions are provided out of the box. |
| 231 |
|
| 232 |
A check function takes a single parameter, the `value`, and either raises a |
| 233 |
`ValidationError` or returns nothing. |
| 234 |
|
| 235 |
### `check_any(_)` |
| 236 |
|
| 237 |
A noop check function. |
| 238 |
|
| 239 |
### `check_type(tp, typename=None)` |
| 240 |
|
| 241 |
Returns a check function to check for a specific type. Setting `typename` |
| 242 |
will replace the type's name in the error message. |
| 243 |
|
| 244 |
For example: |
| 245 |
|
| 246 |
```python |
| 247 |
Required('key', check_type(int)) |
| 248 |
# 'Expected bytes' in both python2 and python3. |
| 249 |
Required('key', check_type(bytes, typename='bytes')) |
| 250 |
``` |
| 251 |
|
| 252 |
Several type checking functions are provided out of the box: |
| 253 |
|
| 254 |
- `check_bool` |
| 255 |
- `check_bytes` |
| 256 |
- `check_int` |
| 257 |
- `check_string` |
| 258 |
- `check_text` |
| 259 |
|
| 260 |
### `check_one_of(possible)` |
| 261 |
|
| 262 |
Returns a function that checks that the value is contained in `possible`. |
| 263 |
|
| 264 |
For example: |
| 265 |
|
| 266 |
```python |
| 267 |
Required('language', check_one_of(('javascript', 'python', 'ruby'))) |
| 268 |
``` |
| 269 |
|
| 270 |
### `check_regex(v)` |
| 271 |
|
| 272 |
Ensures that `v` is a valid python regular expression. |
| 273 |
|
| 274 |
### `check_array(inner_check)` |
| 275 |
|
| 276 |
Returns a function that checks that a value is a sequence and that each |
| 277 |
value in that sequence adheres to the `inner_check`. |
| 278 |
|
| 279 |
For example: |
| 280 |
|
| 281 |
```python |
| 282 |
Required('args', check_array(check_string)) |
| 283 |
``` |
| 284 |
|
| 285 |
### `check_and(*fns)` |
| 286 |
|
| 287 |
Returns a function that performs multiple checks on a value. |
| 288 |
|
| 289 |
For example: |
| 290 |
|
| 291 |
```python |
| 292 |
Required('language', check_and(check_string, my_check_language)) |
| 293 |
``` |