Have you ever branched off of master, done some work, committed, pushed, and opened a pull request only to find out your code belongs in some other long-running branch?

What do you do? Delete your branch and rewrite your code? Stash it and apply onto a new branch? Cherry pick your commits to a new branch?

How about git rebase onto?

I don’t know what your git workflow looks like, but just to start with an easy example, let’s say your server runs the production branch and normal development happens against master. You’ve opened a PR against master, but now you’ve been asked to make it a hotfix into production. There are several commits in master (and thus, on your branch) that are not ready for prime time. How do you fix it in one command?

git rebase --onto production master

The syntax is just git rebase –onto [target-parent] [current-parent]. target-parent and current-parent can be any git ref.

This, of course, results in a non-fast-forward update, so in order to push your changes, you’ll need to do one of two things:

  1. If your organization doesn’t frown on it, use the force! git push --force origin yourbranchname
  2. If you or your organization are uncomfortable with force pushing, you can rename the branch before pushing. git branch -m yournewbranchname

A couple last words. Never, ever force push a shared branch. It will cause problems for someone else and everyone will hate you. Because git rebase onto requires force pushing, don’t do that on a shared branch either. But really, why would you ever do either one in the first place!? You shouldn’t be committing directly to a shared branch anyway. If you write all of your code in personal topic branches that get merged into the shared branches, you can use cool things like git push force and git rebase onto. This is why we can have nice things.

Also, git rebase can be somewhat dangerous if you don’t know what you’re doing. More to your sanity than your code, but still. Make sure you know what to do if you fuck things up.