#!/usr/bin/env python3

from subprocess import run, DEVNULL


def get_local_by_upstream():
    info = run(
        [
            "git",
            "for-each-ref",
            "--format",
            "%(upstream:short)\t%(refname:short)",
            "refs/heads",
        ],
        stdin=DEVNULL,
        capture_output=True,
        check=True,
        encoding="utf-8",
    )
    ret = {}
    for l in info.stdout.splitlines():
        parts = l.strip().split("\t")
        if len(parts) == 2:
            ret[parts[0]] = parts[1]
    return ret


def get_remotes():
    info = run(
        ["git", "remote"],
        stdin=DEVNULL,
        capture_output=True,
        check=True,
        encoding="utf-8",
    )
    return set(l.strip() for l in info.stdout.splitlines())


def fetch_remote(remote):
    run(["git", "fetch", remote], check=True, stdin=DEVNULL, capture_output=True)


def prune_remote(remote):
    info = run(
        ["git", "remote", "prune", remote],
        check=True,
        stdin=DEVNULL,
        capture_output=True,
        encoding="utf-8",
    )
    return [line.split()[-1] for line in info.stdout.splitlines() if "[pruned]" in line]


def delete_branch(branch):
    run(["git", "branch", "-d", branch], stdin=DEVNULL)


def main():
    local_by_upstream = get_local_by_upstream()
    remotes = get_remotes()
    for remote in remotes:
        fetch_remote(remote)
        pruned = prune_remote(remote)
        for branch in pruned:
            try:
                delete_branch(local_by_upstream[branch])
            except KeyError:
                pass


if __name__ == "__main__":
    main()
