diff --git a/.github/workflows/hygiene.yml b/.github/workflows/hygiene.yml new file mode 100644 index 0000000..3a2e322 --- /dev/null +++ b/.github/workflows/hygiene.yml @@ -0,0 +1,25 @@ +# Weekly report of open issues that probably need a decision (see scripts/issue_hygiene.py). Nothing is closed automatically, +# and nothing is written to an issue: an issue exists for work that a pull request closes. The report is in the run summary, +# and the run fails when it lists something, so GitHub notifies the maintainer. +name: hygiene + +on: + schedule: + - cron: "30 6 * * 1" # Monday, after the time report + workflow_dispatch: + +permissions: + contents: read + +jobs: + report: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + - name: Report + env: + GH_TOKEN: ${{ github.token }} + run: | + set +e + python3 -I scripts/issue_hygiene.py report phorge-fr | tee -a "$GITHUB_STEP_SUMMARY" + exit "${PIPESTATUS[0]}" diff --git a/.github/workflows/pr-governance.yml b/.github/workflows/pr-governance.yml index eae047f..8b5f657 100644 --- a/.github/workflows/pr-governance.yml +++ b/.github/workflows/pr-governance.yml @@ -27,6 +27,10 @@ jobs: PR: ${{ github.event.pull_request.number }} HEAD_SHA: ${{ github.event.pull_request.head.sha }} steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + with: + repository: phorge-fr/.github + path: .org - name: Verify metadata run: | set -euo pipefail @@ -61,3 +65,17 @@ jobs: err "Request a reviewer or add a CODEOWNERS file." fi exit "$fail" + + # Not a check: a reminder, printed in the log and the job summary. An issue that this pull request finishes but does not name + # stays open (the pull request closes only what it names), so list the open sub-issues next to the ones it names. + - name: Open sibling sub-issues + continue-on-error: true + run: | + body=$(gh pr view "$PR" --repo "$REPO" --json body --jq .body) + keys=$(printf '%s' "$body" | grep -Eio '(clos(e|es|ed)|fix(es|ed)?|resolv(e|es|ed)|refs?|part of)[: ]+([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)?#[0-9]+' \ + | sed -E 's/^[A-Za-z ]+[: ]+//' | awk -v r="$REPO" '{ if ($0 ~ /^#/) print r $0; else print $0 }' | sort -u | tr '\n' ' ') + [ -n "$keys" ] || exit 0 + out=$(python3 -I .org/scripts/issue_hygiene.py siblings $keys) + echo "$out" + printf '### Open sibling sub-issues\n\n%s\n' "$out" >> "$GITHUB_STEP_SUMMARY" + if [ "$out" != "No open sibling sub-issues." ]; then echo "::notice title=Does this pull request finish a sibling sub-issue?::$out"; fi diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 80ea5d8..bba4646 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -18,8 +18,10 @@ jobs: - name: Shell scripts run: shellcheck scripts/*.sh - name: Python - run: python3 -I -m py_compile scripts/time_tracking.py scripts/check_docs.py + run: python3 -I -m py_compile scripts/time_tracking.py scripts/check_docs.py scripts/issue_hygiene.py - name: Time parser self-test run: python3 -I scripts/time_tracking.py selftest - name: Docs check self-test run: python3 -I scripts/check_docs.py selftest + - name: Issue hygiene self-test + run: python3 -I scripts/issue_hygiene.py selftest diff --git a/GOVERNANCE.md b/GOVERNANCE.md index 4a4a222..e234668 100644 --- a/GOVERNANCE.md +++ b/GOVERNANCE.md @@ -93,6 +93,16 @@ personal-data handling. Every repository of the organization is licensed under the Apache License 2.0 (a `LICENSE` file at its root), and lists third-party licenses in `THIRD_PARTY_NOTICES.md`. A new dependency is checked for compatibility before it is added. +## Before you open a pull request + +A pull request closes only the issues it names. Before opening one, list the open sub-issues next to the ones it concerns and decide, for each, whether this change finishes it: + +```bash +python3 scripts/issue_hygiene.py siblings /# +``` + +Write `Closes /#N` for every issue it finishes: a pull request always closes at least one issue, and an issue is closed only by a pull request. The `pr-governance` check prints the same list as a reminder, and the `hygiene` workflow lists, every Monday, open issues that look finished in its run summary and fails when it finds some. + ## Documentation Every repository documents itself by the same standard: five page types (tutorial, how-to, reference, explanation, decision), a header on every page, and shared checks in CI. See [the documentation standard](docs/reference/documentation-standard.md) and [how to write and check a page](docs/how-to/write-and-check-a-page.md). diff --git a/scripts/issue_hygiene.py b/scripts/issue_hygiene.py new file mode 100644 index 0000000..772ace2 --- /dev/null +++ b/scripts/issue_hygiene.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +"""Report open issues that are probably finished, or whose tracking is inconsistent. + + issue_hygiene.py report ORG print the report; exit status 1 when it lists something (a failed run notifies the maintainer) + issue_hygiene.py siblings REPO#N [REPO#N ...] open sub-issues next to the given issues (run before a pull request) + issue_hygiene.py selftest + +Three findings, each a question for a person, never an automatic close: + epic-done an open issue whose sub-issues are all closed + siblings-done an open sub-issue whose siblings are all closed + referenced an open issue named by a merged pull request without a closing keyword, + and by no open pull request +""" +import json +import re +import subprocess +import sys + +CLOSING = r"(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)" +SOFT = r"(?:part of|refs?|related to)" +REF = re.compile(rf"\b(?P{CLOSING}|{SOFT})[: ]+(?:(?P[\w.-]+/[\w.-]+))?#(?P\d+)", re.I) + + +def gh(*args): + out = subprocess.run(["gh", "api", *args], capture_output=True, text=True) + if out.returncode: + return None + return json.loads(out.stdout) if out.stdout.strip() else None + + +def refs(body, default_repo): + """[(repo, number, closing)] named in a pull request description.""" + found = [] + for m in REF.finditer(body or ""): + closing = re.fullmatch(CLOSING, m["kw"], re.I) is not None + found.append((m["repo"] or default_repo, int(m["num"]), closing)) + return found + + +def collect(org): + repos = [r["full_name"] for r in gh(f"orgs/{org}/repos?per_page=100&type=public") if not r["fork"] and not r["archived"]] + issues, merged, opened = {}, {}, {} + for repo in repos: + for i in gh(f"repos/{repo}/issues?state=open&per_page=100") or []: + if "pull_request" not in i: + issues[(repo, i["number"])] = i + for pr in gh(f"repos/{repo}/pulls?state=closed&per_page=60") or []: + if pr.get("merged_at"): + for r, n, closing in refs(pr["body"], repo): + merged.setdefault((r, n), []).append((repo, pr["number"], closing, pr["merged_at"])) + for pr in gh(f"repos/{repo}/pulls?state=open&per_page=100") or []: + for r, n, _ in refs(pr["body"], repo): + opened.setdefault((r, n), []).append((repo, pr["number"])) + return issues, merged, opened + + +def findings(issues, merged, opened, subs, parents): + """subs[(repo,n)] = [(repo,n,state)], parents[(repo,n)] = (repo,n) or None.""" + out = [] + for key, issue in sorted(issues.items()): + label = f"{key[0]}#{key[1]} {issue['title']}" + children = subs.get(key, []) + if children and all(s == "closed" for _, _, s in children): + out.append(("epic-done", label, f"all {len(children)} sub-issues are closed: close it, or add what is left")) + parent = parents.get(key) + if parent: + siblings = [c for c in subs.get(parent, []) if (c[0], c[1]) != key] + if siblings and all(s == "closed" for _, _, s in siblings): + out.append(("siblings-done", label, f"all its siblings under {parent[0]}#{parent[1]} are closed")) + soft = [(r, n) for r, n, closing, _ in merged.get(key, []) if not closing] + if soft and not any(closing for _, _, closing, _ in merged.get(key, [])) and not opened.get(key): + out.append(("referenced", label, "named without a closing keyword by merged " + ", ".join(f"{r}#{n}" for r, n in soft[:3]))) + return out + + +def siblings(keys): + """Lines naming, for each issue, the other open sub-issues under its parent epic.""" + lines = [] + for key in keys: + repo, num = key.split("#") + parent = gh(f"repos/{repo}/issues/{num}/parent") + if not parent: + continue + prepo = parent["repository"]["full_name"] + open_ones = [s for s in gh(f"repos/{prepo}/issues/{parent['number']}/sub_issues?per_page=100") or [] + if s["state"] == "open" and (s["repository"]["full_name"], s["number"]) != (repo, int(num))] + if open_ones: + lines.append(f"{key} is under {prepo}#{parent['number']} ({parent['title']}). Other open sub-issues, does this change finish one? " + + "; ".join(f"{s['repository']['full_name']}#{s['number']} {s['title']}" for s in open_ones)) + return lines + + +def report(org): + issues, merged, opened = collect(org) + subs, parents = {}, {} + for (repo, n), issue in issues.items(): + if issue.get("sub_issues_summary", {}).get("total"): + subs[(repo, n)] = [(s["repository"]["full_name"], s["number"], s["state"]) for s in gh(f"repos/{repo}/issues/{n}/sub_issues?per_page=100") or []] + if (p := gh(f"repos/{repo}/issues/{n}/parent")): + parents[(repo, n)] = (p["repository"]["full_name"], p["number"]) + for parent in set(parents.values()): + if parent not in subs: + subs[parent] = [(s["repository"]["full_name"], s["number"], s["state"]) for s in gh(f"repos/{parent[0]}/issues/{parent[1]}/sub_issues?per_page=100") or []] + found = findings(issues, merged, opened, subs, parents) + if not found: + return "No open issue looks finished or inconsistently tracked.", 0 + lines = ["Open issues that probably need a decision (each is a question, nothing is closed automatically):", ""] + for kind, label, why in found: + lines.append(f"- **{kind}** {label}: {why}") + return "\n".join(lines), len(found) + + +def selftest(): + assert refs("Closes #3 and part of phorge-fr/.github#17, fixes phorge-fr/Hangar#9", "o/r") == [("o/r", 3, True), ("phorge-fr/.github", 17, False), ("phorge-fr/Hangar", 9, True)] + assert refs("nothing here", "o/r") == [] and refs(None, "o/r") == [] + issues = {("o/r", 30): {"title": "madr"}, ("o/r", 27): {"title": "epic"}, ("o/r", 5): {"title": "open, referenced"}} + subs = {("o/r", 27): [("o/r", 28, "closed"), ("o/r", 30, "open")]} + parents = {("o/r", 30): ("o/r", 27)} + merged = {("o/r", 5): [("o/r", 9, False, "2026-10-01T00:00:00Z")]} + got = {(k, l.split()[0]) for k, l, _ in findings(issues, merged, {}, subs, parents)} + assert got == {("siblings-done", "o/r#30"), ("referenced", "o/r#5")}, got + assert findings(issues, merged, {("o/r", 5): [("o/r", 11)]}, subs, parents)[0][0] == "siblings-done" + print("ok") + + +def main(): + if sys.argv[1:] == ["selftest"]: + return selftest() + if sys.argv[1:2] == ["siblings"]: + print("\n".join(siblings(sys.argv[2:])) or "No open sibling sub-issues.") + return + if len(sys.argv) < 3 or sys.argv[1] != "report": + sys.exit(__doc__) + text, count = report(sys.argv[2]) + print(text) + sys.exit(1 if count else 0) + + +if __name__ == "__main__": + main()