How to perform a rewrite of changes on the main branch?
sobes.tech AI
Answer from AI
Use git revert or git rebase (in "interactive" mode, or git rebase --onto for more complex scenarios) followed by git push -f.
git revert creates a new commit that undoes the changes from specified commits. It is safer as it preserves history.
# Revert last commit
git revert HEAD
# Revert specific commit by hash
git revert <commit-hash>
# Revert a range of commits (excluding the last)
git revert <start-hash>..<end-hash>
# Revert a range of commits (including both)
git revert -n <start-hash>^..<end-hash>
# Revert changes applying them as a single batch without creating separate commits for each
git revert -n <commit-hash-or-range>
# Commit the revert
git commit -m "Revert changes"
git rebase allows rewriting history. It can be used to delete, squash, or reorder commits. Use with caution, especially on shared branches.
# Start an interactive rebase for last N commits
git rebase -i HEAD~N
# In the editor, change 'pick' to 'drop' for commits to delete.
# Using rebase --onto: move commits A, B, C from branch feature onto master,
# ignoring commit D that was on feature.
# Current branch: feature
# X -- Y -- Z -- D -- A -- B -- C (feature)
# /
# W (master)
# Goal: X -- Y -- Z -- W -- A -- B -- C (master)
git rebase --onto master D feature
# Where:
# master - target branch
# D - commit before which to exclude from move
# feature - source branch
After applying git revert or git rebase, force push is needed (git push -f or git push --force-with-lease) because local history diverges.
# Force push after rebase
git push -f origin main
# Safer force push
git push --force-with-lease origin main
Important: Rewriting history on shared branches (main) is highly discouraged as it can disrupt other developers. Use git revert mainly. git rebase on main is only for exceptional cases with full understanding of consequences, usually after team agreement.