Git - Cleaning Commit History
Greetings!

Sometimes you need to completely reset the repository history - when you accidentally pushed secrets, huge files, or simply need a clean history.

In this short HowTo we will consider one of the options for cleaning the Git repository history.

The Essence of the Method

For this purpose we will use an orphan branch, which has no parent in the history. We create it with the current state of the files, delete the old history, rename it to main and push with force.

Situation: we committed something to the repository that shouldn’t be there 😨:

Or simply cluttered the project history:

Cleaning the Commit History

In the “problematic” repository we create a new branch without history, add all current contents and commit:

BASH
git rm --cached .env
echo .env >> ./.gitignore

git checkout --orphan new-branch
git add -A
git commit -m "Initial commit"
Click to expand and view more

Delete the old branch and rename the new one to main (or master if you use it):

BASH
git branch -D main
git branch -m main
Click to expand and view more

Send to the remote repository with the force flag (warning: this will rewrite the history on origin):

BASH
git push -f origin main
Click to expand and view more

Afterword

The method is harsh, but it works 😌. If you need more careful cleaning (for example, remove only certain commits or large files), look at git filter-branch or git-filter-repo - they are slower, but more flexible.

Thank you for reading. Good luck! 🐧

Useful Materials

Copyright Notice

Author: Ivan Cherny

Link: https://r4ven.me/en/linux/git-ochistka-istorii-komitov/

License: CC BY-NC-SA 4.0

Blog materials may be used with attribution to the author and source, for non-commercial purposes, and under the same license.

Start searching

Enter keywords to search articles

↑↓
ESC
⌘K Shortcut