Skip to content

Instantly share code, notes, and snippets.

@btgoodwin
Created August 8, 2024 13:40
Show Gist options
  • Save btgoodwin/4a3651ab9cd002dc733275dbb28a537a to your computer and use it in GitHub Desktop.
Save btgoodwin/4a3651ab9cd002dc733275dbb28a537a to your computer and use it in GitHub Desktop.
How to: rebase feature branch off remote that is repeatedly force-pushed

Let's say you have a feature branch based off a different feature branch. Someone force-pushes against that branch and now your branch cannot be merely rebased or even merged against that branch because all those mismatched commits end up being treated as if they're actually yours (when they weren't). A potential recourse is this:

git fetch <remote>
git rebase --onto <remote>/<upstream branch> \
    <local feature branch>~N \
    <local feature branch>

The value of N is the number of commits in your local branch that are your extensions to that remote branch. So if you originally based off the remote branch and added 6 commits, N = 6.

The above command has the effect of being like using format-patch HEAD~6 to get the last 6 commits as a patch, then doing a hard reset of the local branch against the upstream remote, followed by finally using git am to apply those patches.

In either case, if your branch has already been pushed to the remote, you will have to force-push these changes over your own branch. If you know anyone is using your branch as an upstream base: be nice and let them know about the above command.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment