Overwrite already pushed changes with Git

WARNING: the operations described in this article can irretrievably delete vast amounts of work. Only consider after you have securely backed up the original repository. Don’t destroy your company or job by irretrievably erasing person-years of work!

Why not overwrite Git history?

Overwriting Git history is usually NOT a good idea, and is usually an anti-pattern. Even more so, overwriting previously git push changes will make everyone else need to re-clone your repository, which can be really annoying, especially if they have their own branches. So only consider overwriting Git history when there is a really compelling reason and you understand the possible consequences, even when everything goes right and especially if things go wrong.

Overwrite Git history

Git development patterns commonly used for large repos like CMake may require contributors to overwrite “oops/typo” commits to avoid cluttered Git history. This Git development pattern usually has the contributor:

  1. Fork the original repo
  2. Make a feature branch in the fork, allowing maintainers to edit

    git checkout -b myfeature
  3. CI pipelines validate/lint contributor pushes

    git push -u origin myfeature
  4. If CI errors, require overwriting and force-pushing correction

    git commit -am "fixup typo"
  5. Squash oops/typo commits

    git rebase -i origin/myfeature~2 myfeature

The “~2” indicates how far back to allow squashing. If the oops was farther back in history, increase “2”.
Squash the commit(s) by changing “pick” to “s” and then saving in the interactive editor that pops up in terminal. 6. Once you’re confident changes are correct, force push.