It happens, although very few time, when we accidentally push sensitive data to remote git repository, such as passwords etc.
Having sensitive data is not good thing, as in case someone get access of the repository, then can do some harmful things.
We will use a tool called “BFG” (https://rtyley.github.io/bfg-repo-cleaner/).
First you need to remove all the sensitive data from your file and perform a commit on local repo. After that you will need to download the bfg tool from this link: https://rtyley.github.io/bfg-repo-cleaner/
This is a Java based tool, so you will need Java to be installed on your system. After downloading this tool, either add it in your system path, or just copy it to your repository folder (later you will need to delete it).
Now, run below command to remove the commit history of the file which had sensitive data:
java -jar bfg-1.14.0.jar --delete-files <YOUR_FILE_NAME>
java -jar bfg-1.14.0.jar --delete-files appsettings.json
At the time of writing this post, bfg version is 1.14.0, thats why you see that version numer here. In above example I am removing the appsettings.json file history, as I am using asp.net core project.
When you will run this command, then it will leave the latest commit and remove the older commits of this file. After that you will need to push the changes forcefully on remote server.
git push --force
Now on your remote git repository, for example GitHub, if you see the history of this file, you will see only one commit, which is the latest one.
Actually it removes the earlier commit and add a new commit if for all earlier commits where this file was present.
Note: beware, if you have multiple files with same name in your repo, then this will also remove those files history also, for example, in my Visual studio solution I have three projects that have appsettings.json file, and this tool removed history of those files also, because this tool doesn’t take file path as argument, it takes the file name. I am looking into the solution for such case, and will update if find any, and if you know then Please let me know.