Add tooling: Makefile, level validation, build, Pyodide vendoring, tests, docs

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
denis
2026-10-14 22:23:20 +02:00
parent e538d4d122
commit dfae68db87
22 changed files with 838 additions and 0 deletions
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""Construit dist/ : app + niveaux + Pyodide, avec liste de pré-cache du service worker à jour."""
from __future__ import annotations
import hashlib
import json
import re
import shutil
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
DIST = ROOT / "dist"
PRECACHED_SUFFIXES = {".html", ".css", ".js", ".mjs", ".json", ".svg", ".webmanifest", ".py"}
NOT_PRECACHED = {"service-worker.js"}
def copy_tree(source: Path, target: Path) -> None:
shutil.copytree(source, target, ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "*.md"))
def shell_files() -> list[str]:
"""Fichiers de l'app à pré-cacher (chemins relatifs à la racine du site)."""
files = [
path.relative_to(DIST).as_posix()
for path in sorted(DIST.rglob("*"))
if path.is_file()
and path.suffix in PRECACHED_SUFFIXES
and path.name not in NOT_PRECACHED
and not path.relative_to(DIST).parts[0] in {"vendor", "levels"}
]
return ["./", *files]
def content_hash(paths: list[str]) -> str:
digest = hashlib.sha256()
for relative in paths:
if relative != "./":
digest.update((DIST / relative).read_bytes())
return digest.hexdigest()[:12]
def main() -> int:
pyodide = ROOT / "vendor" / "pyodide"
if not pyodide.exists():
print("vendor/pyodide absent : lancez `make vendor-pyodide` d'abord.", file=sys.stderr)
return 1
if DIST.exists():
shutil.rmtree(DIST)
copy_tree(ROOT / "app", DIST)
copy_tree(ROOT / "levels", DIST / "levels")
shutil.copytree(pyodide, DIST / "vendor" / "pyodide")
precache = shell_files()
worker = DIST / "service-worker.js"
source = worker.read_text(encoding="utf-8")
source, shell_count = re.subn(r"const SHELL = \[.*?\];", f"const SHELL = {json.dumps(precache)};", source, flags=re.S)
source, version_count = re.subn(
r"const CACHE_VERSION = '[^']*';", f"const CACHE_VERSION = 'pyquest-{content_hash(precache)}';", source
)
if shell_count != 1 or version_count != 1:
print("service-worker.js : motifs SHELL/CACHE_VERSION introuvables.", file=sys.stderr)
return 1
worker.write_text(source, encoding="utf-8")
print(f"dist/ prêt : {len(precache)} fichiers pré-cachés.")
return 0
if __name__ == "__main__":
sys.exit(main())
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""Valide les niveaux : schéma JSON, cohérence du manifeste, traductions et code de départ."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Any
import jsonschema
import yaml
ROOT = Path(__file__).resolve().parent.parent
LEVELS_DIR = ROOT / "levels"
SCHEMA_PATH = LEVELS_DIR / "schema" / "level.schema.json"
def missing_english(node: Any, path: str = "") -> list[str]:
"""Liste les chemins où une chaîne i18n {fr: ...} n'a pas de traduction `en`."""
problems: list[str] = []
if isinstance(node, dict):
if "fr" in node and isinstance(node["fr"], (str, list)):
if "en" not in node:
problems.append(path or "<root>")
for key, value in node.items():
problems.extend(missing_english(value, f"{path}.{key}" if path else str(key)))
elif isinstance(node, list):
for index, value in enumerate(node):
problems.extend(missing_english(value, f"{path}[{index}]"))
return problems
def code_snippets(level: dict[str, Any]) -> list[tuple[str, str]]:
"""Extrait (chemin, code) pour chaque starter/solution du niveau."""
snippets: list[tuple[str, str]] = []
for index, step in enumerate(level.get("steps", [])):
for field in ("starter", "solution"):
if isinstance(step.get(field), str):
snippets.append((f"steps[{index}].{field}", step[field]))
starter = level.get("mission", {}).get("starter")
if isinstance(starter, str):
snippets.append(("mission.starter", starter))
return snippets
def validate_level(path: Path, schema: dict[str, Any], require_en: bool) -> list[str]:
errors: list[str] = []
try:
level = yaml.safe_load(path.read_text(encoding="utf-8"))
except yaml.YAMLError as exc:
return [f"YAML invalide : {exc}"]
validator = jsonschema.Draft202012Validator(schema)
for error in sorted(validator.iter_errors(level), key=lambda e: list(e.absolute_path)):
location = ".".join(str(part) for part in error.absolute_path) or "<root>"
errors.append(f"schéma : {location} : {error.message}")
if errors:
return errors
if level["id"] != path.parent.name:
errors.append(f"id '{level['id']}' différent du dossier '{path.parent.name}'")
if require_en:
errors.extend(f"traduction `en` manquante : {where}" for where in missing_english(level))
for where, code in code_snippets(level):
try:
compile(code, where, "exec")
except SyntaxError as exc:
errors.append(f"{where} : le code ne compile pas ({exc.msg}, ligne {exc.lineno})")
return errors
def validate_manifest(known_ids: set[str]) -> list[str]:
manifest = json.loads((LEVELS_DIR / "manifest.json").read_text(encoding="utf-8"))
errors: list[str] = []
listed = [entry["id"] for entry in manifest["levels"]]
for level_id in listed:
if level_id not in known_ids:
errors.append(f"manifest : '{level_id}' n'a pas de level.yaml")
for level_id in sorted(known_ids - set(listed)):
errors.append(f"manifest : '{level_id}' existe mais n'est pas référencé")
for entry in manifest["levels"]:
for required in entry.get("requires", []):
if required not in listed:
errors.append(f"manifest : '{entry['id']}' requiert '{required}' inconnu")
return errors
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--allow-missing-en", action="store_true", help="n'exige pas les traductions en")
args = parser.parse_args()
schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
jsonschema.Draft202012Validator.check_schema(schema)
files = sorted(LEVELS_DIR.glob("*/level.yaml"))
failed = False
for path in files:
errors = validate_level(path, schema, require_en=not args.allow_missing_en)
status = "OK " if not errors else "KO "
print(f"{status} {path.parent.name}")
for message in errors:
print(f" - {message}")
failed = failed or bool(errors)
for message in validate_manifest({path.parent.name for path in files}):
print(f"KO {message}")
failed = True
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env bash
# Télécharge Pyodide (version épinglée) et l'installe dans vendor/pyodide/.
# Pyodide doit être servi depuis le même domaine (COEP require-corp interdit le CDN cross-origin).
set -euo pipefail
PYODIDE_VERSION="314.0.7"
PYODIDE_SHA256="2abdcc2e35208af406e07724cffa85bc582ced97e9028383ecf5462541393f95"
URL="https://github.com/pyodide/pyodide/releases/download/${PYODIDE_VERSION}/pyodide-core-${PYODIDE_VERSION}.tar.bz2"
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
TARGET="${ROOT}/vendor/pyodide"
WORK="$(mktemp -d)"
trap 'rm -rf "${WORK}"' EXIT
if [[ -f "${TARGET}/.version" && "$(cat "${TARGET}/.version")" == "${PYODIDE_VERSION}" ]]; then
echo "Pyodide ${PYODIDE_VERSION} déjà installé dans ${TARGET}"
exit 0
fi
echo "Téléchargement de Pyodide ${PYODIDE_VERSION}..."
curl --fail --location --silent --show-error --output "${WORK}/pyodide.tar.bz2" "${URL}"
echo "${PYODIDE_SHA256} ${WORK}/pyodide.tar.bz2" | sha256sum --check --status \
|| { echo "Somme de contrôle invalide pour ${URL}" >&2; exit 1; }
mkdir -p "${WORK}/extract"
tar --extract --bzip2 --file "${WORK}/pyodide.tar.bz2" --directory "${WORK}/extract"
rm -rf "${TARGET}"
mkdir -p "${ROOT}/vendor"
mv "${WORK}/extract/pyodide" "${TARGET}"
echo "${PYODIDE_VERSION}" > "${TARGET}/.version"
echo "Pyodide ${PYODIDE_VERSION} installé dans ${TARGET}"