How to git commit nothing without error?

问题描述 投票:0回答:7

我正在尝试编写一个执行

git commit
的织物脚本;但是,如果没有要提交的内容,git 将以
1
状态退出。部署脚本将其视为不成功并退出。我确实想检测 actual 提交失败,所以我不能只给 fabric 忽略
git commit
失败。我如何允许忽略空提交失败,以便部署可以继续,但仍然捕获真正提交失败时导致的错误?

def commit():
    local("git add -p && git commit")
python git fabric
7个回答
225
投票

通过检查

git diff-index
?

的退出代码预先捕获此条件

例如(在shell中):

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

编辑:根据 Holger 的评论修复了

git diff
命令。


80
投票

来自

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 bypasses the safety, and
    is primarily for use by foreign SCM interface scripts.

11
投票

只是用明确的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
    会将您的分阶段更改与HEAD进行比较。

    --quiet
    是重要的,因为它意味着
    --exit-code
    “如果存在差异,则程序以代码 1 退出,0 表示没有差异”。

--安静.


3
投票
with settings(warn_only=True):
  run('git commit ...')

这会导致 fabric 忽略失败。具有不创建空提交的优点。

您可以将它包裹在额外的

with hide('warnings'):
层中以完全抑制输出,否则您将在结构输出中得到一条注释,表明提交失败(但 fabfile 继续执行)。


1
投票

通过 shell 时,您可以使用

... || true
技术来声明预期和忽略的失败:

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

这也可以防止 shell 脚本在使用

errexit
选项时退出。

您还可以使用任何其他返回代码为 0 的命令来代替

... || true
,例如

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

0
投票

什么,如果你只是 prevent 由空提交引起的失败而不是 ignoring 它们?

一线:

git add . && git diff --staged --quiet || git commit -m 'Commit message'

使用此脚本:如果没有更改,则不会提交。如果有变化,它会提交它们。

来源:如何让Jenkins git commit only if there are changes?


-7
投票

尝试/抓住宝宝!

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))
© www.soinside.com 2019 - 2024. All rights reserved.