Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save scmx/f0cf283f33e5e1ac83946453461b9ff2 to your computer and use it in GitHub Desktop.
Save scmx/f0cf283f33e5e1ac83946453461b9ff2 to your computer and use it in GitHub Desktop.
Updating a local diverged git branch to latest remote without reset --hard. #git git checkout -B vs git reset --hard

Updating a local diverged git branch to latest remote without reset --hard

Sometimes you have a branch checked out locally that someone else owns and they do a force push. Perhaps it's during a review when they have pushed all the needed fixups and got them approved. So now they squash and force-push the branch. It's time for you to take a new look at the updated commits, so you checkout the branch and try to update it.

The situation

$ git checkout some-topic-branch
$ git pull
fatal: Not possible to fast-forward, aborting.

What's happening here? Well, the branch has diverged, you have the old commits locally that have been changed on the remote, so you need a way of reseting the some-topic-branch to be same as the version at origin/some-topic-branch.

The naive solution (hard reset)

git reset --hard origin/some-topic-branch

The downside here is that it doesn't just reset the branch, it also resets the working directory (any changed files)

The better solution (recreate the branch)

git checkout origin/some-topic-branch
git checkout -B some-topic-branch

Start by checking out another branch (because you can't delete the branch you're currently on), specifically we checkout the origin version of the branch. And then we run checkout again with -B so that it will recreate the branch if it already exists. So any commits in the branch are thrown away, but the working tree remains untouched!

@kai101
Copy link

kai101 commented May 25, 2018

git checkout -B some-topic-branch

Work well.

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