How to Remove Git Commit History and Credentials Securely

Scenario

If you have ever committed your credentials to GitHub and have many commits after that incident, it can become a significant issue to remove the credentials from the history. One option is to delete the entire commit history. In this tutorial, we will learn how to do that.

Orphan

First, we will create a command to create a new branch with the --orphan flag. This flag is used to create a new branch without the commit history from the current branch. It’s like starting a new branch from scratch (orphan), where the first commit on this branch will be a new root commit.

To do this, please run the following command:

git checkout --orphan orp_branch

After that, add all files to this branch:

git add .

Next, add a commit message, for example:

git commit -m "working in progress"

Once the commit is created, we will delete the previous main branch, which is usually main or master, depending on the branch you are currently using:

git branch -D main

After that, we will rename orp_branch to main:

git branch -m main

Next, force push the changes by adding the -f flag:

git push -f origin main

TLDR

Here are the commands to delete all commit history:

git checkout --orphan orp_branch
git add .
git commit -m "working in progress"
git branch -D main
git branch -m main
git push -f origin main

Conclusion

By following the steps above, you can delete all commit history and start fresh with a new branch. This is an effective solution for removing credentials that were accidentally included in the Git history. Always make sure to double-check the commits you are about to push to prevent similar incidents from happening again.