Rebasing is one of Git's most powerful and useful features. There are two specific things I learned git rebasing lets you do with the right approach: undoing a rebase, and splitting apart commits.
Undoing a rebase #
A few times, I've done a rebase for the wrong branch or created too many merge conflicts, and it was easier to just undo it with these steps.
git reflogto find the commit right before the rebase was run, and copy its ID.
git reset --hard <commitID>using that commit’s ID bring the repo back to before the rebase.
git push --force-with-leaseto push that version of the repo to the remote, removing all the rebase changes that had been added after.
Using a rebase to split commits #
You may have bulky commits you want to split into several smaller ones, without having to rewrite the code. Rebasing lets you do this.
- Set up an interactive rebase with
git rebase -i <master_branch>.
- On the interactive rebase list, change
editfor the commit you want to split.
- When editing this commit, run
git reset HEAD~. This unstages all the changes from the commit, but still tracks them.
- Add the select code you want, commit it, and repeat until all the code has been recommitted in new commits.
git rebase --continue.
- Repeat steps 2-5 for any other commits you want to split.
- All set! Happy dance.