In the daily use of a version control system, it can happens to commit wrong data or worse, sensitive data; if we are using Git, we can solve this problem with an interactive rebase.
As you know, the rebase is a Git command that allows you to reapply a bunch of commits on the top of another branch; what you need to do is fix the bad commit and reapply, with the bunch of the commits above, to the top of the branch.
So, the first step is the git rebase command with the option -i; this option allows you to have an interactive session where you can choose to edit one of the commits following the commit selected:
git rebase [<commit>] -i
Once the command is executed, and interactive console is showed:
At the top, it’s showed the list of the commits above the commit specified in the rebase command; the first word is the command that you want do do with the commit; in this case, we want to change the a59a72d commit, so we change the command from pick to edit.
Than, confirm this change with a combination of commands:
The console command terminated and now you can make changes to the bad file and fix it, for example web.config.
Once do that, you need to add the file to the Git staging area:
git add Web.config
Commit amend option
Now you can commit these changes; what we need to do is reapply the bunch of commits to the current branch, and we can do that with the amend option of the commit command:
git commit --amend
This option replace the tip of the branch with the new commit.
The next step is continue the rebase process and confirm the fix to the commit:
git rebase --continue
At this point, the local branch tip and the remote branch tip are not the same because of the “commit –amend”; so, if you proceed with a simple git push origin, the command refuse to update the remote branch because the remote reference is not an ancestor of the local reference.
In order to do that, you need to use the –force option, that you can specify for a specific branch by putting the + character before the branch name.
Before do that, keep in the mind the Golden Rule of Rebasing: you never use rebase on public branches, because this command rewrite the history and you can potentially lost the commits of the other developers.
git push origin +[<branch name>]
After that, the local and remote branch will be updated correctly and the bad commit will be fixed.