Little Git Tricks: Get Rid of Commits
If we committed something into a Git repository that should not be there, we could rewrite the history and make it look as it was never there.
I usually try to prevent rewriting the history, especially when I already pushed the changes. Then when we modify the past, everyone in the team needs to do some extra work to catch up.
If this is not a problem or the lesser evil, we can use the following steps to rewrite the Git history.
Find the last commit to keep
We first need to know what commit we want to reset to. In my case I wanted to go back to the beginning of the commits and for that the --reverse flag for git log was a great help. If you search for a commit closer to the last commit, skip that option:
a30c679 Initial commit
2dd687e Update README.md
6dbefd3 (origin/original-manning-do-not-change) Add files via upload
8271e44 fix version to be able to install the requirements
841b9f5 Create ex1.py
410d0db Create ex2.py
e1cf2f0 add more packages
8d80ab2 exclude .env
3a240da Create ex3.py
81191f4 Create ex4.py
62afcd0 (HEAD -> main, origin/main, origin/HEAD) Create ex5.py
Reset to the last commit to keep
When we know the hash of the commit we want to keep, we can reset our repository to that specific commit with this command:
Push the repository
The final step to overwrite the history is to use --force and push our main branch (or the one we work on) to the remote repository:
Total 0 (delta 0), reused 0 (delta 0), pack-reused 0 (from 0)
To https://github.com/****/repo.git
+ 62afcd0...a30c679 main -> main (forced update)
Verify the history
We can now check that the unwanted commits are gone:
Conclusion
Rewriting the history of a Git project is something we can do. But we always should consider if there are no other options, like revert. That is often enough and does not require extra work from anyone else who develops in the same repository. Keep that in mind before you go around and change the history of your Git repositories.