Assuming any pre-receive hooks on the server accept the push, this will always succeed:
git push --force
Whereas this runs a specific client-side check before proceeding:
git push --force-with-lease
You can run the specific check yourself manually. Here's the "lease-checking" algorithm:
Figure out your current branch.
Run git for-each-ref refs/remotes
. Take note of the commit-id your git client thinks corresponds to the upstream state of your current branch.
E.g., if you are on branch "foo", take note of the commit-id associated with "refs/remotes/origin/foo".
Determine the actual commit-id of the remote branch on the upstream git server right now.
Only let the "git push" proceed if the commit-ids you extracted from step 2 and step 3 agree. In other words, only proceed if your local git clone's notion of upstream agrees with actual upstream.
There's a sad implication here: since git fetch
updates all refs under "refs/remotes/origin/*" to their latest versions, this combination of commands is essentially identical to git push --force
:
git fetch
# The command below behaves identically to "git push --force"
# if a "git fetch" just happened!
git push --force-with-lease
To work around this inherent weakness in git push --force-with-lease
I try to never run git fetch
. Instead I always run git pull --rebase
whenever I need to sync with upstream, since git pull
only updates a single ref under refs/remotes, keeping the "lease" of --force-with-lease
useful.
git help push
has use-cases explaining its purpose (basically to keep you from trashing a change someone just pushed up). What's a little unclear to me is how the remote tracking branch works. But presumably typically it's going to need to look exactly how it looked last time you did afetch
orpull
with no new commits. – zzxyz Oct 15 '18 at 19:51--force-with-lease
is similar to that of compare-and-swap instructions on modern CPUs: the one who wants the swap to occur supplies the expected value and the new value. The system doing the swap compares the expected value with the true current value, and does the swap if and only if the two are equal. Withgit push
, the expected value is whatever is in the remote-tracking name, e.g.,git push --force-with-lease origin X
sends your ownorigin/X
along with the new desired value;origin
's Git tells you if it did the exchange, or not. – torek Oct 15 '18 at 20:28origin
did the exchange, you are done. If not, you can rungit fetch origin
to pick up the new current value, rework your changes if needed, and run another force-with-lease compare-and-swap to try again. – torek Oct 15 '18 at 20:29