Repository Public MIT Research preview
1"""Examen d'un fichier de consignes de projet selon une liste de contrôle explicite (bibliothèque standard).23Usage, dans le dossier du projet : python outils/lint_consignes.py consignes-projet.md4Six critères, chacun réussi ou échoué ; les règles sont volontairement simples et toutes écrites ci-dessous.5C'est un jouet pédagogique : il juge la FORME du fichier (ce qui s'y trouve), jamais sa vérité. Un fichier6peut obtenir 6/6 et citer une commande qui n'existe pas : seule une personne qui lance la commande le sait.7"""8from __future__ import annotations910import re11import sys12from dataclasses import dataclass13from pathlib import Path1415COMMANDES = ("python", "python3", "py", "make", "pytest", "npm", "pnpm", "cargo", "go", "git", "mvn", "gradle")16VAGUES = ("propre", "qualité", "bonnes pratiques", "bien organisé", "correct", "corrects", "correctement",17 "attention", "de temps en temps", "au mieux", "élégant", "si possible")18OBLIGATION = re.compile(r"\b(toujours|doit|doivent|obligatoire)\b", re.I)19INTERDIT = re.compile(r"\b(jamais|interdit|ne\s+\w+\s+(pas|aucun|que)|n'\w+\s+(pas|aucun|que))\b", re.I)20SECRET = re.compile(r"\b\w*(cle|clé|key|token|jeton|secret|password|mot_de_passe)\w*\s*[:=]\s*[\"']?[\w\-]{12,}", re.I)21TERMINE = re.compile(r"^#+\s.*(terminé|termine|acceptation|définition de fini)", re.I)22MOTS_VIDES = {"toujours", "jamais", "doit", "doivent", "pour", "qu'ils", "qu'elles", "avec", "sans", "dans", "tous",23 "toutes", "tout", "leur", "leurs", "cette", "chaque", "avant", "après", "plus", "moins", "être",24 "interdit", "obligatoire", "aucun", "aucune"}25SEUIL = 6262728@dataclass(frozen=True)29class Critere:30 cle: str31 nom: str32 reussi: bool33 detail: str343536def regles(texte: str) -> list[tuple[int, str]]:37 """Lignes de liste du fichier (numéro de ligne, texte), hors blocs de code."""38 resultat, dans_bloc = [], False39 for numero, ligne in enumerate(texte.splitlines(), start=1):40 if ligne.strip().startswith("```"):41 dans_bloc = not dans_bloc42 elif not dans_bloc and re.match(r"\s*[-*]\s+\S", ligne):43 resultat.append((numero, re.sub(r"^\s*[-*]\s+", "", ligne).strip()))44 return resultat454647def commandes_citees(texte: str) -> list[str]:48 """Commandes écrites entre accents graves ou dans un bloc de code : on peut les copier telles quelles."""49 candidates = re.findall(r"`([^`\n]+)`", re.sub(r"```.*?```", "", texte, flags=re.S))50 for bloc in re.findall(r"```[^\n]*\n(.*?)```", texte, flags=re.S):51 candidates.extend(ligne.strip() for ligne in bloc.splitlines())52 retenues = [c for c in candidates if c.split() and c.split()[0] in COMMANDES and len(c.split()) > 1]53 return list(dict.fromkeys(retenues)) # sans doublon, dans l'ordre du fichier545556def objet(regle: str) -> frozenset[str]:57 """Mots porteurs d'une règle : ce sur quoi elle porte, sans les mots d'obligation ou d'interdiction."""58 mots = re.findall(r"[a-zàâçéèêëîïôûùüœ'_/\.\-]{4,}", regle.lower().replace("`", " "))59 return frozenset(m.strip("./-'") for m in mots if m not in MOTS_VIDES) - {""}606162def contradictions(lignes: list[tuple[int, str]]) -> list[tuple[int, int]]:63 """Paires (ligne, ligne) : l'une oblige, l'autre interdit, et l'objet de l'une contient celui de l'autre."""64 obligations = [(n, objet(r)) for n, r in lignes if OBLIGATION.search(r) and not INTERDIT.search(r)]65 interdits = [(n, objet(r)) for n, r in lignes if INTERDIT.search(r)]66 return sorted((min(a, b), max(a, b)) for a, oa in obligations for b, ob in interdits67 if len(oa & ob) >= 2 and (oa <= ob or ob <= oa))686970def regles_vagues(lignes: list[tuple[int, str]]) -> list[int]:71 """Règles qui contiennent un mot vague et rien de vérifiable (ni accent grave, ni nombre)."""72 return [n for n, r in lignes if any(v in r.lower() for v in VAGUES) and "`" not in r and not re.search(r"\d", r)]737475def examiner(texte: str) -> list[Critere]:76 lignes = regles(texte)77 commandes = commandes_citees(texte)78 tests = [c for c in commandes if "test" in c]79 limites = [n for n, r in lignes if INTERDIT.search(r) and re.search(r"`[^`]*[/.][^`]*`", r)]80 secrets = [n for n, l in enumerate(texte.splitlines(), start=1) if SECRET.search(l)]81 paires = contradictions(lignes)82 vagues = regles_vagues(lignes)83 titres = [n for n, l in enumerate(texte.splitlines(), start=1) if TERMINE.search(l)]84 suivants = [n for n, l in enumerate(texte.splitlines(), start=1) if titres and n > titres[0] and l.startswith("#")]85 fin = suivants[0] if suivants else len(texte.splitlines()) + 186 apres = [n for n, _ in lignes if titres and titres[0] < n < fin]87 return [88 Critere("commandes", "commande de test à copier", bool(tests),89 f"{pluriel(len(commandes), 'commande')}, dont {len(tests)} de test"),90 Critere("limites", "limites nommant un chemin", bool(limites), pluriel(len(limites), "règle")),91 Critere("termine", "définition de terminé", bool(titres and apres),92 pluriel(len(apres), "critère") if titres else "aucune rubrique"),93 Critere("secrets", "aucun contenu d'allure secrète", not secrets,94 "aucun" if not secrets else "ligne " + ", ".join(map(str, secrets))),95 Critere("contradictions", "aucune contradiction", not paires,96 "aucune" if not paires else "lignes " + " ; ".join(f"{a} et {b}" for a, b in paires)),97 Critere("precision", "aucune règle vague", not vagues,98 "aucune" if not vagues else pluriel(len(vagues), "règle vague")),99 ]100101102def pluriel(nombre: int, mot: str) -> str:103 """« 1 règle », « 4 règles » ; chaque mot du groupe prend la marque du pluriel."""104 return f"{nombre} " + " ".join(m + ("s" if nombre > 1 else "") for m in mot.split())105106107def note(criteres: list[Critere]) -> int:108 return sum(c.reussi for c in criteres)109110111def main(arguments: list[str]) -> int:112 if len(arguments) != 1:113 print("Usage : python outils/lint_consignes.py <fichier de consignes>")114 return 2115 chemin = Path(arguments[0])116 if not chemin.is_file():117 print(f"Fichier introuvable : {chemin}")118 return 2119 criteres = examiner(chemin.read_text(encoding="utf-8"))120 print(f"Examen de {chemin.name} : six critères de forme")121 for c in criteres:122 print(f" [{'x' if c.reussi else ' '}] {c.nom:<32} {c.detail}")123 print(f"Note : {note(criteres)}/{SEUIL}. Rappel : la note juge la forme, pas la vérité des consignes.")124 return 0 if note(criteres) == SEUIL else 1125126127if __name__ == "__main__":128 sys.exit(main(sys.argv[1:]))129