Make Git Repository Smaller
I’ve got a git repository that I make automated commits multiple times a day, but now the local git repository is getting bigger and bigger. I’m wondering what the easiest way would be to slim down my local repository. Is there a way to remove older commits to slim down my repository size?
Get the commits which you need to keep, like the
masterbranch starting from this year,
git log --oneline --since="2021-01-01" master
Then you will get the commits like below,
d1fc497 (HEAD -> master, origin/master, origin/HEAD) message5 ac89b87 message4 8c3e839 message3 d4ffc42 message2 3f1d63a message1
The first/older commit
3f1d63awill be used in the following step.
Checkout an orphan branch from the first commit you want to keep(as the commit
git checkout --orphan 2021 3f1d63a git commit -m 'init commit'
2021branch will only contains the commits changes starting from
Rebase1 all the last commits starting from
masterbranch, reapply them on top of the
2021branch, and push
git rebase --onto 2021 3f1d63a master git push origin 2021
Remove the unused local branch, like
git branch -D master
Cleanup unnecessary files and optimize the local repository,
git gc --prune=now --aggressive
The above command will remove all refs and inaccessible commits in the repository which are older than two weeks.
--aggressivewill help more time optimizing it.
Git has a feature called reflog that helps to track Git refs in the local repo, it has an internal garbage collection mechanism to remove old refs in Git, but there is also a manual mechanism to remove old refs.
git reflog expire --expire=1.month.ago
The above command will remove all refs that are older than one month, you can mention whatever value you feel safe.