blob: 590aea33557c74e1d6f412586994451ee9e44162 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
"""Module containing cached JSON schemas."""
from __future__ import annotations
import json
import logging
from typing import TYPE_CHECKING
import jsonschema
import yaml
from jsonschema.exceptions import ValidationError
from ansiblelint.loaders import yaml_load_safe
from ansiblelint.schemas.__main__ import JSON_SCHEMAS, _schema_cache
_logger = logging.getLogger(__package__)
if TYPE_CHECKING:
from ansiblelint.file_utils import Lintable
def validate_file_schema(file: Lintable) -> list[str]:
"""Return list of JSON validation errors found."""
if file.kind not in JSON_SCHEMAS:
return [f"Unable to find JSON Schema '{file.kind}' for '{file.path}' file."]
try:
# convert yaml to json (keys are converted to strings)
yaml_data = yaml_load_safe(file.content)
json_data = json.loads(json.dumps(yaml_data))
jsonschema.validate(
instance=json_data,
schema=_schema_cache[file.kind],
)
except yaml.constructor.ConstructorError as exc:
return [f"Failed to load YAML file '{file.path}': {exc.problem}"]
except ValidationError as exc:
return [exc.message]
return []
|