Sunday, August 4, 2019

Remove commit history in git

Have you ever had a need to clean up all the history in the git repository? I have. I dealt with this old fashioned way until I started interacting with the command line.  The old fashioned way is to create a new repository and update files and replace the old with a new one. In this article, I am going to show how to clean the commit history in git using tools and technique using command lines.  

Method 1: Re-init the repository

In this method, I remove and recreate the git and modify the origin and then I can push the code to remote. The following set of commands can be used:
$ rm -rf .git
$ git init
$ git add .
$ git commit -m "Starting Commit"
$ git remote add origin [......]
$ git push -u --force origin master

Method 2: Alter the branch


In this method, I initially create a temp branch, add all the files to that branch, delete the old branch and then rename the current branch to master and then push the changes to remote. Following sets of commands can do the job. 
$ git checkout --orphan temp
$ git add -A
$ git commit -am "Starting Commit"
$ git branch -D master
$ git branch -m master
$ git push -f origin master

Method 3:  Squashing the commits 

In this method, I combine all the commits into one which is known as squashing. For example, if I have 25 commits since the beginning, then I can combine all commits into one by using the following steps for squashing commits into one and amending the commit message:
$ git rebase -i Head~25
$ #edit the commits mannually
$ git commit –amend

No comments:

Post a Comment