#!/usr/bin/env bash # © 2026 Delminio — tutti i diritti riservati. Software proprietario: l'uso con Delminio è regolato dal contratto con cui si usa il servizio; la lettura e la verifica da LICENCE. e_un_close() { grep -qE "^($P_CLOSE) S[0-9]+" <<<"$1"; } case "${1:-}" in commit-msg) file="${2:-}"; [ -f "$file" ] || exit 0 pid=$(cli_pid || true); sess=""; [ -n "$pid" ] && sess=$(mia_sessione "$pid") if [ -n "$sess" ] && ! { f=$(_segno_pubblico) && [ -e "$f" ]; }; then git interpret-trailers --in-place --if-exists doNothing --trailer "Delminio-Sessione: $sess" "$file" 2>/dev/null || true fi staged=$(git diff --cached --name-only -z | python3 -c 'import json,sys; print(json.dumps({"staged": [x for x in sys.stdin.read().split("\0") if x], "sessione": sys.argv[1], "remoto": sys.argv[2]}))' "$sess" "$(_remoto)") controlli_f="$STATO/carta-controlli-$$"; rm -f "$controlli_f" if duri=$(chiedi POST /api/lock/commit "$staged"); then pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid") DELMINIO_DURI="$duri" DELMINIO_U="$URL" DELMINIO_T="$TOKEN" DELMINIO_ACCETTATE="$(accettate_file)" \ DELMINIO_CONTROLLI_F="$controlli_f" python3 - "$nome" <<'DURI' || exit 1 import hashlib, json, os, subprocess, sys, urllib.error, urllib.request exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665) duri = json.loads(os.environ["DELMINIO_DURI"]).get("duri") or [] radice = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True).stdout.strip() or "." try: accettate = set(open(os.environ["DELMINIO_ACCETTATE"], encoding="utf-8").read().split()) except OSError: accettate = set() fermo = False fatti = [] # B923: il comando e la sua uscita, le prove nella carta del commit GUARDIA_SECONDI = 120 # il controllo del commit ha il suo tempo: ci girano anche i test def manda(percorso, dati): req = urllib.request.Request(os.environ["DELMINIO_U"] + percorso, data=json.dumps(dati).encode(), method="POST", headers={"Authorization": "Bearer " + os.environ["DELMINIO_T"], "Content-Type": "application/json"}) return json.loads(urllib.request.urlopen(req, timeout=8).read()) def cieco(lk, motivo): """B938 — il controllo non ha detto niente: si conta, e il commit si ferma come per una violazione (le guardie del commit sono tutte di decisioni che bloccano).""" try: manda("/api/lock/cieco", {"codice": lk["codice"], "motivo": motivo, "sessione": sys.argv[1], "comando": lk["comando"]}) except Exception: pass # un conto non ferma un commit for lk in duri: impronta = hashlib.sha256((lk["codice"] + "\0" + lk["comando"]).encode()).hexdigest() if impronta not in accettate: print(F("guardia_non_accettata", codice=lk["codice"], comando=lk["comando"]), file=sys.stderr) continue fermo_cieco = "" try: p = subprocess.run(lk["comando"], shell=True, cwd=radice, capture_output=True, text=True, timeout=GUARDIA_SECONDI) rc, uscita = p.returncode, p.stdout + p.stderr except subprocess.TimeoutExpired: rc, uscita = 124, F("controllo_lento_breve", comando=lk["comando"], secondi=GUARDIA_SECONDI) fermo_cieco = F("guardia_lento_fermo", codice=lk["codice"], comando=lk["comando"], secondi=GUARDIA_SECONDI) cieco(lk, "lento") except OSError: rc, uscita = 127, "" fatti.append({"codice": lk["codice"], "comando": lk["comando"], "uscita": rc}) if rc == 0: continue if rc in (126, 127) and not fermo_cieco: uscita = F("controllo_non_parte_breve", comando=lk["comando"]) fermo_cieco = F("guardia_non_parte_fermo", codice=lk["codice"], comando=lk["comando"]) cieco(lk, "non_parte") try: r = manda("/api/lock/violazione", {"codice": lk["codice"], "uscita": uscita[-4000:], "sessione": sys.argv[1]}) except urllib.error.HTTPError as e: print(F("lock_grida_errore", codice=lk["codice"], codice_http=e.code), file=sys.stderr) r = {"esito": "avviso"} except Exception: print(F("lock_grida_muto", codice=lk["codice"]), file=sys.stderr) r = {"esito": "avviso"} if fermo_cieco and r.get("esito") == "ferma": print(fermo_cieco, file=sys.stderr) print(("❌ " if r.get("esito") == "ferma" else "⚠️ ") + (r.get("messaggio") or lk["cosa"]), file=sys.stderr) if fermo_cieco and r.get("esito") != "ferma": print(" " + uscita.strip(), file=sys.stderr) elif not fermo_cieco: print(F("guardia_dice"), file=sys.stderr) for riga in uscita.strip().splitlines()[-15:]: print(" " + riga, file=sys.stderr) fermo = fermo or r.get("esito") == "ferma" with open(os.environ["DELMINIO_CONTROLLI_F"], "w", encoding="utf-8") as h: json.dump(fatti, h) sys.exit(1 if fermo else 0) DURI case "$duri" in *'"carta":{'*) : > "$STATO/carta"; rm -f "$STATO/carta-no" [ -f "$(dirname "$0")/firme.py" ] && DELMINIO_DURI="$duri" DELMINIO_STATO="$STATO" \ python3 "$(dirname "$0")/firme.py" _messaggio "$file" "$sess" "$controlli_f" || true ;; esac rm -f "$controlli_f" else _f "$M_lock_duri_sono" perche "$(perche_no)" >&2 fi soggetto=$(grep -v '^#' "$file" | sed -n '/[^[:space:]]/{p;q;}') e_un_close "$soggetto" || exit 0 pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid") corpo=$(python3 - "$file" "$nome" <<'GIUDIZIO' import json, subprocess, sys messaggio = open(sys.argv[1], encoding="utf-8").read() staged = subprocess.run(["git", "diff", "--cached", "--name-only"], capture_output=True, text=True).stdout.split() head = subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip() print(json.dumps({"messaggio": messaggio, "staged": staged, "sessione": sys.argv[2], "head": head})) GIUDIZIO ) if ! r=$(CHIEDI_TEMPO=45 chiedi POST /api/chiusura/giudica "$corpo"); then _f "$M_chiusura_passa_senza" perche "$(perche_no)" >&2 exit 0 fi DELMINIO_VERDETTO="$r" python3 - "$file" <<'VERDETTO' import json, os, subprocess, sys exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665) r = json.loads(os.environ["DELMINIO_VERDETTO"]) if not r.get("ok", True): print(F("chiusura_rifiutata"), file=sys.stderr) for m in r.get("motivi", []): print(f" • {m}", file=sys.stderr) sys.exit(1) perche = {"P_TRAILER_TORNATA": F("perche_tornata"), "P_TRAILER_MEMORIA": F("perche_memoria")} for k, v in (r.get("aggiungi") or {}).items(): subprocess.run(["git", "interpret-trailers", "--in-place", "--trailer", f"{k}: {v}", sys.argv[1]], check=True) spiega = next((x for var, x in perche.items() if k.lower() in os.environ[var].lower().split("|")), "") print(F("aggiunge_trailer_perche", trailer=f"{k}: {v}", perche=spiega) if spiega else F("aggiunge_trailer", trailer=f"{k}: {v}"), file=sys.stderr) for a in r.get("avvisi") or []: print(f"⚠️ {a}", file=sys.stderr) VERDETTO ;; post-rewrite) coppie=$(awk '$1 != $2 { print $1, $2 }') [ -n "$coppie" ] || exit 0 segni=""; [ -f "$STATO/carta" ] && segni=segni f="$STATO/riscritti-$$"; printf '%s\n' "$coppie" > "$f" _staccato bash "$0" post-rewrite-dopo "$f" "$(_remoto)" $segni >/dev/null 2>&1 < /dev/null & ;; post-rewrite-dopo) f=$2 corpo=$(python3 "$(dirname "$0")/firme.py" _riscritti ${4:-} < "$f" 2>/dev/null \ | python3 -c 'import json, sys; d = json.load(sys.stdin); d["remoto"] = sys.argv[1]; print(json.dumps(d))' "$3") \ && chiedi POST /api/repo/riscritti "$corpo" >/dev/null 2>&1 rm -f "$f" ;; post-commit) soggetto=$(git log -1 --format=%s 2>/dev/null) pid=$(cli_pid || true); sess=""; [ -n "$pid" ] && sess=$(mia_sessione "$pid") righe="" [ -z "$(git rev-parse -q --verify HEAD^2 2>/dev/null)" ] && righe=$(git show --numstat --format= --diff-filter=d HEAD 2>/dev/null) carta="" [ -f "$(dirname "$0")/firme.py" ] && carta=$(DELMINIO_STATO="$STATO" DELMINIO_URL="$URL" DELMINIO_TOKEN="$TOKEN" \ DELMINIO_ACCETTATE="$(accettate_file)" DELMINIO_REMOTO="$(_remoto)" python3 "$(dirname "$0")/firme.py" _commit "$sess") corpo=$(DELMINIO_RIGHE="$righe" DELMINIO_CARTA="$carta" python3 -c ' import json, os, sys d = dict(zip(("remoto", "hash", "sessione", "soggetto"), sys.argv[1:])) file = [] for r in os.environ.get("DELMINIO_RIGHE", "").splitlines(): p = r.split("\t", 2) if len(p) == 3 and p[0].isdigit() and p[1].isdigit(): file.append((p[2].split("/")[:-1], int(p[0]) + int(p[1]))) for livelli in (3, 2, 1): righe = {} for cartelle, n in file: k = "/".join(cartelle[:livelli]) or "." righe[k] = righe.get(k, 0) + n if len(righe) <= 150: break d["righe"] = righe if os.environ.get("DELMINIO_CARTA"): d["carta"] = json.loads(os.environ["DELMINIO_CARTA"]) print(json.dumps(d))' \ "$(_remoto)" "$(git rev-parse HEAD 2>/dev/null)" "$sess" "$soggetto") clone=$(cd "$(dirname "$0")/.." 2>/dev/null && pwd) testa=$(git rev-parse HEAD 2>/dev/null) f="$STATO/commit-$testa.json"; printf '%s' "$corpo" > "$f" _staccato bash "$0" post-commit-dopo "$f" "$testa" "$clone" ${carta:+carta} >/dev/null 2>&1 < /dev/null & e_un_close "$soggetto" || exit 0 n=$(printf '%s' "$soggetto" | grep -oE 'S[0-9]+' | head -1) corpo=$(python3 - "$n" "$(_remoto)" <<'CLOSE' import json, os, subprocess, sys def g(*a): return subprocess.run(["git", *a], capture_output=True, text=True).stdout.strip() def chiavi(var): # i nomi di un trailer in ogni lingua (F665), come li vuole git return ",".join("key=" + k for k in os.environ[var].split("|")) remoto = sys.argv[2] repo = os.path.basename(remoto.rstrip("/"))[:-4] if remoto.rstrip("/").endswith(".git") \ else os.path.basename(remoto.rstrip("/")) if not repo: repo = os.path.basename(os.path.dirname(os.path.abspath(g("rev-parse", "--git-common-dir")))) print(json.dumps({"sessione": sys.argv[1], "close": True, "commit": { "hash": g("rev-parse", "--short=10", "HEAD"), "remoto": remoto, "repo": repo, "tornata": g("log", "-1", "--format=%(trailers:" + chiavi("P_TRAILER_TORNATA") + ",valueonly,separator=%x20)"), "audit": g("log", "-1", "--format=%(trailers:" + chiavi("P_TRAILER_AUDIT") + ",valueonly)").strip(), "testo": g("--no-replace-objects", "log", "-1", "--format=%B")}})) CLOSE ) if r=$(chiedi POST /api/canale/sessioni/chiudi "$corpo"); then _f "$M_delminio_chiusa_chi" n "$n" >&2 m=$(printf '%s' "$r" | python3 -c 'import json,sys try: print(", ".join(json.load(sys.stdin).get("mollate") or [])) except Exception: print("")') [ -z "$m" ] || _f "$M_opere_avevi_mano" m "$m" >&2 else _f "$M_risultera_morta_senza" perche "$(perche_no)" n "$n" >&2 fi ;; post-commit-dopo) f=$2; corpo=$(cat "$f" 2>/dev/null); rm -f "$f" [ -n "$corpo" ] || exit 0 if [ "${5:-}" = carta ]; then segni=$(python3 "$(dirname "$0")/firme.py" _segni "$3" 2>/dev/null) && con=$(DELMINIO_SEGNI="$segni" python3 -c ' import json, os, sys d = json.loads(sys.stdin.read()) d["carta"].update(json.loads(os.environ["DELMINIO_SEGNI"])) print(json.dumps(d))' <<<"$corpo") && corpo=$con fi r=$(chiedi POST /api/repo/commit "$corpo" 2>/dev/null) \ && riaggancia "$(printf '%s' "$r" | campo versione)" "$4" presto ;; esac