Repository Public MIT Research preview
1#!/usr/bin/env python32"""Fabrique le point de départ du laboratoire à partir du corrigé, pour qu'ils ne divergent jamais.34 python3 generer_starter.py réécrit starter/budget.py, politiques.py, banc_bruit.py5 python3 generer_starter.py --check échoue si starter/ diffère de ce que le corrigé produirait67Règle : dans chaque fichier de ../solutions/, toute fonction PUBLIQUE garde sa signature et sa docstring (qui8est sa spécification) et son corps devient `raise NotImplementedError("À compléter : <nom>")` ; toute9fonction PRIVÉE (nom commençant par « _ ») est retirée, avec ses appels ; les classes de données, les10constantes et les imports sont conservés. Le point de départ ne contient donc aucune ligne de solution11(vérifié par tests/test_starter.py).12"""13from __future__ import annotations1415import argparse16import ast17import sys18from pathlib import Path1920LABS = Path(__file__).resolve().parent21SOLUTIONS, STARTER = LABS.parent / "solutions", LABS / "starter"22FICHIERS = ("budget.py", "politiques.py", "banc_bruit.py")232425def transformer(source: str) -> str:26 arbre = ast.parse(source)27 lignes = source.splitlines()28 remplacements: list[tuple[int, int, list[str]]] = []29 for noeud in arbre.body:30 if not isinstance(noeud, ast.FunctionDef):31 continue32 debut = noeud.lineno - 1 - len(noeud.decorator_list)33 if noeud.name.startswith("_"):34 remplacements.append((debut, noeud.end_lineno, []))35 continue36 doc = noeud.body[0] if isinstance(noeud.body[0], ast.Expr) and isinstance(getattr(noeud.body[0], "value", None), ast.Constant) else None37 fin_entete = (doc.end_lineno if doc else noeud.body[0].lineno - 1)38 corps = [f' raise NotImplementedError("À compléter : {noeud.name}")']39 remplacements.append((fin_entete, noeud.end_lineno, corps))40 for debut, fin, nouveau in sorted(remplacements, reverse=True):41 lignes[debut:fin] = nouveau42 texte = "\n".join(lignes) + "\n"43 texte = texte.replace("(CORRIGÉ)", "(POINT DE DÉPART — à compléter)")44 while "\n\n\n\n" in texte:45 texte = texte.replace("\n\n\n\n", "\n\n\n")46 return texte474849def attendu() -> dict[Path, str]:50 return {STARTER / nom: transformer((SOLUTIONS / nom).read_text(encoding="utf-8")) for nom in FICHIERS}515253def main() -> int:54 ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)55 ap.add_argument("--check", action="store_true")56 args = ap.parse_args()57 perimes = []58 for chemin, texte in attendu().items():59 if args.check:60 if not chemin.exists() or chemin.read_text(encoding="utf-8") != texte:61 perimes.append(chemin.name)62 else:63 chemin.parent.mkdir(exist_ok=True)64 chemin.write_text(texte, encoding="utf-8")65 print(f"écrit starter/{chemin.name}")66 if perimes:67 print("starter périmé : " + ", ".join(perimes), file=sys.stderr)68 return 169 return 0707172if __name__ == "__main__":73 sys.exit(main())74