Tuesday, June 2, 2015

Git merge to restore lost commit

Lets start from a status like following,
udara@udara-home:~/workspace/USSD-Reminder$ git status
# On branch new-feature
# Your branch is ahead of 'origin/new-feature' by 1 commit.
#   (use "git push" to publish your local commits)
#
nothing to commit, working directory clean
So here my local branch is one commit ahead from the remote. Assume mistakenly I did a git reset --hard HEAD^. This will remove my last commit and now I need to find a way to undo my last command.

When we issue the git reset command, commit goes to dangling state and commit is not going to remove permanently. luckily !!

IMPORTANT:

Make sure you don't run git gc until you restore the lost commit. git gc command will trigger the garbage collector and remove all commits which are in dangling state.


Let's start the restoring process....

1. We need to find the SHA1 of the deleted commit so we can bring it back.
 git fsck --lost-found
git fsck command will list down all commits which are in dangling state.
udara@udara-home:~/workspace/USSD-Reminder$ git fsck --lost-found
Checking object directories: 100% (256/256), done.
Checking objects: 100% (16/16), done.
dangling commit 5e3079cc8ac9e15cbfc1f513d249678c0893feab
So we have the SHA1 of the commit which needs to restore.

2. Lets merge this commit.
git merge <SHA1>
udara@udara-home:~/workspace/USSD-Reminder$ git merge 5e3079cc8ac9e15cbfc1f513d249678c0893feab
Updating 0ffdab3..5e3079c
Fast-forward
 config.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
Now if we run the git status command it should mention that my local branch is one commit ahead than the remote.

No comments:

Post a Comment