diff --git a/.github/branch-protection/dev.json b/.github/branch-protection/dev.json new file mode 100644 index 0000000..6557961 --- /dev/null +++ b/.github/branch-protection/dev.json @@ -0,0 +1,15 @@ +{ + "required_status_checks": { + "strict": true, + "checks": [ + { "context": "Qualité (lint, format, tests)", "app_id": 15368 } + ] + }, + "enforce_admins": true, + "required_pull_request_reviews": null, + "restrictions": null, + "required_linear_history": false, + "allow_force_pushes": false, + "allow_deletions": false, + "required_conversation_resolution": false +} diff --git a/.github/branch-protection/main.json b/.github/branch-protection/main.json new file mode 100644 index 0000000..cb37ce0 --- /dev/null +++ b/.github/branch-protection/main.json @@ -0,0 +1,20 @@ +{ + "required_status_checks": { + "strict": false, + "checks": [ + { "context": "Garde : PR vers main doit venir de dev", "app_id": 15368 }, + { "context": "Qualité (lint, format, tests)", "app_id": 15368 } + ] + }, + "enforce_admins": true, + "required_pull_request_reviews": { + "dismiss_stale_reviews": false, + "require_code_owner_reviews": false, + "required_approving_review_count": 0 + }, + "restrictions": null, + "required_linear_history": false, + "allow_force_pushes": false, + "allow_deletions": false, + "required_conversation_resolution": false +} diff --git a/.github/workflows/branch-protection.yml b/.github/workflows/branch-protection.yml new file mode 100644 index 0000000..4b6b0f0 --- /dev/null +++ b/.github/workflows/branch-protection.yml @@ -0,0 +1,45 @@ +# Vérifie que la protection réelle de `main` et `dev` correspond aux règles +# versionnées .github/branch-protection/{main,dev}.json (socle Mathilde-Team, +# repris de Gcm4 #161 / Netcross #334). +# +# Une protection de branche est un réglage du dépôt, invisible dans le code : +# ce workflow rend l'écart visible. L'appliquer reste une action manuelle d'un +# administrateur : +# gh api -X PUT repos///branches//protection \ +# --input .github/branch-protection/.json +name: Protection des branches + +"on": + push: + branches: [main, dev] + schedule: + - cron: "23 6 * * *" + workflow_dispatch: + +permissions: + contents: read + +jobs: + verification: + name: "Protection de ${{ matrix.branche }} conforme à la règle versionnée" + runs-on: ${{ fromJSON(vars.RUNS_ON_LINUX || '{"group":"maison","labels":["self-hosted","linux"]}') }} + strategy: + fail-fast: false + matrix: + branche: [main, dev] + steps: + - name: Checkout du dépôt + uses: actions/checkout@v7 + + - name: Installation de uv + uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0 + + - name: Installation de Python + run: uv python install + + - name: Comparaison avec .github/branch-protection/${{ matrix.branche }}.json + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # loguru (SOCLE §8) à la version de uv.lock ; --no-project évite + # d'installer le projet et ses dépendances pour un script autonome. + run: uv run --no-project --with "loguru==0.7.3" python scripts/check_branch_protection.py --branche ${{ matrix.branche }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bd7b23c..7f77aa9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,6 +14,10 @@ jobs: # de couverture est combinée à celle du job Qualité, qui applique le seuil. name: Tests GTK4 (Xvfb, couverture) runs-on: ubuntu-latest + # Plafond (#98) : sans lui, une connexion apt figée garde le job + # jusqu'aux 360 min par défaut. Durée normale : 1 à 3 min, jusqu'à 14 min + # quand le miroir Ubuntu est lent. + timeout-minutes: 30 steps: - name: Checkout du dépôt @@ -23,9 +27,12 @@ jobs: # libgirepository-2.0-dev + libcairo2-dev + pkg-config : compilation # de PyGObject/pycairo dans le venv ; gvfs + dbus : reproduction réelle # de tests/test_gvfs_env_workaround.py (sinon sauté). + # Jusqu'à 12 min observées (miroir lent) ; Acquire::* relance une + # connexion figée au lieu d'attendre indéfiniment. + timeout-minutes: 20 run: | - sudo apt-get update - sudo env DEBIAN_FRONTEND=noninteractive apt-get install -y \ + sudo apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=60 update + sudo env DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=60 install -y \ gir1.2-gtk-4.0 libgirepository-2.0-dev libcairo2-dev pkg-config \ xvfb xauth dbus dbus-x11 gvfs iproute2 @@ -63,6 +70,7 @@ jobs: needs: gtk if: ${{ !cancelled() }} runs-on: ${{ fromJSON(vars.RUNS_ON_LINUX || '{"group":"maison","labels":["self-hosted","linux"]}') }} + timeout-minutes: 30 steps: - name: Checkout du dépôt diff --git a/.github/workflows/desassignation.yml b/.github/workflows/desassignation.yml new file mode 100644 index 0000000..0b8f4e3 --- /dev/null +++ b/.github/workflows/desassignation.yml @@ -0,0 +1,29 @@ +# Retire chaque heure les assignés des issues ouvertes sans activité de leur +# part depuis 24 h (commentaire, commit, PR…). Logique commune dans +# Mathilde-Team/.github (workflow réutilisable desassignation-inactifs.yml, +# SOCLE.md §9). Label `garder-assignation` pour exempter une issue. +name: Désassignation des issues inactives + +"on": + schedule: + - cron: "10 * * * *" + workflow_dispatch: + inputs: + simulation: + description: N'écrit rien, affiche seulement les décisions + type: boolean + default: true + +permissions: + contents: read + issues: write + +concurrency: + group: desassignation + cancel-in-progress: false + +jobs: + desassigner: + uses: Mathilde-Team/.github/.github/workflows/desassignation-inactifs.yml@main + with: + simulation: ${{ github.event_name == 'workflow_dispatch' && inputs.simulation }} diff --git a/CHANGELOG.md b/CHANGELOG.md index f46c57c..9c96133 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ Format : [Keep a Changelog](https://keepachangelog.com/fr/1.1.0/). Les numéros suivent [SemVer](https://semver.org/lang/fr/), et la version de `pyproject.toml` est égale au tag. +## [Non publié] + +### Ajouté +- Règles de protection versionnées `.github/branch-protection/{main,dev}.json` (relevées sur la protection réelle du 22/10/2026), vérifiées par le workflow `branch-protection.yml` (push sur main/dev, chaque jour) et `scripts/check_branch_protection.py` (socle Mathilde-Team/.github#1, #96). + ## [1.0.0] - 2026-10-22 Première version publiée sous forme de release GitHub. diff --git a/scripts/check_branch_protection.py b/scripts/check_branch_protection.py new file mode 100755 index 0000000..0d8dcd9 --- /dev/null +++ b/scripts/check_branch_protection.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +"""Compare la protection réelle d'une branche à la règle versionnée. + +Règle : .github/branch-protection/.json (format de l'API GitHub +« Update branch protection », applicable telle quelle par un administrateur) : + + gh api -X PUT repos///branches//protection \ + --input .github/branch-protection/.json + +Avec le GITHUB_TOKEN d'un workflow (sans droit d'administration), seule la +partie publique de la protection est lisible (GET /branches/) : +branche protégée, checks requis, application aux administrateurs. Le reste de +la règle n'est pas vérifiable ici et est signalé en information. + +Bibliothèque standard pour le réseau (urllib) ; loguru pour la journalisation +(SOCLE §8, ``SOCLE_DEBUG=1`` pour voir les debug). Code de sortie 1 en cas +d'écart ou d'erreur d'API, 2 si le dépôt est inconnu ou la règle absente ou +illisible. +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request +from pathlib import Path + +from loguru import logger + + +def lire_protection(depot: str, branche: str, jeton: str | None) -> dict: + """Renvoie la représentation publique de la branche (GET /branches/).""" + logger.debug("lire_protection() called | depot={} branche={} jeton={}", depot, branche, bool(jeton)) + requete = urllib.request.Request( + f"https://api.github.com/repos/{depot}/branches/{branche}", + headers={"Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28"}, + ) + if jeton: + requete.add_header("Authorization", f"Bearer {jeton}") + with urllib.request.urlopen(requete, timeout=30) as reponse: + logger.debug("lire_protection() returning | protection lue") + return json.load(reponse) + + +def checks_attendus(regle: dict) -> set[str]: + """Noms des checks requis par la règle versionnée.""" + logger.debug("checks_attendus() called | {} clé(s) dans la règle", len(regle)) + rsc = regle.get("required_status_checks") or {} + noms = {c["context"] for c in rsc.get("checks", [])} | set(rsc.get("contexts", [])) + logger.debug("checks_attendus() returning | {} check(s) attendus", len(noms)) + return noms + + +def comparer(regle: dict, branche_api: dict) -> list[str]: + """Liste des écarts entre la règle et la protection réelle.""" + logger.debug("comparer() called | branche protégée={}", bool(branche_api.get("protected"))) + if not branche_api.get("protected"): + logger.debug("comparer() returning | 1 écart (branche non protégée)") + return ["la branche n'est pas protégée"] + ecarts = [] + protection = branche_api.get("protection") or {} + rsc = protection.get("required_status_checks") or {} + reels = {c["context"] for c in rsc.get("checks", [])} | set(rsc.get("contexts", [])) + attendus = checks_attendus(regle) + if manquants := sorted(attendus - reels): + ecarts.append(f"checks requis absents : {', '.join(manquants)}") + if en_trop := sorted(reels - attendus): + ecarts.append(f"checks requis non prévus par la règle : {', '.join(en_trop)}") + admins_attendu = bool(regle.get("enforce_admins")) + admins_reel = rsc.get("enforcement_level") == "everyone" + if attendus and admins_attendu != admins_reel: + ecarts.append(f"application aux administrateurs : attendu {admins_attendu}, réel {admins_reel}") + logger.debug("comparer() returning | {} écart(s)", len(ecarts)) + return ecarts + + +def main() -> int: + logger.trace("main() called (avant configuration des puits)") + logger.remove() + logger.add(sys.stderr, level="DEBUG" if os.environ.get("SOCLE_DEBUG") else "WARNING") + logger.debug("main() called") + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--branche", required=True) + parser.add_argument("--depot", default=os.environ.get("GITHUB_REPOSITORY")) + parser.add_argument("--regles", default=".github/branch-protection") + args = parser.parse_args() + if not args.depot: + print("::error::dépôt inconnu (--depot ou GITHUB_REPOSITORY)") + logger.debug("main() returning | 2 (dépôt inconnu)") + return 2 + + chemin = Path(args.regles, f"{args.branche}.json") + try: + regle = json.loads(chemin.read_text(encoding="utf-8")) + except FileNotFoundError: + logger.error("règle absente : {}", chemin) + print(f"::error::règle absente : {chemin}") + logger.debug("main() returning | 2 (règle absente)") + return 2 + except json.JSONDecodeError as erreur: + logger.error("règle illisible : {} (ligne {}, {})", chemin, erreur.lineno, erreur.msg) + print(f"::error::règle illisible : {chemin} (ligne {erreur.lineno}, {erreur.msg})") + logger.debug("main() returning | 2 (règle illisible)") + return 2 + try: + branche_api = lire_protection(args.depot, args.branche, os.environ.get("GITHUB_TOKEN")) + except urllib.error.HTTPError as erreur: + logger.error("lecture de la branche {} impossible : HTTP {}", args.branche, erreur.code) + print(f"::error::lecture de la branche {args.branche} impossible : HTTP {erreur.code}") + logger.debug("main() returning | 1 (HTTP {})", erreur.code) + return 1 + except urllib.error.URLError as erreur: + logger.error("API GitHub injoignable : {}", erreur.reason) + print(f"::error::API GitHub injoignable : {erreur.reason}") + logger.debug("main() returning | 1 (API injoignable)") + return 1 + + ecarts = comparer(regle, branche_api) + for ecart in ecarts: + print(f"::error::{args.branche} : {ecart}") + print( + "::notice::non vérifiable avec le GITHUB_TOKEN : branche à jour (strict), revues de PR, force-push, suppression" + ) + if ecarts: + print( + f"Pour appliquer la règle : gh api -X PUT repos/{args.depot}/branches/{args.branche}" + f"/protection --input {args.regles}/{args.branche}.json" + ) + logger.debug("main() returning | 1 ({} écart(s))", len(ecarts)) + return 1 + print(f"Protection de {args.branche} conforme à {args.regles}/{args.branche}.json") + logger.debug("main() returning | 0 (conforme)") + return 0 + + +if __name__ == "__main__": + sys.exit(main())