How to undo local operation in Git?

Have you ever blown your project after merging local and remote changes? I have… Fortunately, I used Git and had an opportunity to undo local operation.

Recently I have described how to undo one type of operation – commit. This article presents how to undo various types of operations on a local repository and why it is useful.

Real-life situation

Someday I was working on my feature branch and I realized it needs master’s commits. Therefore I did git rebase master and resolved all conflicts. Then I run the project in Unity Editor and the editor crashed. I resolved conflicts of a scene file in the wrong way. Unity Editor saves scenes in YAML format which is not easy to read, so I was not able to find the issue. I had to undo these changes.

Undo local operation – solution

Do you know git log command? It displays a history of a local repository commits. In one log there is a commit’s message, creation time, author and hash. The hash is a unique identifier of a commit.

git log undo local operation

A similar command is git reflog. It displays logs either, but a log presents information about an update of HEAD. HEAD is a reference to the tip of a current branch. Such operations like commit, rebase, pull, checkout etc. update HEAD, because they change set of commits in a local repository, so a tip of a current branch will change.

git reflog undo local operation

In a above case we will see that somebody has done some changes and has done a commit. Let’s remove these changes by using reflog.

git reset –hard 0ffe661

git reset –hard removes a commit as well as a local tracked changes. The number next to the command is a hash of an operation that is desired the last operation in a local repository.

git reflog after reset

As you can see in the above screen, git reset –hard does not remove a log from reflog but it adds a new one. Reflog tracks a whole history of HEAD updates.

Now we have the desired situation – commit does not exist and changes either.

Conclusion

I use git reflog as a last resort because often using it would ruin history. History would be more complex and unreadable as a result. These would cause dangerous mistakes.

0 0 vote
Article Rating
Share on
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Izabela
Izabela
February 12, 2019 6:47 pm

Very helpful article! Thanks!