Jason's Braindump

Make Git Repository Smaller

Background

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?

Solution

  1. Get the commits which you need to keep, like the master branch 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 3f1d63a will be used in the following step.

  2. Checkout an orphan branch from the first commit you want to keep(as the commit 3f1d63a from above):

    git checkout --orphan 2021 3f1d63a
    git commit -m 'init commit'
    

    Now the 2021 branch will only contains the commits changes starting from 3f1d63a.

  3. Rebase1 all the last commits starting from 3f1d63a on master branch, reapply them on top of the 2021 branch, and push 2021,

    git rebase --onto 2021 3f1d63a master
    git push origin 2021
    
  4. Remove the unused local branch, like master branch,

    git branch -D master
    
  5. 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. --aggressive will help more time optimizing it.

  6. 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.

Reference

Read more


  1. Refer to https://git-scm.com/docs/git-rebase for the git rebase - Reapply commits on top of another base tip. ↩︎