TIL git force push without losing remote refs
Force pushing in git is usually a practice frowned upon. Let's look at a scenario, say I'm not on the last changes of a branch and change the tree from A->B to A->D and force push it.
A -> B (My view of origin)
A -> B -> C (Teammate's commit C pushed to origin)
A -> D (Force pushing D causes C to be dropped)
Change C which was present in origin is lost and what's worse is when other's working on the code pull from origin they lose the changes in C silently. The only way to recover commit C is using the reflog.
While force pushing is frowned upon when doing branch based development and the current changes are to be rebased a force push is needed as the branches reference changes. The alternative to this would be to add a merge commit in the branch but this is a separate commit.
Alternatively one can use git push --force-with-lease this is a safer version for --force which will protect all remote refs that are going to be updated by requiring their current value to be the same as the
remote-tracking branch we have for them.
Further Reading
- https://git-scm.com/docs/git-push#Documentation/git-push.txt---force-with-lease