'How do I remove all stale branches from Github?
We have a lot of branches that are inactive (the newest is 7 months old, the oldest is two years ago).
I'd like to remove all of those branches in bulk from the remote if no PR is still open for them.
Should I be using Github's API? Should I be using git using snippets like those provided in this StackOverflow question?
Is there some Github functionality I'm not familiar with that can help organize our repository?
Solution 1:[1]
You can certainly achieve this using the GitHub API, but you will require a little bit of fiddling to do it.
First, use the list pull requests API to obtain a list of open pull requests. Each item in this list contains a ["head"]["ref"]
entry which will be the name of a branch.
Now, using the get all references API, list all of the references in your repository. Note that the syntax for branches in the Git Data API is slightly different than the one returned from the pull request API (e.g. refs/heads/topic
vs. topic
), so you'll have to compensate for this. The references API also returns tags unless you search just the refs/heads/
sub-namespace, as mentioned in the docs, so be aware of this.
Once you have these two lists of branch refs, it's simple enough to work out which branches have no open pull requests (don't forget to account for master
or any other branch you wish to keep!).
At this point, you can use the delete reference API to remove those branch refs from the repository.
Solution 2:[2]
For the 2021 Github's web page, you can right click on the browser after opening the stale branches and run this in the browser java script console.
var stale_branches = document.getElementsByClassName('color-text-danger');
for (var i = 0; i < stale_branches.length; i++) {
stale_branches.item(i).click();
}
or as @MartinNowak has suggested
document.querySelectorAll('button[data-target="branch-filter-item.destroyButton"]').forEach(btn => btn.click())
Solution 3:[3]
I took a different tack from the other answers and just used good ol' git
(and bash) to do the work:
- Retrieve list of all branches using
git branch -r >~/branches.txt
(after settinggit config --global core.pager cat
) - Prune
~/branches.txt
of ones I want to keep - Call
git push <ref> --delete <branch>
on each one ...
for ref_branch in $(cat ~/branches.txt | head -n 5); do
ref="$(echo "$ref_branch" | grep -Eo '^[^/]+')"
branch="$(echo "$ref_branch" | grep -Eo '[^/]+$')"
git push "$ref" --delete "$branch"
done
Note the use of | head -n 5
to give it a try with only 5 at a time. Remove that to let the whole thing rip.
This will likely work on most sh
shells (zsh, etc.) but not Windows; sorry.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | kfb |
Solution 2 | |
Solution 3 | Neil C. Obremski |