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:
- Fork the original repo
- Make a feature branch in the fork, allowing maintainers to edit
git checkout -b myfeature
- CI pipelines validate/lint contributor pushes
git push -u origin myfeature
- If CI errors, require overwriting and force-pushing correction
git commit -am "fixup typo"
- 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.
- Once you’re confident changes are correct, force push.