"""Counts how long pull requests wait for review in your Azure DevOps organization (Services or Server), and prints the report as Markdown. It runs on your machine; nothing is sent anywhere except to your own Azure DevOps. What it reads, and nothing else (all GET requests, checked in get() below before anything is sent): 1. the list of repositories _apis/git/repositories 2. the pull requests of each one _apis/git/repositories//pullrequests 3. the comment threads of each one _apis/git/repositories//pullRequests//threads 4. the policy results of open ones _apis/policy/evaluations (to see a failing build) All four need only the token scope Code (Read). The script never reads file contents or diffs. Titles, descriptions and comment texts come back from the API but are not kept or printed. Reviewers are shown as letters; the names behind the letters go to reviewer-letters.txt, which stays with you and is not part of the report. The token: put it in the environment variable AZURE_DEVOPS_PAT, or type it when asked (it is not shown). It is never taken as an argument, printed or written to a file. Usage: python count_stuck_prs_azure.py https://dev.azure.com/yourorg > report.md python count_stuck_prs_azure.py https://tfs.example.local/tfs/DefaultCollection --days 90 --project Shop > report.md Python 3.8 or later, standard library only. """ import argparse import base64 import getpass import json import os import re import statistics import sys import time from datetime import datetime, timedelta, timezone from urllib.error import HTTPError, URLError from urllib.parse import quote, urlencode, urlparse from urllib.request import HTTPRedirectHandler, Request, build_opener class NoRedirect(HTTPRedirectHandler): """A redirect would carry the token to another address, so none is followed.""" def redirect_request(self, req, fp, code, msg, headers, newurl): return None OPENER = build_opener(NoRedirect) SIGN_IN = ("Azure DevOps answered %s with %s, not with data: it wants a sign-in, so the token was not accepted. " "Check that the token belongs to this organization and has not expired, and that the address is the " "organization (https://dev.azure.com/yourorg) or, for Azure DevOps Server, the collection " "(https://tfs.example.local/tfs/DefaultCollection).") GUID = r"[0-9a-fA-F-]{36}" ALLOWED = [re.compile(p + "$") for p in ( r"/_apis/git/repositories", r"/%s/_apis/git/repositories/%s/pullrequests" % (GUID, GUID), r"/%s/_apis/git/repositories/%s/pullRequests/\d+/threads" % (GUID, GUID), r"/%s/_apis/policy/evaluations" % GUID, )] REASONS = ["no reviewer asked", "reviewer asked, no answer", "build failing", "changes requested (author's turn)", "reviewed, approval still missing"] BUILD_POLICY = "0609b952-1397-4640-95ec-e00a01b2c241" class Client: def __init__(self, base, token, api_version): self.base = base.rstrip("/") self.auth = "Basic " + base64.b64encode((":" + token).encode()).decode() self.api = api_version self.calls = 0 def get(self, path, params): rest = path if not any(p.fullmatch(rest) for p in ALLOWED): raise SystemExit("refused to call %s: not one of the four reads this script makes" % rest) url = self.base + quote(path) + "?" + urlencode(params) for attempt in range(5): req = Request(url, method="GET", headers={"Authorization": self.auth, "Accept": "application/json"}) try: with OPENER.open(req, timeout=60) as r: self.calls += 1 body = r.read().decode("utf-8", "replace") try: return json.loads(body) except ValueError: raise SystemExit(SIGN_IN % (rest, "a web page")) except HTTPError as e: if e.code in (401, 403): raise SystemExit("Azure DevOps refused the token (%d) for %s. Make a token with the scope " "Code (Read) for this organization." % (e.code, rest)) if 300 <= e.code < 400: raise SystemExit(SIGN_IN % (rest, "a redirect (%d)" % e.code)) if e.code == 404: return None if e.code == 429 or e.code >= 500: time.sleep(float(e.headers.get("Retry-After") or 5 * (attempt + 1))) continue raise SystemExit("Azure DevOps answered %d for %s" % (e.code, rest)) except URLError as e: if attempt == 4: raise SystemExit("could not reach %s: %s" % (urlparse(self.base).netloc, e.reason)) time.sleep(5 * (attempt + 1)) raise SystemExit("Azure DevOps kept answering busy for %s" % rest) def when(s): if not s: return None m = re.match(r"(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d)(?:\.(\d+))?(.*)$", s.replace("Z", "+00:00")) frac = (m.group(2) or "")[:6].ljust(6, "0") # Azure DevOps sends 0 to 7 decimals; older Pythons read only 6 return datetime.fromisoformat("%s.%s%s" % (m.group(1), frac, m.group(3) or "+00:00")) def norm(i): return (i or "").replace("-", "").lower() def is_bot(who): if not who: return True name = (who.get("displayName") or "") + " " + (who.get("uniqueName") or "") return bool(who.get("isContainer")) or bool(re.search(r"Build Service|(^|\s)Build\\|\[bot\]|dependabot|renovate", name, re.I)) def prop(thread, key): v = (thread.get("properties") or {}).get(key) return v.get("$value") if isinstance(v, dict) else v def main(): ap = argparse.ArgumentParser(description="Count how long pull requests wait for review in Azure DevOps.") ap.add_argument("url", help="organization URL, e.g. https://dev.azure.com/yourorg, or your Server collection URL") ap.add_argument("--days", type=int, default=90, help="pull requests opened in the last N days (default 90)") ap.add_argument("--project", help="only this project (name)") ap.add_argument("--api-version", default="7.1", help="7.1 for Services and Server 2022; 6.0 or 5.0 for older Server") ap.add_argument("--letters-file", default="reviewer-letters.txt", help="where the names behind the letters go") a = ap.parse_args() if urlparse(a.url).scheme != "https": raise SystemExit("use the https:// address of your organization, so the token is not sent in the clear") token = os.environ.get("AZURE_DEVOPS_PAT") or getpass.getpass("Azure DevOps token, Code (Read) only (not shown): ") if not token.strip(): raise SystemExit("no token") c = Client(a.url, token.strip(), a.api_version) now = datetime.now(timezone.utc) since = now - timedelta(days=a.days) policy_api = a.api_version if "preview" in a.api_version else a.api_version + "-preview.1" repos = (c.get("/_apis/git/repositories", {"api-version": a.api_version}) or {}).get("value", []) repos = [r for r in repos if not r.get("isDisabled") and (not a.project or r["project"]["name"] == a.project)] sys.stderr.write("%d repositories\n" % len(repos)) prs = [] for r in repos: pid, rid = r["project"]["id"], r["id"] skip, old_pages = 0, 0 while True: page = (c.get("/%s/_apis/git/repositories/%s/pullrequests" % (pid, rid), {"searchCriteria.status": "all", "$top": 100, "$skip": skip, "api-version": a.api_version}) or {}).get("value", []) fresh = [p for p in page if when(p["creationDate"]) >= since] prs += [(pid, rid, p) for p in fresh] old_pages = 0 if fresh else old_pages + 1 if len(page) < 100 or old_pages >= 2: # newest first; two whole pages before the window end the repository break skip += 100 sys.stderr.write("%d pull requests opened since %s\n" % (len(prs), since.date())) humans = [x for x in prs if not is_bot(x[2].get("createdBy"))] waits, first_by, names = [], {}, {} stuck = dict.fromkeys(REASONS, 0) waited_day = 0 for n, (pid, rid, p) in enumerate(humans, 1): if n % 50 == 0: sys.stderr.write("%d/%d\n" % (n, len(humans))) author = norm(p["createdBy"].get("id")) threads = (c.get("/%s/_apis/git/repositories/%s/pullRequests/%d/threads" % (pid, rid, p["pullRequestId"]), {"api-version": a.api_version}) or {}).get("value", []) start = when(p["creationDate"]) reviews = [] # (time, reviewer id, display name): a vote or a comment by someone other than the author for t in threads: kind = str(prop(t, "CodeReviewThreadType") or "") if "draft" in kind.lower() and not p.get("isDraft"): start = max(start, when(t.get("publishedDate"))) # published from draft: wait counts from here if kind == "VoteUpdate": voter = norm(prop(t, "CodeReviewVotedByTfId")) if voter and voter != author: reviews.append((when(t["publishedDate"]), voter, prop(t, "CodeReviewVotedByDisplayName") or "?")) continue for cm in t.get("comments") or []: who = cm.get("author") or {} if cm.get("commentType") == "text" and not cm.get("isDeleted") and not is_bot(who) \ and norm(who.get("id")) != author: reviews.append((when(cm["publishedDate"]), norm(who.get("id")), who.get("displayName") or "?")) reviews = [r for r in reviews if r[0] >= start] first = min(reviews, default=None) end = when(p.get("closedDate")) if p["status"] != "active" else now if first: h = max(0.0, (first[0] - start).total_seconds() / 3600) waits.append(h) first_by.setdefault(first[1], []).append(h) names[first[1]] = first[2] waited_day += h >= 24 elif not p.get("isDraft") and end and (end - start).total_seconds() >= 24 * 3600: waited_day += 1 if p["status"] == "active" and not p.get("isDraft") and (now - start).total_seconds() >= 24 * 3600: votes = [rv.get("vote", 0) for rv in p.get("reviewers") or []] evals = (c.get("/%s/_apis/policy/evaluations" % pid, {"artifactId": "vstfs:///CodeReview/CodeReviewId/%s/%d" % (pid, p["pullRequestId"]), "api-version": policy_api}) or {}).get("value", []) kinds = [((e.get("configuration") or {}).get("type") or {}, e.get("status")) for e in evals] build_bad = any(s in ("rejected", "broken") and (k.get("id") == BUILD_POLICY or k.get("displayName") == "Build") for k, s in kinds) if build_bad: stuck["build failing"] += 1 elif any(v in (-5, -10) for v in votes): stuck["changes requested (author's turn)"] += 1 elif not reviews and not p.get("reviewers"): stuck["no reviewer asked"] += 1 elif not reviews: stuck["reviewer asked, no answer"] += 1 else: stuck["reviewed, approval still missing"] += 1 def q(vals, f): if not vals: return "-" s = sorted(vals) return "%.1f" % s[min(len(s) - 1, int(round(f * (len(s) - 1))))] st = [x[2]["status"] for x in humans] print("# Stuck pull requests") print() print("Source: %s, pull requests opened %s to %s (UTC)%s, counted on %s. Bots and service accounts left out. " "Reviewers are shown as letters." % (urlparse(a.url).netloc + urlparse(a.url).path.rstrip("/"), since.date(), now.date(), ", project %s" % a.project if a.project else "", now.date())) print() print("## 1. Overview") print() print("| Pull requests by people | Completed | Abandoned | Still open | Bot pull requests left out |") print("|---|---|---|---|---|") print("| %d | %d | %d | %d | %d |" % (len(humans), st.count("completed"), st.count("abandoned"), st.count("active"), len(prs) - len(humans))) print() print("## 2. Time to first review (hours, from opened or published from draft)") print() print("| Reviewed | Median | 75% within | 90% within | Waited a day or more (incl. never reviewed) |") print("|---|---|---|---|---|") print("| %d | %s | %s | %s | %d (%d%%) |" % (len(waits), q(waits, .5), q(waits, .75), q(waits, .9), waited_day, round(100 * waited_day / max(1, len(humans))))) print() print("## 3. Open now and waiting a day or more, by reason") print() print("| Reason | Pull requests |") print("|---|---|") for k in REASONS: print("| %s | %d |" % (k, stuck[k])) print() print("## 4. Who gives the first review (top 6)") print() print("| Reviewer | First reviews | Median hours to first review |") print("|---|---|---|") ranked = sorted(first_by.items(), key=lambda kv: -len(kv[1])) total = sum(len(v) for v in first_by.values()) for i, (_, v) in enumerate(ranked[:6]): print("| %s | %d (%d%%) | %.1f |" % (chr(65 + i), len(v), round(100 * len(v) / max(1, total)), statistics.median(v))) print() print("## 5. Time lost (formula, filled in with your numbers)") print() print("developers x pull requests per developer per week x minutes to get back into a pull request after a wait " "x 4.3 weeks x hourly cost. Example for 50 developers, 3 a week, 30 minutes, US$40 an hour: about 320 hours, " "US$12,900 a month.") print() print("## 6. Every month") print() print("The same report can come every month with what to change: US$350 a month for up to 50 developers, " "US$550 for up to 100, a service separate from the plugin. Write to support@lesstep.com " "(https://lesstep.com/azure-devops-pull-requests/team-report-sample/).") with open(a.letters_file, "w", encoding="utf-8") as f: for i, (who, _) in enumerate(ranked[:6]): f.write("%s\t%s\n" % (chr(65 + i), names.get(who, "?"))) sys.stderr.write("done: %d reads. Names behind the letters: %s (keep it; it is not part of the report)\n" % (c.calls, a.letters_file)) if __name__ == "__main__": if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8") main()