basforge

Search titles, text and the “If it doesn’t work” cases.

    RU

    push --force-with-lease instead of --force

    After a rebase or --amend of a pushed branch you need a forced push. --force overwrites the branch on GitHub even if someone else has pushed there meanwhile. --force-with-lease overwrites only if GitHub has exactly what you saw at your last fetch — otherwise it refuses.

    What it looks like

    You rewrote the last commit (--amend), and meanwhile a colleague pushed theirs. A regular push is refused:

     ! [rejected]        main -> main (non-fast-forward)

    --force goes through and silently deletes your colleague’s commit from GitHub. --force-with-lease compares the branch on the server with your origin/main and, seeing a commit you don’t know about, refuses:

    git push --force-with-lease
    # To github.com:example-user/notes.git
    #  ! [rejected]        main -> main (stale info)
    # error: failed to push some refs to 'github.com:example-user/notes.git'

    stale info means GitHub has something other than what you saw. Run git fetch, see what arrived with git log HEAD..origin/main, integrate it (Branches in git) and push again.

    Where the lease doesn’t save you

    An editor with automatic fetch (VS Code does it in the background if git.autofetch is on) updates origin/main without your knowledge — and --force-with-lease assumes you’ve seen the other commit. The cure is --force-if-includes (git 2.30+): the push goes through only if the other commits are in your branch too.

    git config --global alias.pushf "push --force-with-lease --force-if-includes"
    git pushf

    Where force isn’t needed at all

    • main — the branch everyone works from and the servers pull (Server configs in git). Don’t rewrite it; fix a mistake with a new commit, git revert (Undo in git).
    • In the GitHub repository settings (Settings, Rules), forbid force pushes to a protected branch entirely — then even an accidental --force won’t get through.