Skip to content

Lean formalization of the Riemann Hypothesis (Alpöge, 2026-11-20) being cleaned up by members of the Lean community.

Python
4.1 KB
Raw Blame
#!/usr/bin/env python3
"""Build CONTRIBUTORS.md from the merged pull requests on GitHub.

Lists everyone with a merged pull request into `main` (both editions: the earlier edition's
pull requests also targeted `main`, and its history is preserved on the `alpoge` branch) or into
`alpoge`, with a link to their merged pull requests. Pull requests from an account in `ALIASES`
are credited to its owner. Bots and the batch pull requests
(`chore: batch ...`), which have no individual author, are left out. Sorted by the number of
merged pull requests, then by login.

Usage: python3 scripts/contributors.py [--pending N ...] > CONTRIBUTORS.md
`--pending` counts open pull requests that a batch is about to merge. Needs `gh`, logged in.
"""
import argparse
from collections import Counter
import json
import subprocess
import sys

REPO = "leanprover-community/riemann-hypothesis"
# Accounts that act for a person ("Bot of @x" on their profile): their pull requests are credited
# to that person.
ALIASES = {"s-celles-bot": "s-celles"}
OWNER, NAME = REPO.split("/")
QUERY = """
query($owner: String!, $name: String!, $base: String!, $after: String) {
  repository(owner: $owner, name: $name) {
    pullRequests(states: MERGED, baseRefName: $base, first: 100, after: $after) {
      pageInfo { hasNextPage endCursor }
      nodes { number title author { __typename login } }
    }
  }
}
"""


def gh_graphql(variables):
    args = ["gh", "api", "graphql", "-f", f"query={QUERY}"]
    for key, value in variables.items():
        if value is not None:
            args += ["-f", f"{key}={value}"]
    return json.loads(subprocess.run(args, check=True, capture_output=True, text=True).stdout)


def merged(base):
    after = None
    while True:
        data = gh_graphql({"owner": OWNER, "name": NAME, "base": base, "after": after})
        page = data["data"]["repository"]["pullRequests"]
        yield from page["nodes"]
        if not page["pageInfo"]["hasNextPage"]:
            return
        after = page["pageInfo"]["endCursor"]


def counts(pull_requests):
    tally = Counter()
    for pr in pull_requests:
        author = pr["author"]
        if author is None or author["__typename"] == "Bot":
            continue
        login = ALIASES.get(author["login"], author["login"])
        if login.endswith("[bot]") or pr["title"].startswith("chore: batch "):
            continue
        tally[login] += 1
    return tally


def pending(numbers):
    for number in numbers:
        out = subprocess.run(["gh", "pr", "view", str(number), "-R", REPO, "--json",
                              "number,title,author"], check=True, capture_output=True, text=True)
        pr = json.loads(out.stdout)
        login = pr["author"]["login"]
        bot = pr["author"].get("is_bot") or login.endswith("[bot]") or login.startswith("app/")
        yield {"number": pr["number"], "title": pr["title"],
               "author": {"__typename": "Bot" if bot else "User", "login": login}}


def main():
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--pending", nargs="*", type=int, default=[])
    args = parser.parse_args()
    seen = {}
    for base in ("main", "alpoge"):
        for pr in merged(base):
            seen[pr["number"]] = pr
    for pr in pending(args.pending):
        seen.setdefault(pr["number"], pr)
    tally = counts(seen.values())
    lines = [
        "# Contributors",
        "",
        "Everyone with a merged pull request in this repository, by number of merged pull requests. "
        "The earlier edition's history is preserved on the "
        f"[`alpoge`](https://github.com/{REPO}/tree/alpoge) branch, and its pull requests are "
        "counted here too. This file is generated by `scripts/contributors.py`.",
        "",
    ]
    for login, count in sorted(tally.items(), key=lambda item: (-item[1], item[0].lower())):
        link = f"https://github.com/{REPO}/pulls?q=is%3Apr+is%3Amerged+author%3A{login}"
        lines.append(f"- [{login}](https://github.com/{login}): [{count} merged]({link})")
    sys.stdout.write("\n".join(lines) + "\n")


if __name__ == "__main__":
    main()