TOC

使用 git push --force-with-lease 替代 git push --force

今天注意到了 git push 的一个参数 --force-with-lease,可以在 Remote 有更新的时候不执行强推。

我之前考虑过会有这样的情况发生:我准备强推之前,会做最后一次拉代码检查,无误之后 force push。但是这个检查和 push 之间有一个时间差,会不会在这期间有别的小可爱提交了代码呢?
这种情况是完全可能存在的,就像是线程安全问题,只是团队的规模消减了我对这种情况的担心。

但是 --force-with-lease 参数可以彻底化解我的这种担忧,我决定以后就改用这个参数了。

不过 --force 有个 -f 可以方便一些,--force-with-lease 却没有,需要定义一个别名才好,不管是 shell 别名,或是 git alias。

PS:我查看了一下我的 zsh 配置(omz)中已经有了这个别名:gpf

gpf is an alias for git push --force-with-lease

实验

cd /tmp

mkdir testProject && cd testProject && git init --bare && cd ../

git clone testProject testProject1 && cd testProject1 && echo '# testProject' > README.md && git add README.md && git commit -m "Init commit" && git push && cd ..

git clone testProject testProject2 && cd testProject2 && echo 'Testing' >> README.md && git commit -am "update" && git push && cd ..

cd testProject1 && echo update2 >> README.md && git commit -am "update2"

git push
# To /tmp/testProject
#  ! [rejected]        master -> master (fetch first)
# error: 推送一些引用到 '/tmp/testProject' 失败
# 提示:更新被拒绝,因为远程仓库包含您本地尚不存在的提交。这通常是因为另外
# 提示:一个仓库已向该引用进行了推送。再次推送前,您可能需要先整合远程变更
# 提示:(如 'git pull ...')。
# 提示:详见 'git push --help' 中的 'Note about fast-forwards' 小节。

git push --force-with-lease
# To /tmp/testProject
#  ! [rejected]        master -> master (stale info)
# error: 推送一些引用到 '/tmp/testProject' 失败

git fetch
git push --force-with-lease