Overwrite already pushed changes with Git

Overwriting Git history requires caution and care. An unlimited amount of work can be permanently lost in doing so. Git repos should have “offsite” backup that is checkpointed–the backup retains more than just the last copy. Overwriting Git history should normally only be done on “feature” branches, not on the “main” branch.

Overwrite Git history: common Git development patterns may require contributors to overwrite feature branch 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 switch -c 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"
    
  5. Squash oops/typo commits

    git rebase -i HEAD~2 myfeature
    

    The “~2” indicates how far back to allow squashing. To reach farther back in history, increase “2”. Squash the fixup commit(s) by changing “pick” to “f” and then save in the editor that opens automatically.

  6. Once you’re confident changes are correct, force push.


Related: