Clean and reset the git commit history
You have an existing repository for your project which already has many commit history. Someday you need to reset your git log history because of some reasons such as rewriting the entire project from scratch or you just want to clean and making your git commit history tidy. You can try the methods below.
The first method only creates a new branch without the previous commit history. It doesn’t actually delete the history and still retain the previous history in a different location. If you really want to delete the actual git history data, try the second method instead.
First method
-
Ensure you are in the latest updated branch in the repository. Let’s assume the branch is the
main
branch. -
Create and move to a new orphan branch. This branch will be used as a replacement for the main branch later.
Orphan branch is a branch with no parent commit history. That means, if you type
git log
, then git will tell you if thenew-branch
you just created does not have any commits yet. -
You need to add all files in our project to the git again.
-
Commit your files. This will be your initial commit history in the current branch.
-
Delete the old
main
branch. -
Rename the current branch to
main
. -
Finally, force update to the
main
branch in your remote repository. The orphan branch becomes your latest branch.
Second method
-
Same with the first method. Ensure you are in the latest updated branch which I will assume the
main
branch. -
The git commit history is stored in the
.git
folder. If you really want to reset your git history data from scratch, you may delete that.git
folder. You should think carefully before doing this. This action is irreversible. -
After the
.git
folder is removed. You need to reinitialize the repository. This command will reinitialize the repository with theinit
git command and create an initial branch namedmain
. -
You need to add all files in our project to the git after reinitialization.
-
Commit your files. This will be your initial commit history.
-
Add the remote repository url. This example will use GitHub for the remote repository.
-
Finally, force update to the
main
branch in your remote repository.
If you want to reset the git history but still keep the git data, the recommended way is by using the first method. However, if you really want to reset and create a fresh git data. You need to follow the second method.