Repository Public MIT Research preview
1"""Laboratoire S11, parcours C — corrigé (réservé à l'enseignant)."""2from __future__ import annotations34LISTE_FERMEE = ("pwd", "ls", "cd", "mkdir", "cat", "grep", "find", "echo")5ECRIVENT = ("mkdir",)678def normaliser(repertoire_courant: str, chemin: str) -> str:9 morceaux = [] if chemin.startswith("/") else [m for m in repertoire_courant.split("/") if m]10 for morceau in chemin.split("/"):11 if morceau in ("", "."):12 continue13 if morceau == "..":14 if morceaux:15 morceaux.pop()16 else:17 morceaux.append(morceau)18 return "/" + "/".join(morceaux)192021def executer_et(commandes: list) -> tuple[int, int]:22 lancees, code = 0, 023 for commande in commandes:24 code = commande()25 lancees += 126 if code != 0:27 break28 return lancees, code293031def rediriger(dossiers: set, fichiers: dict, chemin: str, texte: str, ajouter: bool) -> int:32 parent = chemin.rsplit("/", 1)[0] or "/"33 if parent not in dossiers or chemin in dossiers:34 return 135 fichiers[chemin] = (fichiers.get(chemin, "") if ajouter else "") + texte36 return 0373839def dans_le_bac(bac: str, repertoire_courant: str, chemin: str) -> bool:40 absolu = normaliser(repertoire_courant, chemin)41 return absolu == bac or absolu.startswith(bac.rstrip("/") + "/")424344def evaluer(mots: list[str], cible: str | None, repertoire_courant: str, bac: str) -> str:45 """Défi — la garde : « refuser », « approuver » ou « autoriser » une commande simple.4647 `mots` : la commande et ses arguments ; `cible` : le fichier visé par « > » ou « >> », ou None.48 """49 if not mots or mots[0] not in LISTE_FERMEE:50 return "refuser"51 arguments = [m for m in mots[1:] if not m.startswith("-")]52 if mots[0] == "grep":53 arguments = arguments[1:] # le premier mot est le motif, pas un chemin54 elif mots[0] in ("pwd", "echo"):55 arguments = []56 elif mots[0] == "find":57 arguments = arguments[:1]58 chemins = arguments + ([cible] if cible else [])59 if not all(dans_le_bac(bac, repertoire_courant, c) for c in chemins):60 return "refuser"61 return "approuver" if mots[0] in ECRIVENT or cible else "autoriser"62