The top answer is VERY long and didn't even explain it to me. Here's a quicker better explanation.
This is all to avoid races where multiple people are working on the same branch and are force pushing it (e.g. to rebase it).
- Person X fetches
branch
. - Person Y fetches
branch
. - Y adds a new commit and
git push
s it. - X rebases the
branch
andgit push -f
's it (because you have to force push for a rebase).
This will wipe out Y's new commit and X will never know about it. The "slightly better" solution is --force-with-lease
. Now when we get to
- X rebases the
branch
andgit push --force-with-lease
's it.
Git will automatically check that our origin/branch
matches the remote origin/branch
. Since X didn't fetch in the mean time his origin/branch
is still pointing to the original commit (not Y's new commit) so they mismatch and it fails.
The idea is X will see this failure, do a git fetch
and then see Y's commit and know to integrate it.
However there is a flaw! What if X is using an IDE that periodically git fetch
s in the background? His origin/branch
will now match the remote origin/branch
so --force-with-lease
won't stop him and he will still wipe out Y's new commit.
--force-with-lease
assumes you are manually git fetch
ing and checking for new commits afterwards. With IDEs that isn't necessarily the case.
So if you instead --force-with-lease
and --force-if-includes
then Git tries to actually verify that you did integrate Y's new commit into your branch before force pushing.
@torek's answer has things nonsense like this:
If you've never needed it before, you don't need it now. So the shortest answer to "when should I use this" would be "never".
Don't listen to him. This is like saying "if you've never needed to use a seatbelt you don't need it now".
You should always use it. The check for "have you integrated all the commits" may give false negatives very occasionally, but you can check those cases manually if/when they happen.