feat(contribution): la convention des commits se vérifie au hook, au poste et dans la CI
Chaque commit d'une demande arrive tel quel sur main (commit de fusion) : titre conventionnel, Signed-off-by (DCO) de l'auteur, un outil jamais co-auteur. scripts/verifier_commits.py sert le hook commit-msg (make git-hooks), make commits-verifier et la CI des demandes. Assisted-by: Claude Code Signed-off-by: Daniel Allaire <allaire.dan@chezlepro.ca>
This commit is contained in:
parent
47afcc0c27
commit
e924a69404
7 changed files with 178 additions and 0 deletions
|
|
@ -39,6 +39,15 @@ jobs:
|
|||
steps:
|
||||
- name: Recuperer le depot
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
# Toute l'histoire : la convention des commits se verifie sur la plage de la demande.
|
||||
fetch-depth: 0
|
||||
|
||||
# CHAQUE COMMIT D'UNE DEMANDE ARRIVE TEL QUEL SUR `main` (fusion par commit de fusion,
|
||||
# CONTRIBUTING.md) : titre conventionnel, `Signed-off-by` de l'auteur, un outil jamais co-auteur.
|
||||
- name: Convention des commits de la demande
|
||||
if: github.event_name == 'pull_request'
|
||||
run: python3 scripts/verifier_commits.py "origin/${GITHUB_BASE_REF}..HEAD"
|
||||
|
||||
- name: Outils et collections, puis `make ci`
|
||||
run: |
|
||||
|
|
|
|||
9
Makefile
9
Makefile
|
|
@ -1385,6 +1385,15 @@ etat: ## L'etat de tous les ecosystemes en une commande : depots du poste, runne
|
|||
changelog-archiver: ## Range le CHANGELOG : le mois en cours reste, les mois passes vont dans changelog/AAAA-MM.md (P103)
|
||||
python3 scripts/changelog_archiver.py
|
||||
|
||||
.PHONY: git-hooks
|
||||
git-hooks: ## Active les hooks du depot (commit-msg : convention des commits, DCO, outils jamais co-auteurs) — une fois par copie
|
||||
git config core.hooksPath scripts/git-hooks
|
||||
@printf '%s\n' 'Hooks actifs : scripts/git-hooks (git config core.hooksPath). Voir CONTRIBUTING.md.'
|
||||
|
||||
.PHONY: commits-verifier
|
||||
commits-verifier: ## Les commits d'une branche suivent-ils la convention (titre, DCO, outil jamais co-auteur) ? — PLAGE=<base>..<tete>, defaut eregion/main..HEAD
|
||||
python3 scripts/verifier_commits.py "$(or $(PLAGE),eregion/main..HEAD)"
|
||||
|
||||
.PHONY: changelog-assembler
|
||||
changelog-assembler: ## Juste avant une fusion : les fragments de changelog.d/ deviennent des entrees datees et numerotees — ARGS=--essai pour voir
|
||||
python3 scripts/changelog_assembler.py $(ARGS)
|
||||
|
|
|
|||
|
|
@ -1550,6 +1550,12 @@ hors_assistant:
|
|||
changelog-archiver: >-
|
||||
Range le CHANGELOG du depot moteur, au poste du mainteneur, avant un commit. Il ne
|
||||
touche aucune machine ; un runner n'a rien a y ranger.
|
||||
git-hooks: >-
|
||||
Active les hooks git d'une copie de travail, au poste de qui ecrit des commits. Il ne
|
||||
touche aucune machine ; un runner n'ecrit pas de commit.
|
||||
commits-verifier: >-
|
||||
Relit les commits d'une branche avant sa fusion, au poste de qui relit ; la CI fait la meme
|
||||
verification sur chaque demande. Il ne touche aucune machine.
|
||||
changelog-assembler: >-
|
||||
Assemble les fragments du journal sur la branche d'une demande de fusion, juste avant de
|
||||
la fusionner, au poste de qui fusionne. Il ne touche aucune machine ; un runner n'a pas de
|
||||
|
|
|
|||
|
|
@ -128,6 +128,8 @@ documente ses options (`--help`) dans sa docstring.
|
|||
| `make schema` | Regenere docs/audit/schema-plan.json depuis les registres et les validateurs |
|
||||
| `make plan-recette` | Regenere docs/audit/plan-de-recette.md depuis le wiki |
|
||||
| `make changelog-archiver` | Range le CHANGELOG : le mois en cours reste, les mois passes vont dans changelog/AAAA-MM.md (P103) |
|
||||
| `make git-hooks` | Active le hook `commit-msg` du dépôt : titre conventionnel, `Signed-off-by` (DCO), un outil jamais co-auteur — une fois par copie, voir CONTRIBUTING.md |
|
||||
| `make commits-verifier` | Les commits d'une branche suivent-ils la convention (titre conventionnel, DCO, outil jamais co-auteur) ? `PLAGE=<base>..<tête>`, par défaut `eregion/main..HEAD` |
|
||||
| `make changelog-assembler` | Juste avant une fusion : les fragments de `changelog.d/` deviennent des entrées datées et numérotées (`ARGS=--essai` pour voir) — voir CONTRIBUTING.md |
|
||||
| `make sonder` | Sonde une cible et DIT ce qui distingue — CIBLE=<hote\|ip> [PORTS="22 443"] |
|
||||
| `make valider` | Passe la recette de validation sur la flotte |
|
||||
|
|
|
|||
4
scripts/git-hooks/commit-msg
Executable file
4
scripts/git-hooks/commit-msg
Executable file
|
|
@ -0,0 +1,4 @@
|
|||
#!/bin/sh
|
||||
# Hook commit-msg du depot (CONTRIBUTING.md) — active par `make git-hooks`.
|
||||
# Refuse un titre non conventionnel, un commit sans `Signed-off-by` (DCO), un outil co-auteur.
|
||||
exec python3 "$(git rev-parse --show-toplevel)/scripts/verifier_commits.py" --message "$1"
|
||||
46
scripts/tests/test_verifier_commits.py
Normal file
46
scripts/tests/test_verifier_commits.py
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
#!/usr/bin/env python3
|
||||
"""La convention des messages de commit (scripts/verifier_commits.py, CONTRIBUTING.md)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts"))
|
||||
import verifier_commits as v # noqa: E402
|
||||
|
||||
SIGNE = "Signed-off-by: Anne Exemple <anne@exemple.org>"
|
||||
|
||||
|
||||
class Convention(unittest.TestCase):
|
||||
|
||||
def test_conforme(self):
|
||||
self.assertEqual(v.defauts(f"fix(flux): la sonde se tait\n\nCorps.\n\nAssisted-by: Claude Code\n{SIGNE}\n"), [])
|
||||
self.assertEqual(v.defauts(f"feat!: rupture\n\n{SIGNE}"), [])
|
||||
|
||||
def test_titre_non_conventionnel(self):
|
||||
self.assertTrue(any("titre" in d for d in v.defauts(f"courriel : SRS\n\n{SIGNE}")))
|
||||
self.assertTrue(any("titre" in d for d in v.defauts(f"feature(x): inconnu\n\n{SIGNE}")))
|
||||
|
||||
def test_dco_obligatoire_et_celui_de_l_auteur(self):
|
||||
self.assertTrue(any("Signed-off-by" in d for d in v.defauts("docs: x\n")))
|
||||
self.assertTrue(any("auteur" in d for d in v.defauts(f"docs: x\n\n{SIGNE}", "autre@exemple.org")))
|
||||
self.assertEqual(v.defauts(f"docs: x\n\n{SIGNE}", "ANNE@exemple.org"), [])
|
||||
|
||||
def test_un_outil_n_est_jamais_co_auteur_une_personne_si(self):
|
||||
outil = f"docs: x\n\nCo-Authored-By: Claude Opus <noreply@anthropic.com>\n{SIGNE}"
|
||||
self.assertTrue(any("co-auteur" in d for d in v.defauts(outil)))
|
||||
personne = f"docs: x\n\nCo-authored-by: Mathieu Exemple <mathieu@exemple.org>\n{SIGNE}"
|
||||
self.assertEqual(v.defauts(personne), [])
|
||||
self.assertTrue(any("Assisted-by" in d for d in v.defauts(f"docs: x\n\nAssisted-by:\n{SIGNE}")))
|
||||
|
||||
def test_fixup_au_hook_seulement(self):
|
||||
self.assertEqual(v.defauts(f"fixup! docs: x\n\n{SIGNE}", travail_permis=True), [])
|
||||
self.assertTrue(v.defauts(f"fixup! docs: x\n\n{SIGNE}"))
|
||||
|
||||
def test_les_commentaires_de_l_editeur_sont_ignores(self):
|
||||
self.assertEqual(v.defauts(f"docs: x\n\n{SIGNE}\n# Veuillez saisir le message\n"), [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
102
scripts/verifier_commits.py
Executable file
102
scripts/verifier_commits.py
Executable file
|
|
@ -0,0 +1,102 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Un message de commit respecte-t-il la convention du depot ? (CONTRIBUTING.md)
|
||||
|
||||
POURQUOI (2026-11-23). Les demandes de fusion entrent par un commit de fusion : chaque commit
|
||||
d'une branche arrive TEL QUEL sur `main`. L'historique doit dire sans ambiguite qui a ecrit quoi
|
||||
— le mainteneur, un contributeur, l'assistance d'un outil. Ce que la convention exige :
|
||||
|
||||
- un titre conventionnel : `type(portee): description` (feat, fix, docs, test, refactor, ci,
|
||||
chore, perf, build, style, revert) ;
|
||||
- un `Signed-off-by:` (DCO), celui de l'auteur du commit quand on verifie une plage ;
|
||||
- un outil se declare par `Assisted-by: <outil>` et n'est jamais co-auteur : un
|
||||
`Co-authored-by:` qui nomme un outil ou un robot est refuse. Celui d'une personne reste permis.
|
||||
|
||||
Usage :
|
||||
python3 scripts/verifier_commits.py --message <fichier> # hook commit-msg (make git-hooks)
|
||||
python3 scripts/verifier_commits.py <base>..<tete> # une plage (CI d'une demande de fusion)
|
||||
|
||||
Les commits de fusion ne sont pas verifies : Forgejo les ecrit. `fixup!` et `squash!` passent au
|
||||
hook (ils disparaissent au rebase) mais pas dans une plage : une branche se nettoie avant la revue.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
TYPES = ("feat", "fix", "docs", "test", "refactor", "ci", "chore", "perf", "build", "style", "revert")
|
||||
TITRE = re.compile(rf"^({'|'.join(TYPES)})(\([^()\s][^()]*\))?!?: \S")
|
||||
TRAVAIL = re.compile(r"^(fixup|squash|amend)! ")
|
||||
SIGNE = re.compile(r"(?m)^Signed-off-by: (.+) <([^<>@\s]+@[^<>\s]+)>\s*$")
|
||||
ASSISTE = re.compile(r"(?mi)^assisted-by:(.*)$")
|
||||
OUTIL = re.compile(r"claude|anthropic|codex|openai|copilot|chatgpt|gpt-|gemini|cursor|\[bot\]|-bot\b|bot@", re.I)
|
||||
COAUTEUR = re.compile(r"(?mi)^co-authored-by:(.*)$")
|
||||
|
||||
|
||||
def defauts(message: str, auteur_courriel: str = "", travail_permis: bool = False) -> list[str]:
|
||||
lignes = [l for l in message.splitlines() if not l.startswith("#")]
|
||||
texte = "\n".join(lignes).strip()
|
||||
if not texte:
|
||||
return ["message vide"]
|
||||
titre = texte.splitlines()[0]
|
||||
out = []
|
||||
if not (TITRE.match(titre) or (travail_permis and TRAVAIL.match(titre))):
|
||||
out.append(f"titre non conventionnel : « {titre[:70]} » — attendu `type(portee): description`, "
|
||||
f"type parmi {', '.join(TYPES)}")
|
||||
signes = SIGNE.findall(texte)
|
||||
if not signes:
|
||||
out.append("aucun `Signed-off-by: Nom <courriel>` (DCO) — `git commit -s`")
|
||||
elif auteur_courriel and auteur_courriel.lower() not in {c.lower() for _n, c in signes}:
|
||||
out.append(f"aucun `Signed-off-by` de l'auteur du commit ({auteur_courriel})")
|
||||
for valeur in COAUTEUR.findall(texte):
|
||||
if OUTIL.search(valeur):
|
||||
out.append(f"un outil n'est jamais co-auteur : « Co-authored-by:{valeur.strip()[:50]} » — "
|
||||
"le declarer par `Assisted-by: <outil>`")
|
||||
for valeur in ASSISTE.findall(texte):
|
||||
if not valeur.strip():
|
||||
out.append("`Assisted-by:` sans nom d'outil")
|
||||
return out
|
||||
|
||||
|
||||
def plage(intervalle: str) -> int:
|
||||
r = subprocess.run(["git", "log", "--no-merges", "--format=%H%x00%ae%x00%B%x1e", intervalle],
|
||||
capture_output=True, text=True)
|
||||
if r.returncode != 0:
|
||||
print(f"plage illisible : {intervalle} — {r.stderr.strip()[:200]}")
|
||||
return 2
|
||||
echecs = 0
|
||||
commits = [c for c in r.stdout.split("\x1e") if c.strip()]
|
||||
for c in commits:
|
||||
sha, courriel, message = c.strip("\n").split("\x00", 2)
|
||||
d = defauts(message, courriel)
|
||||
titre = message.strip().splitlines()[0][:70]
|
||||
if d:
|
||||
echecs += 1
|
||||
print(f"ECHEC {sha[:7]} {titre}")
|
||||
for x in d:
|
||||
print(f" - {x}")
|
||||
else:
|
||||
print(f"OK {sha[:7]} {titre}")
|
||||
print(f"{len(commits) - echecs}/{len(commits)} commit(s) conformes a la convention (CONTRIBUTING.md).")
|
||||
return 1 if echecs else 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = sys.argv[1:]
|
||||
if len(args) == 2 and args[0] == "--message":
|
||||
d = defauts(Path(args[1]).read_text(encoding="utf-8"), travail_permis=True)
|
||||
if d:
|
||||
print("Commit refuse — convention du depot (CONTRIBUTING.md) :", file=sys.stderr)
|
||||
for x in d:
|
||||
print(f" - {x}", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
if len(args) == 1 and ".." in args[0]:
|
||||
return plage(args[0])
|
||||
print(__doc__.split("Usage :")[1].split("Les commits")[0].rstrip(), file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Loading…
Reference in a new issue