loading...

Git: rebasing

ricardomol profile image Ricardo Molina ・2 min read

Source: https://dev.to/maxwell_dev/the-git-rebase-introduction-i-wish-id-had

Let’s say when you created your branch off of the master branch, the master branch was on commit #1. Every commit in your branch was layered on top of commit #1. When you’re ready to merge your branch, you discover other developers made changes and the most recent commit is commit #5.

Rebasing is taking all your branch’s commits and adding them on top of commit #5 instead of commit #1. If you consider commit #1 as the “base” of your branch, you’re changing that base to the most recent one, commit #5. Hence why it’s called rebasing!

A straightforward rebase has a pretty simple command structure: git rebase <branch>. branch is the one you’re rebasing off of. So here you’d run git rebase master. Assuming there’s no conflicts, that’s all the rebase needs!

The rebase itself technically removes your old commits and makes new commits identical to them, rewriting the repo’s commit history. That means pushing the rebase to the remote repo will need some extra juice. Using git push --forcewill do the trick fine, but a safer option is git push --force-with-lease. The latter will alert you of any upstream changes you hadn’t noticed and prevent the push. This way you avoid overwriting anyone else’s work, so it’s the safer option.

If you’ve dealt with merge conflicts before, rebase conflicts are handled essentially the same way. Running git status will tell you where the conflicts are, and the two conflicting sections of code will be next to each other so you can decide how to fix them.

Once everything is fixed, add and commit the changes like you would a normal merge conflict. Then run git rebase --continue so git can rebase the rest of your commits. It’ll pause for any more conflicts, and once they’re set you just need to push --force-with-lease.

There’s two lesser-used options you could also use. One is git rebase --abort, which would bring you back to before you started the rebase. It’s useful for unexpected conflicts that you can’t rush a decision for. Another is git rebase --skip, which skips over the commit causing the conflict altogether. Unless it’s an unneeded commit and you’re feeling lazy, you likely won’t use it much.

Discussion

markdown guide