83 lines
3.7 KiB
Python
83 lines
3.7 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
sync_blocked_by.py — macht blocks/blocked-by bidirektional konsistent.
|
|
Für jedes konkrete Paar "A blocks B" wird A in B's blocked-by-Feld ergänzt (falls fehlt).
|
|
IDEMPOTENT (berechnet Fehlende aus Ist-Stand), default DRY-RUN, scharf: --apply
|
|
"""
|
|
import json, os, re, sys, time, urllib.request, urllib.error
|
|
APPLY = "--apply" in sys.argv
|
|
TOK = {}
|
|
for line in open(os.path.expanduser("~/.cli-tokens/plane")):
|
|
line = line.strip()
|
|
if "=" in line and not line.startswith("#"):
|
|
k, v = line.split("=", 1); TOK[k.strip()] = v.strip()
|
|
BASE = TOK["PLANE_BASE_URL"].rstrip("/"); WS = TOK["PLANE_WORKSPACE"]; KEY = TOK["PLANE_API_KEY"]
|
|
PID = "35d0d968-8ab3-40cc-97b8-b81d917dc5df"
|
|
API = f"{BASE}/api/v1/workspaces/{WS}/projects/{PID}"
|
|
IDRE = re.compile(r"\b(VEXT|VR|VA|VD|VH|VJ|VN|EXT|AK|R|D|H|J|N)-[A-Za-z0-9]+")
|
|
def ids(s): return IDRE.findall(s) and [m.group(0) for m in IDRE.finditer(s)] or []
|
|
|
|
def http(m, p, b=None):
|
|
data = json.dumps(b).encode() if b is not None else None
|
|
r = urllib.request.Request(API + p, data=data, method=m); r.add_header("X-API-Key", KEY)
|
|
if data: r.add_header("Content-Type", "application/json")
|
|
for _ in range(4):
|
|
try:
|
|
with urllib.request.urlopen(r, timeout=30) as resp:
|
|
raw = resp.read().decode(); return resp.status, (json.loads(raw) if raw else {})
|
|
except urllib.error.HTTPError as e:
|
|
if e.code == 429: time.sleep(5); continue
|
|
return e.code, {}
|
|
return 999, {}
|
|
def get_all(p):
|
|
out, c = [], None
|
|
while True:
|
|
st, d = http("GET", p + (("?per_page=100&cursor=" + c) if c else "?per_page=100"))
|
|
if st >= 400: break
|
|
if isinstance(d, list): out += d; break
|
|
out += d.get("results", [])
|
|
if d.get("next_page_results") and d.get("next_cursor"): c = d["next_cursor"]
|
|
else: break
|
|
return out
|
|
|
|
issues = get_all("/issues/")
|
|
W = {} # wid -> issue
|
|
for i in issues:
|
|
if " · " in i["name"]: W[i["name"].split(" · ")[0].strip()] = i
|
|
def field(html, label):
|
|
m = re.search(label + r":</(?:b|strong)>\s*(.*?)<br", html)
|
|
return ids(m.group(1)) if m else []
|
|
# erwartete blocked-by je Ticket = alle A, die "blocks B" sagen
|
|
states = {s["id"]: s["name"] for s in get_all("/states/")}
|
|
def cancelled(wid): return states.get(W[wid]["state"]) == "Cancelled"
|
|
expected = {}
|
|
for w, i in W.items():
|
|
if cancelled(w): continue # aufgeloeste/abgesagte Tickets (VD-1/VD-5/D-REST) NICHT als Blocker
|
|
for b in field(i["description_html"], "blocks"):
|
|
if b in W and not cancelled(b): expected.setdefault(b, set()).add(w)
|
|
# pro Ticket: fehlende blocked-by
|
|
plan = []
|
|
for b, exp in expected.items():
|
|
cur = set(field(W[b]["description_html"], "blocked-by"))
|
|
missing = sorted(exp - cur)
|
|
if missing: plan.append((b, missing, sorted(cur)))
|
|
plan.sort()
|
|
print(f"=== blocked-by-Sync {'(SCHARF)' if APPLY else '(DRY-RUN)'} === {len(plan)} Tickets erhalten ergaenzte blocked-by")
|
|
def patch_bb(html, add):
|
|
m = re.search(r"(⛔ blocked-by:</(?:b|strong)>\s*)(.*?)(<br)", html)
|
|
if not m: return None
|
|
cur = m.group(2).strip()
|
|
base = "" if cur in ("", "—", "-") else cur.rstrip(", ")
|
|
newlist = (base + ", " if base else "") + ", ".join(add)
|
|
return html[:m.start(2)] + newlist + html[m.end(2):]
|
|
done = 0
|
|
for b, missing, cur in plan:
|
|
print(f" {b}: + {missing} (war: {cur or '—'})")
|
|
if APPLY:
|
|
nh = patch_bb(W[b]["description_html"], missing)
|
|
if nh is None: print(f" ⚠ kein blocked-by-Feld in {b}"); continue
|
|
st, _ = http("PATCH", f"/issues/{W[b]['id']}/", {"description_html": nh}); time.sleep(1.1)
|
|
if st < 300: done += 1
|
|
else: print(f" ✗ HTTP {st}")
|
|
print(f"{'gepatcht: '+str(done) if APPLY else '→ scharf: --apply'}")
|