How to restore overwritten Git commits when multiple developers are pushing changes simultaneously
Consider the following scenario. Multiple developers work on one feature branch of a project. Developer A pushes commits into the feature branch, developer B oversees that his local repository is behind origin, force pushes his commits and as a result overwrites the commits from Developer A. Developer A pulls the changes and his commits are now gone. Can Developer’s A missing commits be restored and how?
The problem
The force push (git push -f
) by Developer B caused the origin branch to lose the commits made by Developer A. This situation can be quite alarming as it seems like the work done by Developer A is lost. However, Git provides tools to recover from such scenarios.
The solution
-
Using git reflog To recover the lost commits, developer A has to use the
git reflog
command on his local machine. git reflog records updates to the tip of branches and other references. We can see the history of changes, as a list, including the commits that were overwritten by the force push. -
Identifying the Lost commits. From the reflog output, we identify the commit IDs of the lost commits.
-
Re-adding the commits. Using the commit IDs, we re-added the lost commits to the feature branch. This can be done using git cherry-pick or by creating a new branch and merging the changes.
Using cherry-picking:
git cherry-pick <commit-id>
Or with the help of an extra branch, where
<commit-id>
is the latest lost commit and from the extra branch merge into the common feature branch:git checkout -b recovery-branch <commit-id>
Lessons Learned from our mistake
-
Always Pull Before Pushing: Ensure that you pull the latest changes from the branch before pushing your changes. This helps to avoid conflicts and potential loss of work.
-
Avoid Force Pushes: Use force push (git push -f) with caution. It can overwrite changes and lead to loss of commits.
-
Communication is Key: Effective communication within the team can prevent such issues. Make sure everyone is aware of the best practices and the current state of the branch.