If you have ever worked on a team project, you probably have some experience with Git, creating branches and making commits.
Working on a branch is a safe way to make changes on the code without affecting the main branch. But what about commits that you regret about?
There would be 2 options to solve that:
- Undo the changes you made and pushing them back to your branch.
- Using git rebase interactive commit.
In a previous post, I talked about a scary command: git rebase. Scary just because it was new but also very useful. I can say that git rebase interactive is also very useful as it helps keeping a clean repo history.
Let's say that I committed some changes, kept working on a project and now I realized that the changes I did some commits ago were not really necessary. Instead of just undoing the code changes (they would still be visible on my repo's history), I could simply remove that commit as it had never happened. How to do that?
Let's first check my list of commits with the following command:
git log --oneline
All these commits have an ID, a description and are displayed in a bottom-top order. Let's say I am not very proud of the commit with the 07a1629 ID (render list). How can I remove it? I need to select 1 commit before my βfailed commitβ:
git rebase -i 9e6a8ea
This way I will get a shorter list of commits including the one I want to remove. Now I only need to select the desired commit by placing my cursor on it:
By pressing βdβ twice the commit will disappear (this is specific for Vim as text editor):
If by any chance you need to stop git rebase, you can type:
git rebase --abort
Now we only need to save changes with :wqa and push them to our branch with:
git push origin mybranchname --force-with-lease
This command won't overwrite my work on the remote branch.
Top comments (1)
This command will override any changes on remote that your local repository is aware of. The difference with force pushes:
--force
βpush goes through always, no questions ask,--force-with-lease
βpush is blocked, if there are some commits on remote branch that you don't have locally. Most likelyβsome work done by your colleagues