Recently I was searching for a safe way to remove the commit history of a git project. It was a project, developed in a private space that I had planned to release to the public. Unfortunately, especially with private repositories, you find old commits with either problematic statements in the description or with problematic content in the commits. This could be a description like “Hopefully this commit is fixing this strange and annoying issue”, it could be a password in one of the commits, snippets you’re not allowed to distribute and so on and so forth. Usually, the easiest way is to create a new repository and upload the content you would like to distribute. The problem with this approach is, you need to change your repository name (renaming causes too many other issues). If you would like to keep your repository name, you need a slightly different approach like this:
git checkout --orphan latest_branch
git add -A
git commit -s -m 'Initial commit'
git branch -D main
git branch -m main
git push -f origin main
The mentioned sequence creates a new branch with one initial commit only, deletes the main branch and renames the newly created branch back to “main”. This is clean and doesn’t break the remote repositories from other developers.