80 lines
2.4 KiB
Python
80 lines
2.4 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
validator.py
|
|
Validateur JSON pour series-studio avec erreurs précises et localisées
|
|
(chemin du champ, cause de l'erreur, correction attendue).
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import jsonschema
|
|
|
|
SCHEMA_PATH = os.path.join(os.path.dirname(__file__), "schema.json")
|
|
|
|
def load_schema():
|
|
with open(SCHEMA_PATH, "r", encoding="utf-8") as f:
|
|
return json.load(f)
|
|
|
|
_SCHEMA = load_schema()
|
|
_VALIDATOR = jsonschema.Draft7Validator(_SCHEMA)
|
|
|
|
def format_error(err: jsonschema.ValidationError):
|
|
"""Formate une erreur jsonschema en dictionnaire clair et localisé."""
|
|
path = ".".join(str(p) for p in err.path)
|
|
if not path:
|
|
if err.validator == "required":
|
|
# Le message indique quelle propriété manque
|
|
prop = err.message.split("'")[1] if "'" in err.message else "champ_requis"
|
|
path = prop
|
|
else:
|
|
path = "source"
|
|
|
|
cause = err.message
|
|
fix = f"Vérifier le champ '{path}' : respecter la structure spécifiée dans schema.json."
|
|
|
|
if err.validator == "type":
|
|
fix = f"Le champ '{path}' doit être de type '{err.validator_value}' au lieu de '{type(err.instance).__name__}'."
|
|
elif err.validator == "required":
|
|
fix = f"Ajouter le champ manquant requis : '{path}'."
|
|
elif err.validator == "enum":
|
|
fix = f"La valeur pour '{path}' doit être parmi {err.validator_value}."
|
|
elif err.validator == "minimum":
|
|
fix = f"La valeur de '{path}' doit être supérieure ou égale à {err.validator_value}."
|
|
|
|
return {
|
|
"path": path,
|
|
"field": path,
|
|
"cause": cause,
|
|
"fix": fix
|
|
}
|
|
|
|
def validate_source(source):
|
|
"""Valide une source JSON complète et renvoie un dictionnaire de résultat."""
|
|
if not isinstance(source, dict):
|
|
return {
|
|
"valid": False,
|
|
"errors": [
|
|
{
|
|
"path": "source",
|
|
"field": "source",
|
|
"cause": "Le document racine doit être un objet JSON (dict)",
|
|
"fix": "Fournir un objet JSON avec schema_version, cartouche, exercices, etc."
|
|
}
|
|
]
|
|
}
|
|
|
|
errors = []
|
|
for err in _VALIDATOR.iter_errors(source):
|
|
errors.append(format_error(err))
|
|
|
|
if errors:
|
|
return {
|
|
"valid": False,
|
|
"errors": errors
|
|
}
|
|
return {
|
|
"valid": True,
|
|
"errors": []
|
|
}
|