How to git commit nothing without an error?

I'm trying to write a fabric script that does a git commit; however, if there is nothing to commit, git exits with a status of 1. The deploy script takes that as unsuccessful, and quits. I do want to detect actual failures-to-commit, so I can't just give fabric a blanket ignore for git commit failures. How can I allow empty-commit failures to be ignored so that deploy can continue, but still catch errors caused when a real commit fails?

def commit():
local("git add -p && git commit")
41776 次浏览

来自 git commit手册页:

--allow-empty
Usually recording a commit that has the exact same tree as its
sole parent commit is a mistake, and the command prevents you
from making such a commit. This option bypassesthe safety, and
is primarily for use by foreign SCM interface scripts.
with settings(warn_only=True):
run('git commit ...')

这会导致结构忽略失败。它的优点是不会创建空提交。

您可以将它包装在另外一个 with hide('warnings'):层中,以完全禁止输出,否则您将在结构输出中看到提交失败(但是 Fabfile 继续执行)。

通过检查 git diff 的退出代码来预先捕获这个条件?

例如(在 shell 中) :

git add -A
git diff-index --quiet HEAD || git commit -m 'bla'

编辑: 根据霍尔格的评论修正了 git diff命令。

试着抓住宝宝!

from fabric.api import local
from fabric.colors import green




def commit(message='updates'):
try:
local('git add .')
local('git commit -m "' + message + '"')
local('git push')
print(green('Committed and pushed to git.', bold=False))
except:
print(green('Done committing, likely nothing new to commit.', bold=False))

在执行 shell 时,您可以使用 ... || true技术来声明一个可以预期和忽略的失败:

git commit -a -m "beautiful commit" || true

这还可以防止在使用 errexit选项时 shell 脚本退出。

您还可以使用返回代码为0的任何其他命令代替 ... || true,例如

git commit -a -m "beautiful commit" || echo "ignore commit failure, proceed"

只是用一个明确的 if语句扩展了 Tobi & Holger的答案。

git add -A
if ! git diff-index --quiet HEAD; then
git commit -m "Message here"
git push origin main
fi

让我们给它一点解释。

  1. git add -A: 分阶段进行更改(下一步所需)

  2. git diff-index --quiet HEAD会比较你的 阶段性变化和头部。

    --quiet is impotant as it will imply --exit-code which "makes the program exit with codes 1 if there were differences and 0 means no differences".

参见 安静