Skip to content

Instantly share code, notes, and snippets.

@adamchainz
Created February 24, 2025 11:16

Revisions

  1. adamchainz created this gist Feb 24, 2025.
    60 changes: 60 additions & 0 deletions gh-delete-merged-branches.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,60 @@
    #!/usr/bin/env uv run
    # /// script
    # requires-python = ">=3.13"
    # ///
    import json
    import subprocess


    def main(argv=None) -> int:
    query = """
    query {
    repository(owner: "{owner}", name: "{repo}") {
    pullRequests(states: MERGED, first: 100, orderBy: {field: UPDATED_AT, direction: DESC}) {
    nodes {
    headRefName
    }
    }
    }
    }
    """

    pr_data = subprocess.run(
    [
    "gh",
    "api",
    "graphql",
    "-F",
    f"query={query}",
    ],
    capture_output=True,
    text=True,
    check=True,
    )

    data = json.loads(pr_data.stdout)

    # Get the list of local branches once and split it into a set
    local_branches = subprocess.run(
    ["git", "rev-parse", "--symbolic", "--branches"],
    capture_output=True,
    text=True,
    check=True,
    ).stdout.splitlines()
    local_branches_set = set(local_branches)

    for pr in data["data"]["repository"]["pullRequests"]["nodes"]:
    branch = pr["headRefName"]

    if branch in local_branches_set:
    print(f"Deleting local branch: {branch}")
    subprocess.run(
    ["git", "branch", "-d", branch],
    check=True,
    )

    return 0


    if __name__ == "__main__":
    raise SystemExit(main())