delminio-client / kit / it / ganci-git-client
raw · sha256 6a6c4e8343b98b544d536ef92bc705f4fd96c3da40c06dcb6d205ffee59fc937
1#!/usr/bin/env bash
2# © 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.
3e_un_close() { grep -qE "^($P_CLOSE) S[0-9]+" <<<"$1"; }
4case "${1:-}" in
5 commit-msg)
6 file="${2:-}"; [ -f "$file" ] || exit 0
7 pid=$(cli_pid || true); sess=""; [ -n "$pid" ] && sess=$(mia_sessione "$pid")
8 if [ -n "$sess" ] && ! { f=$(_segno_pubblico) && [ -e "$f" ]; }; then
9 git interpret-trailers --in-place --if-exists doNothing --trailer "Delminio-Sessione: $sess" "$file" 2>/dev/null || true
10 fi
11 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)")
12 controlli_f="$STATO/carta-controlli-$$"; rm -f "$controlli_f"
13 if duri=$(chiedi POST /api/lock/commit "$staged"); then
14 pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid")
15 DELMINIO_DURI="$duri" DELMINIO_U="$URL" DELMINIO_T="$TOKEN" DELMINIO_ACCETTATE="$(accettate_file)" \
16 DELMINIO_CONTROLLI_F="$controlli_f" python3 - "$nome" <<'DURI' || exit 1
17import hashlib, json, os, subprocess, sys, urllib.error, urllib.request
18exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
19duri = json.loads(os.environ["DELMINIO_DURI"]).get("duri") or []
20radice = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True).stdout.strip() or "."
21try:
22 accettate = set(open(os.environ["DELMINIO_ACCETTATE"], encoding="utf-8").read().split())
23except OSError:
24 accettate = set()
25fermo = False
26fatti = [] # B923: il comando e la sua uscita, le prove nella carta del commit
27GUARDIA_SECONDI = 120 # il controllo del commit ha il suo tempo: ci girano anche i test
28
29
30def manda(percorso, dati):
31 req = urllib.request.Request(os.environ["DELMINIO_U"] + percorso, data=json.dumps(dati).encode(), method="POST",
32 headers={"Authorization": "Bearer " + os.environ["DELMINIO_T"],
33 "Content-Type": "application/json"})
34 return json.loads(urllib.request.urlopen(req, timeout=8).read())
35
36
37def cieco(lk, motivo):
38 """B938 — il controllo non ha detto niente: si conta, e il commit si ferma come per una
39 violazione (le guardie del commit sono tutte di decisioni che bloccano)."""
40 try:
41 manda("/api/lock/cieco", {"codice": lk["codice"], "motivo": motivo, "sessione": sys.argv[1],
42 "comando": lk["comando"]})
43 except Exception:
44 pass # un conto non ferma un commit
45for lk in duri:
46 impronta = hashlib.sha256((lk["codice"] + "\0" + lk["comando"]).encode()).hexdigest()
47 if impronta not in accettate:
48 print(F("guardia_non_accettata", codice=lk["codice"], comando=lk["comando"]), file=sys.stderr)
49 continue
50 fermo_cieco = ""
51 try:
52 p = subprocess.run(lk["comando"], shell=True, cwd=radice, capture_output=True, text=True,
53 timeout=GUARDIA_SECONDI)
54 rc, uscita = p.returncode, p.stdout + p.stderr
55 except subprocess.TimeoutExpired:
56 rc, uscita = 124, F("controllo_lento_breve", comando=lk["comando"], secondi=GUARDIA_SECONDI)
57 fermo_cieco = F("guardia_lento_fermo", codice=lk["codice"], comando=lk["comando"], secondi=GUARDIA_SECONDI)
58 cieco(lk, "lento")
59 except OSError:
60 rc, uscita = 127, ""
61 fatti.append({"codice": lk["codice"], "comando": lk["comando"], "uscita": rc})
62 if rc == 0:
63 continue
64 if rc in (126, 127) and not fermo_cieco:
65 uscita = F("controllo_non_parte_breve", comando=lk["comando"])
66 fermo_cieco = F("guardia_non_parte_fermo", codice=lk["codice"], comando=lk["comando"])
67 cieco(lk, "non_parte")
68 try:
69 r = manda("/api/lock/violazione", {"codice": lk["codice"], "uscita": uscita[-4000:], "sessione": sys.argv[1]})
70 except urllib.error.HTTPError as e:
71 print(F("lock_grida_errore", codice=lk["codice"], codice_http=e.code), file=sys.stderr)
72 r = {"esito": "avviso"}
73 except Exception:
74 print(F("lock_grida_muto", codice=lk["codice"]), file=sys.stderr)
75 r = {"esito": "avviso"}
76 if fermo_cieco and r.get("esito") == "ferma":
77 print(fermo_cieco, file=sys.stderr)
78 print(("❌ " if r.get("esito") == "ferma" else "⚠️ ") + (r.get("messaggio") or lk["cosa"]), file=sys.stderr)
79 if fermo_cieco and r.get("esito") != "ferma":
80 print(" " + uscita.strip(), file=sys.stderr)
81 elif not fermo_cieco:
82 print(F("guardia_dice"), file=sys.stderr)
83 for riga in uscita.strip().splitlines()[-15:]:
84 print(" " + riga, file=sys.stderr)
85 fermo = fermo or r.get("esito") == "ferma"
86with open(os.environ["DELMINIO_CONTROLLI_F"], "w", encoding="utf-8") as h:
87 json.dump(fatti, h)
88sys.exit(1 if fermo else 0)
89DURI
90 case "$duri" in
91 *'"carta":{'*)
92 : > "$STATO/carta"; rm -f "$STATO/carta-no"
93 [ -f "$(dirname "$0")/firme.py" ] && DELMINIO_DURI="$duri" DELMINIO_STATO="$STATO" \
94 python3 "$(dirname "$0")/firme.py" _messaggio "$file" "$sess" "$controlli_f" || true ;;
95 esac
96 rm -f "$controlli_f"
97 else
98 _f "$M_lock_duri_sono" perche "$(perche_no)" >&2
99 fi
100 soggetto=$(grep -v '^#' "$file" | sed -n '/[^[:space:]]/{p;q;}')
101 e_un_close "$soggetto" || exit 0
102 pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid")
103 corpo=$(python3 - "$file" "$nome" <<'GIUDIZIO'
104import json, subprocess, sys
105messaggio = open(sys.argv[1], encoding="utf-8").read()
106staged = subprocess.run(["git", "diff", "--cached", "--name-only"],
107 capture_output=True, text=True).stdout.split()
108head = subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip()
109print(json.dumps({"messaggio": messaggio, "staged": staged, "sessione": sys.argv[2], "head": head}))
110GIUDIZIO
111)
112 if ! r=$(CHIEDI_TEMPO=45 chiedi POST /api/chiusura/giudica "$corpo"); then
113 _f "$M_chiusura_passa_senza" perche "$(perche_no)" >&2
114 exit 0
115 fi
116 DELMINIO_VERDETTO="$r" python3 - "$file" <<'VERDETTO'
117import json, os, subprocess, sys
118exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
119r = json.loads(os.environ["DELMINIO_VERDETTO"])
120if not r.get("ok", True):
121 print(F("chiusura_rifiutata"), file=sys.stderr)
122 for m in r.get("motivi", []):
123 print(f" • {m}", file=sys.stderr)
124 sys.exit(1)
125perche = {"P_TRAILER_TORNATA": F("perche_tornata"), "P_TRAILER_MEMORIA": F("perche_memoria")}
126for k, v in (r.get("aggiungi") or {}).items():
127 subprocess.run(["git", "interpret-trailers", "--in-place", "--trailer", f"{k}: {v}", sys.argv[1]], check=True)
128 spiega = next((x for var, x in perche.items() if k.lower() in os.environ[var].lower().split("|")), "")
129 print(F("aggiunge_trailer_perche", trailer=f"{k}: {v}", perche=spiega) if spiega
130 else F("aggiunge_trailer", trailer=f"{k}: {v}"), file=sys.stderr)
131for a in r.get("avvisi") or []:
132 print(f"⚠️ {a}", file=sys.stderr)
133VERDETTO
134 ;;
135 post-rewrite)
136 coppie=$(awk '$1 != $2 { print $1, $2 }')
137 [ -n "$coppie" ] || exit 0
138 segni=""; [ -f "$STATO/carta" ] && segni=segni
139 f="$STATO/riscritti-$$"; printf '%s\n' "$coppie" > "$f"
140 _staccato bash "$0" post-rewrite-dopo "$f" "$(_remoto)" $segni >/dev/null 2>&1 < /dev/null &
141 ;;
142 post-rewrite-dopo)
143 f=$2
144 corpo=$(python3 "$(dirname "$0")/firme.py" _riscritti ${4:-} < "$f" 2>/dev/null \
145 | python3 -c 'import json, sys; d = json.load(sys.stdin); d["remoto"] = sys.argv[1]; print(json.dumps(d))' "$3") \
146 && chiedi POST /api/repo/riscritti "$corpo" >/dev/null 2>&1
147 rm -f "$f"
148 ;;
149 post-commit)
150 soggetto=$(git log -1 --format=%s 2>/dev/null)
151 pid=$(cli_pid || true); sess=""; [ -n "$pid" ] && sess=$(mia_sessione "$pid")
152 righe=""
153 [ -z "$(git rev-parse -q --verify HEAD^2 2>/dev/null)" ] && righe=$(git show --numstat --format= --diff-filter=d HEAD 2>/dev/null)
154 carta=""
155 [ -f "$(dirname "$0")/firme.py" ] && carta=$(DELMINIO_STATO="$STATO" DELMINIO_URL="$URL" DELMINIO_TOKEN="$TOKEN" \
156 DELMINIO_ACCETTATE="$(accettate_file)" DELMINIO_REMOTO="$(_remoto)" python3 "$(dirname "$0")/firme.py" _commit "$sess")
157 corpo=$(DELMINIO_RIGHE="$righe" DELMINIO_CARTA="$carta" python3 -c '
158import json, os, sys
159d = dict(zip(("remoto", "hash", "sessione", "soggetto"), sys.argv[1:]))
160file = []
161for r in os.environ.get("DELMINIO_RIGHE", "").splitlines():
162 p = r.split("\t", 2)
163 if len(p) == 3 and p[0].isdigit() and p[1].isdigit():
164 file.append((p[2].split("/")[:-1], int(p[0]) + int(p[1])))
165for livelli in (3, 2, 1):
166 righe = {}
167 for cartelle, n in file:
168 k = "/".join(cartelle[:livelli]) or "."
169 righe[k] = righe.get(k, 0) + n
170 if len(righe) <= 150:
171 break
172d["righe"] = righe
173if os.environ.get("DELMINIO_CARTA"):
174 d["carta"] = json.loads(os.environ["DELMINIO_CARTA"])
175print(json.dumps(d))' \
176 "$(_remoto)" "$(git rev-parse HEAD 2>/dev/null)" "$sess" "$soggetto")
177 clone=$(cd "$(dirname "$0")/.." 2>/dev/null && pwd)
178 testa=$(git rev-parse HEAD 2>/dev/null)
179 f="$STATO/commit-$testa.json"; printf '%s' "$corpo" > "$f"
180 _staccato bash "$0" post-commit-dopo "$f" "$testa" "$clone" ${carta:+carta} >/dev/null 2>&1 < /dev/null &
181 e_un_close "$soggetto" || exit 0
182 n=$(printf '%s' "$soggetto" | grep -oE 'S[0-9]+' | head -1)
183 corpo=$(python3 - "$n" "$(_remoto)" <<'CLOSE'
184import json, os, subprocess, sys
185def g(*a):
186 return subprocess.run(["git", *a], capture_output=True, text=True).stdout.strip()
187def chiavi(var): # i nomi di un trailer in ogni lingua (F665), come li vuole git
188 return ",".join("key=" + k for k in os.environ[var].split("|"))
189remoto = sys.argv[2]
190repo = os.path.basename(remoto.rstrip("/"))[:-4] if remoto.rstrip("/").endswith(".git") \
191 else os.path.basename(remoto.rstrip("/"))
192if not repo:
193 repo = os.path.basename(os.path.dirname(os.path.abspath(g("rev-parse", "--git-common-dir"))))
194print(json.dumps({"sessione": sys.argv[1], "close": True, "commit": {
195 "hash": g("rev-parse", "--short=10", "HEAD"), "remoto": remoto, "repo": repo,
196 "tornata": g("log", "-1", "--format=%(trailers:" + chiavi("P_TRAILER_TORNATA") + ",valueonly,separator=%x20)"),
197 "audit": g("log", "-1", "--format=%(trailers:" + chiavi("P_TRAILER_AUDIT") + ",valueonly)").strip(),
198 "testo": g("--no-replace-objects", "log", "-1", "--format=%B")}}))
199CLOSE
200)
201 if r=$(chiedi POST /api/canale/sessioni/chiudi "$corpo"); then
202 _f "$M_delminio_chiusa_chi" n "$n" >&2
203 m=$(printf '%s' "$r" | python3 -c 'import json,sys
204try: print(", ".join(json.load(sys.stdin).get("mollate") or []))
205except Exception: print("")')
206 [ -z "$m" ] || _f "$M_opere_avevi_mano" m "$m" >&2
207 else
208 _f "$M_risultera_morta_senza" perche "$(perche_no)" n "$n" >&2
209 fi
210 ;;
211 post-commit-dopo)
212 f=$2; corpo=$(cat "$f" 2>/dev/null); rm -f "$f"
213 [ -n "$corpo" ] || exit 0
214 if [ "${5:-}" = carta ]; then
215 segni=$(python3 "$(dirname "$0")/firme.py" _segni "$3" 2>/dev/null) && con=$(DELMINIO_SEGNI="$segni" python3 -c '
216import json, os, sys
217d = json.loads(sys.stdin.read())
218d["carta"].update(json.loads(os.environ["DELMINIO_SEGNI"]))
219print(json.dumps(d))' <<<"$corpo") && corpo=$con
220 fi
221 r=$(chiedi POST /api/repo/commit "$corpo" 2>/dev/null) \
222 && riaggancia "$(printf '%s' "$r" | campo versione)" "$4" presto
223 ;;
224esac