git push --force-with-lease
- Version
- 2.51
- Review
- Draft
Summary#
--force-with-lease lets you push rewritten history only if the remote ref still points at an expected commit. An explicit expected object ID makes the comparison independent of background fetches.
Syntax#
git push --force-with-lease=refs/heads/topic:EXPECTED origin topic
Example#
(
set -eu
scratch=$(mktemp -d "${TMPDIR:-/tmp}/devlookup-git.XXXXXX")
trap 'rm -rf -- "$scratch"' EXIT
unset GIT_CONFIG_GLOBAL $(git rev-parse --local-env-vars)
export GIT_CONFIG_NOSYSTEM=1 GIT_TEMPLATE_DIR= LC_ALL=C
export HOME="$scratch" XDG_CONFIG_HOME="$scratch" GIT_ATTR_NOSYSTEM=1
git init --bare -q -b topic "$scratch/remote.git"
mkdir "$scratch/work"
cd "$scratch/work"
git init -q -b topic
printf 'draft\n' > topic.txt
git add topic.txt
git -c user.name="Reference Example" -c user.email=example@example.invalid commit -qm "Draft"
git remote add origin "$scratch/remote.git"
git push -q origin topic
expected=$(git rev-parse refs/remotes/origin/topic)
printf 'refined\n' > topic.txt
git add topic.txt
git -c user.name="Reference Example" -c user.email=example@example.invalid commit --amend -qm "Refine"
git push -q --force-with-lease="refs/heads/topic:$expected" origin topic
if git push -q --force-with-lease="refs/heads/topic:$expected" origin \
"$expected:refs/heads/topic" 2> /dev/null; then
exit 1
fi
echo "stale lease rejected"
git --git-dir="$scratch/remote.git" log -1 --format=%s refs/heads/topic
)
Expected output#
stale lease rejected
Refine
Common mistakes#
Replace EXPECTED with the object ID from the remote state you inspected before the rewrite. If the lease fails, examine the new remote commits before attempting another push. A successful lease can still replace history, so follow the branch's collaboration rules.
Version applicability#
Git 1.8.5 added the explicit ref-and-expected-object form.
The complete example requires Git 2.28 or later for git init -b.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0