HeadlinesBriefing favicon HeadlinesBriefing.com

Rewriting Remote Git History with reset and force-with-lease

DEV Community •
×

When a commit is mistakenly pushed to a remote repository, developers can rewrite history to move the branch back to an earlier point. The standard workflow involves checking out the branch, fetching the latest state, performing a hard reset to the desired commit, and pushing with --force-with-lease. This effectively removes later commits from the branch's visible history, restoring it to a previous state.

The process requires caution, especially on shared branches. Rewriting history disrupts collaborators who may have based work on the now-obsolete commits. Using --force-with-lease is safer than a standard force push because it checks if the remote branch has moved since the last fetch, preventing accidental overwrites of other developers' work. This makes it the preferred method for controlled history rewrites.

For targeted fixes, you can reset to a specific commit SHA or use `HEAD~N` to remove the last N commits. While powerful, this technique should be reserved for branches where the impact is understood. After a remote rewrite, other developers must reconcile their local history, often via rebase or reset, to align with the new branch state.