Cleaning Up Your Local Git
Do you work with a lot of branches in git
? Do you ever find the number of branches you have checked out locally is too d*mn high? Well, never fear! Powershell is (again) here to help make this problem easier. Behold!
# fetches all remote branches and removes stale, tracked refs
git fetch --prune
# delete local branches that have been merged to main
# NOTE: Change this to *master* if you're still using that as your mainline branch
git branch --merged | %{$_.trim()} | ?{$_ -notmatch 'main'} | %{git branch -d $_}
# remove stale refs (local refs to branches that are gone on the remote)
git remote prune origin
Not going to lie, the first time I ran this and saw it removing hundreds of branches, it was brown trousers time. However, I’ve come to trust it and I run it pretty frequently. It preserves my in-flight work and only removes things that the git history itself informs us has been removed.
I’ve also incorporated this into my Powershell profile with an alias of gclean
so that I can easily run it at will. Boom!
Leave a Comment