I just got tired of seeing the huge list of branches whenever I do git branch
. 99% of these branches are already merged and the remote branch already gone. So, once in a while, it’s good to do some housekeeping with your repositories. Note that everything below does not affect the remote repository at all. It only cleans up your local repository.
1. Prune local branches
Delete all local branches that have been merged, except for develop
, master
or staging
git branch --merged | grep -vE 'develop|master|staging' | xargs git branch -d
2. Prune remote branches
Delete all remote branches you still keep track of, which no longer exist in the remote origin
git fetch --prune
3. Clear reflog
Clear all reflog entries
git reflog expire --all --expire=now
4. Garbage collection
Run garbage collection process aggressively
git gc --prune=now --aggressive
To make it easy to run all the actions above, we can add everything under an alias in .gitconfig
.
[alias]
housekeeping = \
!git branch --merged | grep -vE 'develop|master|staging' | xargs git branch -d && \
git fetch --prune && \
git reflog expire --all --expire=now && \
git gc --prune=now --aggressive
Now, we can run git housekeeping
every once in a while to feel good while your repository gets cleansed thoroughly.
$ git housekeeping
Deleted branch feature/cross_region_orders (was 62bfae1).
Deleted branch feature/cross_region_quotation (was 4d823d9).
Deleted branch feature/out_of_service_area_orders (was 80de5c3).
Deleted branch feature/remove_dhl_hardcode (was 265f644).
Deleted branch feature/store_google_response (was f9f8b71).
From bitbucket.org:pick-up/address_service
- [deleted] (none) -> origin/feature/close_redis
- [deleted] (none) -> origin/feature/cross_region_orders
- [deleted] (none) -> origin/feature/discard_google_parts
- [deleted] (none) -> origin/feature/remove_dhl_hardcode
- [deleted] (none) -> origin/feature/th-region
- [deleted] (none) -> origin/hotfix/2.25.2
- [deleted] (none) -> origin/hotfix/2.29.1
- [deleted] (none) -> origin/release/2.27.0
- [deleted] (none) -> origin/release/2.28.0
- [deleted] (none) -> origin/release/2.28.1
Counting objects: 2194, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (2171/2171), done.
Writing objects: 100% (2194/2194), done.
Total 2194 (delta 1473), reused 614 (delta 0)
If you have multiple repositories, you can even consider using gita. With gita, we can do gita super housekeeping
to perform housekeeping on all our repositories in one go.