Git

Last Updated: 9/5/2023

Undoing a Faulty Merge

  • Sometimes we do a merge and then find out that our code doesn't get compiled, or our application doesn't work. This happens if we don't combine the changes properly. In situations like this, we need to undo the merge, and then remerge.

Reset

  • One option is to remove the commit, as if it was never there, You have to be a bit careful with this solution. Because as part of removing this commit, we are rewriting history, rewriting history is totally fine if this history is local in our repository, but if you have shared our commits with other team members, if you have pushed your commits to a remote repository, then we should not rewrite our history.
  • When resetting the head pointer, we have three options soft, mixed, and hard.
  • We have our working directory, our staging area, and the last snapshot,
  • Reset the head using the soft option. Git is going to have the head pointer point to a different snapshot. But our staging area and working directory are not affected.
  • If we use the mixed option, which is the default option. So we don't have to specify it git is going to get that new snapshot and put it in the staging area as well. So if you have local changes in our working directory, they are not affected, they're going to stay there.
  • If we use the hard option, git is going to take that new snapshot and put in our working directory as well. So all our environments are going to look identical. This is the state that we were in, before we started the merge, all our working environments were identical.
git reset --hard HEAD~1

Revert

  • Another option is to revert it, which means we're going to create a new commit that will cancel all the changes in this commit.
  • We want to revert last commit. The last merge commit has 2 parents 1 on master and another on feature branch.
  • We have to tell git, how we want to revert the changes. we want to revert to the merge commit to the last commit on the master branch before we started the merge. The last commit on master is the first parent of our merge commit, because our merge commit is on the master branch. So the first parent should also be on the master branch.
git revert -m 1 HEAD
  • 1 means first parent that is master