415 lines
20 KiB
Python
415 lines
20 KiB
Python
"""Manage the JobbJakt migration. Read-only unless --apply is supplied."""
|
|
import argparse
|
|
from collections import Counter
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from contextlib import contextmanager
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
from urllib.error import HTTPError, URLError
|
|
from urllib.request import build_opener, HTTPRedirectHandler, Request
|
|
|
|
REPO = "https://git.cesnimda.uk/cesnimda/jobtrackingapp"
|
|
API = "https://git.cesnimda.uk/api/v1/repos/cesnimda/jobtrackingapp/"
|
|
ROOT = Path(__file__).resolve().parents[1] / "docs/gitea-backlog"
|
|
STATE = ROOT / "checkpoints.json"
|
|
SCOPES = {
|
|
"Kind": "Epic|Feature|Bug|Enhancement|Technical Debt|Refactoring|Security|Performance|UI-UX|Accessibility|Testing|Documentation|Research|Maintenance",
|
|
"Priority": "Critical|High|Medium|Low",
|
|
"Area": "Backend|Frontend|Database|AI|AI-Local|AI-Cloud|Authentication|Authorisation|Job Tracking|Job Discovery|Career Builder|CV Builder|Cover Letters|Templates|PDF|Analytics|Localisation|Settings|Integrations|Infrastructure|CI-CD|Backups|Security|Accessibility|Documentation",
|
|
"Effort": "XS|S|M|L|XL",
|
|
"Status": "Blocked|Needs Decision|Needs Investigation|Needs Reproduction|Deferred",
|
|
"Source": "User Request|Existing Roadmap|Code Audit|Security Audit|Test Audit|UX Audit|Proposed Improvement",
|
|
}
|
|
STAGES = ["Backlog", "Ready", "In Progress", "Blocked", "Code Review", "Testing", "Ready to Deploy", "Done"]
|
|
COLORS = dict(Kind="#7552a3", Priority="#bf5b17", Area="#1c6b8d", Effort="#386e55",
|
|
Status="#a34d36", Source="#55627d")
|
|
MARKER = re.compile(r"<!-- jobbjakt:([A-Z0-9-]+) -->")
|
|
MILESTONES = {"Release qualification": "Evidence and operator decisions for a frozen release candidate.",
|
|
"Redesign acceptance": "Close the A3 route, workflow and human acceptance matrix.",
|
|
"Product review": "Decide the Phase 10 handoff and complete independent product review."}
|
|
|
|
|
|
class NoRedirect(HTTPRedirectHandler):
|
|
def redirect_request(self, *args):
|
|
return None
|
|
|
|
|
|
def request(path, method="GET", data=None):
|
|
headers = {"Accept": "application/json", "Content-Type": "application/json"}
|
|
if os.getenv("GITEA_TOKEN"):
|
|
headers["Authorization"] = "token " + os.environ["GITEA_TOKEN"]
|
|
req = Request(API + path, method=method, headers=headers,
|
|
data=None if data is None else json.dumps(data).encode())
|
|
for attempt in range(4):
|
|
try:
|
|
with build_opener(NoRedirect()).open(req, timeout=35) as res:
|
|
raw = res.read()
|
|
return json.loads(raw) if raw else None
|
|
except (HTTPError, URLError, TimeoutError) as exc:
|
|
code = getattr(exc, "code", 0)
|
|
if method != "GET" or code not in (0, 429, 502, 503, 504) or attempt == 3:
|
|
raise RuntimeError(f"{method} {path}: HTTP {code or 'transport failure'}. Reconcile before retrying writes.") from None
|
|
delay = getattr(exc, "headers", {}) or {}
|
|
wait = delay.get("Retry-After", "")
|
|
if wait.isdigit() and int(wait) > 60:
|
|
raise RuntimeError(f"Rate limited; resume after {wait} seconds.") from None
|
|
time.sleep(int(wait) if wait.isdigit() else 2 ** attempt)
|
|
|
|
|
|
def pages(path):
|
|
result = []
|
|
for page in range(1, 10001):
|
|
sep = "&" if "?" in path else "?"
|
|
batch = request(f"{path}{sep}limit=50&page={page}")
|
|
if not batch:
|
|
return result
|
|
result.extend(batch)
|
|
raise ValueError("Pagination did not terminate")
|
|
|
|
|
|
def save(path, obj):
|
|
tmp = path.with_suffix(".pending")
|
|
tmp.write_text(json.dumps(obj, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
tmp.replace(path)
|
|
|
|
|
|
@contextmanager
|
|
def import_lock():
|
|
"""OS releases the shared per-host writer lock if the process is interrupted."""
|
|
path = Path(tempfile.gettempdir()) / "jobjakt-gitea-backlog.lock"
|
|
with path.open("a+b") as handle:
|
|
handle.seek(0)
|
|
if os.name == "nt":
|
|
import msvcrt
|
|
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
|
|
else:
|
|
import fcntl
|
|
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
yield
|
|
|
|
|
|
def label_spec():
|
|
specs = {}
|
|
for scope, names in SCOPES.items():
|
|
for name in names.split("|"):
|
|
title = f"{scope}/{name}"
|
|
color = COLORS[scope]
|
|
if scope == "Priority":
|
|
color = dict(Critical="#ad2626", High="#d56b27", Medium="#d6af45", Low="#7c9e83")[name]
|
|
specs[title] = dict(name=title, color=color, description=f"{scope} classification for {name.lower()}.",
|
|
exclusive=scope in ("Priority", "Effort"))
|
|
return specs
|
|
|
|
|
|
def label_names(x):
|
|
names = [f"Kind/{x['kind']}", f"Priority/{x['priority']}", f"Effort/{x['effort']}",
|
|
f"Source/{x['source']}", *["Area/" + area for area in x["areas"]]]
|
|
if x["stage"] == "Blocked":
|
|
names.append("Status/Blocked")
|
|
if x["key"] in ("P-D02", "U-DESIGN", "W-DESIGN", "D-DELETE"):
|
|
names.append("Status/Needs Decision")
|
|
if x["kind"] == "Research" and x["stage"] == "Ready":
|
|
names.append("Status/Needs Investigation")
|
|
return names
|
|
|
|
|
|
def validate(items):
|
|
by_key = {x["key"]: x for x in items}
|
|
assert len(by_key) == len(items) == len({x["title"].casefold() for x in items})
|
|
specs = label_spec()
|
|
def visit(key, path):
|
|
assert key not in path, f"Dependency cycle at {key}"
|
|
for dep in by_key[key]["deps"]:
|
|
visit(dep, path | {key})
|
|
for x in items:
|
|
assert x["criteria"] and x["testing"] and x["refs"] and x["background"]
|
|
assert set(label_names(x)) <= specs.keys() and x["stage"] in STAGES
|
|
assert x["stage"] != "Done" and (not x["milestone"] or x["milestone"] in MILESTONES)
|
|
assert not x.get("parent") or by_key[x["parent"]]["kind"] == "Epic"
|
|
visit(x["key"], set())
|
|
return by_key
|
|
|
|
|
|
def body(x):
|
|
sections = [("Summary", x["title"] + "."),
|
|
("Background and evidence", x["background"]),
|
|
("Scope and expected outcome", x["criteria"][0]),
|
|
("Acceptance criteria", "\n".join("- [ ] " + s for s in x["criteria"])),
|
|
("Testing requirements", x["testing"]),
|
|
("Dependencies and compatibility", "Initial disposition: " + x["stage"] +
|
|
". " + ("Prerequisites: " + ", ".join(x["deps"]) + ". " if x["deps"] else "") +
|
|
("See the recorded owner, environment or provider gate before proceeding. " if x["stage"] == "Blocked" else "") +
|
|
"Production changes require separate release approval."),
|
|
("Definition of done", "Link the verified result, revision or decision and remaining limitations. Obtain the acceptance required above before closing."),
|
|
("References", "\n".join(f"- [Evidence {i}]({ref})" for i, ref in enumerate(x["refs"], 1)))]
|
|
return "\n\n".join("### " + k + "\n\n" + v for k, v in sections) + f"\n\n<!-- jobbjakt:{x['key']} -->"
|
|
|
|
|
|
def matches(items, existing, state):
|
|
found = {}
|
|
for x in items:
|
|
key = x["key"]
|
|
hits = [i for i in existing if key in MARKER.findall(i["body"] or "")]
|
|
same_title = [i for i in existing if i["title"].strip().casefold() == x["title"].strip().casefold()]
|
|
if len(hits) > 1 or any(i not in hits for i in same_title):
|
|
raise ValueError(f"Ambiguous existing issue for {key}; reconcile manually before importing.")
|
|
if hits:
|
|
found[key] = hits[0]
|
|
recorded = state["issues"].get(key)
|
|
if recorded and (not hits or recorded["number"] != hits[0]["number"]):
|
|
raise ValueError(f"Remote identity differs from checkpoint for {key}")
|
|
return found
|
|
|
|
|
|
def relations(x, items, found):
|
|
lines = []
|
|
if x.get("parent"):
|
|
lines.append("Parent epic: #" + str(found[x["parent"]]["number"]))
|
|
for child in items:
|
|
if child.get("parent") == x["key"]:
|
|
lines.append(f"- [ ] #{found[child['key']]['number']} {child['title']}")
|
|
if x["deps"]:
|
|
lines.append("Depends on " + ", ".join("#" + str(found[k]["number"]) for k in x["deps"]))
|
|
return "\n".join(lines)
|
|
|
|
|
|
def verify_one(x, items, found, milestones):
|
|
issue = found[x["key"]]
|
|
errors = []
|
|
if issue["state"] != "open" or issue["title"] != x["title"] or body(x) not in issue["body"]:
|
|
errors.append("content or state")
|
|
if not set(label_names(x)) <= {v["name"] for v in issue["labels"]}:
|
|
errors.append("labels")
|
|
if (issue["milestone"] or {}).get("title") != x["milestone"]:
|
|
errors.append("milestone")
|
|
if any(line not in issue["body"] for line in relations(x, items, found).splitlines()):
|
|
errors.append("epic or links")
|
|
if x["deps"]:
|
|
actual = {v["number"] for v in pages(f"issues/{issue['number']}/dependencies")}
|
|
if not {found[k]["number"] for k in x["deps"]} <= actual:
|
|
errors.append("native dependencies")
|
|
return [x["key"] + ": " + ", ".join(errors)] if errors else []
|
|
|
|
|
|
def main():
|
|
p = argparse.ArgumentParser(description=__doc__)
|
|
p.add_argument("action", choices=["plan", "sync", "verify", "verify-board", "queue", "blocked", "criteria", "report", "fallback", "retire-fallback", "note"])
|
|
p.add_argument("key", nargs="?")
|
|
p.add_argument("--note-file", type=Path, help="Append a UTF-8 progress/evidence note without replacing existing text")
|
|
p.add_argument("--apply", action="store_true")
|
|
p.add_argument("--batch-size", type=int, default=10)
|
|
p.add_argument("--max-batches", type=int)
|
|
args = p.parse_args()
|
|
if args.batch_size < 1 or args.max_batches is not None and args.max_batches < 1:
|
|
p.error("Batch sizes must be positive")
|
|
items = json.loads((ROOT / "inventory.json").read_text(encoding="utf-8"))
|
|
by_key = validate(items)
|
|
state = json.loads(STATE.read_text(encoding="utf-8"))
|
|
paths = ["issues?state=all&type=issues", "labels", "milestones?state=all"]
|
|
with ThreadPoolExecutor(3) as pool:
|
|
existing, labels, miles = list(pool.map(pages, paths))
|
|
existing = [i for i in existing if not i.get("pull_request")]
|
|
found = matches(items, existing, state)
|
|
missing = [x for x in items if x["key"] not in found]
|
|
if args.action in ("verify-board", "retire-fallback"):
|
|
board = read_board()
|
|
errors = [x["key"] for x in items if x["key"] not in found or
|
|
board.get(found[x["key"]]["number"]) != x["stage"]]
|
|
if errors:
|
|
raise ValueError(f"{len(errors)} missing or misplaced cards: {', '.join(errors)}")
|
|
print(f"Verified {len(items)} issue-to-column assignments on project 1")
|
|
if args.action == "retire-fallback":
|
|
for i in found.values():
|
|
for label in i["labels"]:
|
|
name = label["name"]
|
|
if name in ("Status/Ready", "Status/Testing", "Status/Backlog") and state["created_labels"].get(name) == label["id"]:
|
|
if args.apply:
|
|
request(f"issues/{i['number']}/labels/{label['id']}", "DELETE")
|
|
else:
|
|
print(f"#{i['number']} retire {name}")
|
|
return
|
|
if args.action == "note":
|
|
issue = found[args.key]
|
|
if not args.note_file:
|
|
p.error("note requires --note-file")
|
|
note = args.note_file.read_text(encoding="utf-8").strip()
|
|
if not note:
|
|
p.error("note is empty")
|
|
if note not in issue["body"] and args.apply:
|
|
request(f"issues/{issue['number']}", "PATCH", {"content_version": issue["content_version"],
|
|
"body": issue["body"] + "\n\n" + note})
|
|
return
|
|
if args.action == "fallback":
|
|
board = read_board()
|
|
labels_by_name = {v["name"]: v for v in labels}
|
|
for x in items:
|
|
issue = found[x["key"]]
|
|
if issue["number"] in board:
|
|
continue
|
|
name = "Status/" + x["stage"]
|
|
current = {v["name"] for v in issue["labels"]}
|
|
if name in current:
|
|
continue
|
|
if any("Status/" + s in current for s in STAGES):
|
|
raise ValueError(f"Existing workflow label on #{issue['number']}; reconcile its current stage.")
|
|
if not args.apply:
|
|
print(f"#{issue['number']} {name}")
|
|
continue
|
|
if name not in labels_by_name:
|
|
labels_by_name[name] = request("labels", "POST", dict(name=name, color="#586fa2",
|
|
description=f"Board fallback for the {x['stage']} column."))
|
|
state.setdefault("created_labels", {})[name] = labels_by_name[name]["id"]
|
|
save(STATE, state)
|
|
request(f"issues/{issue['number']}/labels", "POST", {"labels": [labels_by_name[name]["id"]]})
|
|
return
|
|
if args.action == "criteria":
|
|
issue = found[args.key]
|
|
print(issue["body"].split("### Acceptance criteria", 1)[1].split("\n### ", 1)[0].strip())
|
|
return
|
|
if args.action in ("queue", "blocked"):
|
|
board = read_board()
|
|
rank = SCOPES["Priority"].split("|")
|
|
for i in sorted(existing, key=lambda i: (min([rank.index(v["name"][9:]) for v in i["labels"] if v["name"].startswith("Priority/") and v["name"][9:] in rank] or [9]), i["number"])):
|
|
stage = effective_stage(i, board)
|
|
if i["state"] != "open" or stage != ("Ready" if args.action == "queue" else "Blocked"):
|
|
continue
|
|
blockers = [d["number"] for d in pages(f"issues/{i['number']}/dependencies") if d["state"] == "open"]
|
|
if args.action == "blocked" or not blockers:
|
|
print(f"#{i['number']} {i['title']} {blockers or ''}")
|
|
return
|
|
if args.action == "report":
|
|
print(json.dumps(distribution(existing), indent=2))
|
|
return
|
|
if args.action == "verify":
|
|
if missing:
|
|
raise ValueError(f"{len(missing)} expected issues missing")
|
|
current_labels = {v["name"]: v for v in labels}
|
|
for name, spec in label_spec().items():
|
|
if name not in current_labels or bool(current_labels[name]["exclusive"]) != spec["exclusive"]:
|
|
raise ValueError("Missing or incorrectly scoped label: " + name)
|
|
with ThreadPoolExecutor(4) as pool:
|
|
errors = sum(pool.map(lambda x: verify_one(x, items, found, miles), items), [])
|
|
if errors:
|
|
raise ValueError("\n".join(errors))
|
|
print(f"Verified {len(items)} issue identities, bodies, classifications, milestones, epic links and dependencies.")
|
|
return
|
|
labels = {v["name"].casefold(): v for v in labels}
|
|
miles = {v["title"]: v for v in miles}
|
|
specs = label_spec()
|
|
print(f"Existing issues {len(existing)}; matched {len(found)}; to create {len(missing)}; " +
|
|
f"new labels {sum(n.casefold() not in labels for n in specs)}; new milestones {len(MILESTONES.keys() - miles.keys())}", flush=True)
|
|
if args.action == "plan" or not args.apply:
|
|
return
|
|
if not os.getenv("GITEA_TOKEN"):
|
|
p.error("--apply requires GITEA_TOKEN or the Windows credential wrapper")
|
|
for name, spec in specs.items():
|
|
if name.casefold() not in labels:
|
|
labels[name.casefold()] = request("labels", "POST", spec)
|
|
state.setdefault("created_labels", {})[name] = labels[name.casefold()]["id"]
|
|
save(STATE, state)
|
|
for name, desc in MILESTONES.items():
|
|
if name not in miles:
|
|
miles[name] = request("milestones", "POST", {"title": name, "description": desc})
|
|
state.setdefault("created_milestones", {})[name] = miles[name]["id"]
|
|
save(STATE, state)
|
|
for start in range(0, len(missing), args.batch_size):
|
|
batch = missing[start:start+args.batch_size]
|
|
for x in batch:
|
|
payload = dict(title=x["title"], body=body(x), labels=[labels[n.casefold()]["id"] for n in label_names(x)])
|
|
if x["milestone"]:
|
|
payload["milestone"] = miles[x["milestone"]]["id"]
|
|
i = request("issues", "POST", payload)
|
|
found[x["key"]] = i
|
|
state["issues"][x["key"]] = {"number": i["number"], "id": i["id"], "url": i["html_url"], "column": x["stage"]}
|
|
save(STATE, state)
|
|
state["batches"].append([x["key"] for x in batch])
|
|
save(STATE, state)
|
|
print(f"Checkpoint: {len(found)}/{len(items)} issues", flush=True)
|
|
if args.max_batches and start // args.batch_size + 1 >= args.max_batches and len(found) < len(items):
|
|
return
|
|
# Recover the journal after an interrupted successful POST and preserve all human-written text.
|
|
for key, i in found.items():
|
|
state["issues"].setdefault(key, {"number": i["number"], "id": i["id"], "url": i["html_url"], "column": by_key[key]["stage"]})
|
|
save(STATE, state)
|
|
for x in items:
|
|
i = found[x["key"]]
|
|
link_text = relations(x, items, found)
|
|
path = f"issues/{i['number']}"
|
|
if link_text and any(line not in i["body"] for line in link_text.splitlines()):
|
|
live = request(path)
|
|
end = "<!-- jobbjakt-links -->"
|
|
additions = [line for line in link_text.splitlines() if line not in live["body"]]
|
|
if additions:
|
|
extra = "\n".join(additions) + "\n\n" + end
|
|
updated = (live["body"].replace(end, extra, 1) if end in live["body"]
|
|
else live["body"] + "\n\n### Related work\n\n" + extra)
|
|
request(path, "PATCH", {"body": updated, "content_version": live["content_version"]})
|
|
if x["deps"]:
|
|
linked = {d["number"] for d in pages(path + "/dependencies")}
|
|
for dep in x["deps"]:
|
|
number = found[dep]["number"]
|
|
if number not in linked:
|
|
request(path + "/dependencies", "POST", {"owner": "cesnimda", "repo": "jobtrackingapp", "index": number})
|
|
if "Native dependencies and epic links reconciled." not in state["phases"]:
|
|
state["phases"].append("Native dependencies and epic links reconciled.")
|
|
save(STATE, state)
|
|
|
|
|
|
def read_board():
|
|
from html.parser import HTMLParser
|
|
class Board(HTMLParser):
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.stage = None
|
|
self.read_title = False
|
|
self.cards = {}
|
|
|
|
def handle_starttag(self, tag, attrs):
|
|
a = dict(attrs)
|
|
if "project-column-title-text" in a.get("class", "").split():
|
|
self.read_title = True
|
|
href = a.get("href", "")
|
|
match = re.fullmatch(r"/cesnimda/jobtrackingapp/issues/(\d+)", href)
|
|
if tag == "a" and match and self.stage:
|
|
self.cards[int(match[1])] = self.stage
|
|
|
|
def handle_data(self, data):
|
|
if self.read_title and data.strip():
|
|
self.stage = data.strip()
|
|
self.read_title = False
|
|
|
|
parser = Board()
|
|
with build_opener(NoRedirect()).open(REPO + "/projects/1", timeout=30) as response:
|
|
parser.feed(response.read().decode())
|
|
return parser.cards
|
|
|
|
|
|
def distribution(existing):
|
|
board = read_board()
|
|
return {"total": len(existing), **{k: dict(Counter(l["name"].split("/", 1)[1] for i in existing for l in i["labels"] if l["name"].startswith(k + "/"))) for k in ("Kind", "Priority", "Area", "Source")},
|
|
"columns": dict(Counter(board.get(i["number"], "Unassigned") for i in existing)),
|
|
"workflow": dict(Counter(effective_stage(i, board) for i in existing))}
|
|
|
|
|
|
def effective_stage(issue, board):
|
|
if issue["number"] in board:
|
|
return board[issue["number"]]
|
|
labels = {label["name"] for label in issue["labels"]}
|
|
return next((s for s in STAGES if "Status/" + s in labels), "Unassigned")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
if "--apply" in sys.argv:
|
|
with import_lock():
|
|
main()
|
|
else:
|
|
main()
|
|
except (RuntimeError, ValueError, KeyError) as err:
|
|
sys.exit(str(err))
|