Skip to content

Instantly share code, notes, and snippets.

@damncabbage
Last active March 25, 2019 02:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save damncabbage/13808c78ace3054cd5493e3781e859b8 to your computer and use it in GitHub Desktop.
Save damncabbage/13808c78ace3054cd5493e3781e859b8 to your computer and use it in GitHub Desktop.

PSA about Git in case folks haven't run into git push --force-with-lease before: it just saved my bacon (again).

I have a shared branch for a feature my team at work is working on, feature/flub [yes, okay, I've anonymised it]. We've been merging PRs into it.

To incorporate the build-fix changes above, I did this:

$ git checkout feature/flub                # I've been working on other stuff; let's hop over to the shared branch.
$ git pull --rebase origin master          # Take the branch, and pretend we *just* created it off the latest 'master' on GitHub.
$ git push --force-with-lease origin HEAD  # Tell GitHub about the new change.
To github.com:myorg/thing.git
 ! [rejected]              HEAD -> feature/flub (stale info)
error: failed to push some refs to 'git@github.com:myorg/thing.git'

[... head scratching follows.]

"Oh, shit, right. I forgot to pull down the merges that have happened since I last updated my local version of this branch."

$ git fetch origin                      # Get an updated idea of what GitHub has
$ git reset --hard origin/feature/flub  # Reset the local branch to match the remote one, blowing away any local changes I might have.

"Okay, back to what I originally tried..."

$ git pull --rebase origin master  # Just do the same thing as earlier. There are more efficient ways, but this works.
$ tig                              # To double-check it looks fine;. 'tig' is my git browser; 'git log --stat' would also work fine.
$ git push --force-with-lease origin HEAD
Enumerating objects: 85, done.
...
 + abc123def...def456abc HEAD -> feature/flub (forced update)

If you want a more thorough intro to this feature (and other examples of bad situations it saves you from), here's a write-up from https://twitter.com/tarkasteve: https://developer.atlassian.com/blog/2015/04/force-with-lease/

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