如何在没有错误的情况下git提交任何内容?

时间:2011-11-14 15:13:49

标签: python git fabric

我正在尝试编写一个执行git commit的结构脚本;但是,如果没有提交,git将退出状态为1。部署脚本将其视为不成功,并退出。我确实想要检测实际的失败提交,所以我不能仅仅为git commit失败给织物一个忽略。如何允许忽略空提交失败,以便部署可以继续,但仍然可以捕获真正提交失败时导致的错误?

def commit():
    local("git add -p && git commit")

6 个答案:

答案 0 :(得分:99)

通过检查git diff的退出代码

预先捕获此条件

例如(在shell中):

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

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

答案 1 :(得分:54)

来自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.

答案 2 :(得分:5)

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

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

您可以将其包装在with hide('warnings'):的附加层中以完全抑制输出,否则您将在结构输出中获得提交失败的注释(但fabfile继续执行)。

答案 3 :(得分:2)

只需使用明确的 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 表示没有差异”。

--quiet

答案 4 :(得分:0)

在通过 shell 时,您可以使用 ... || true 技术来声明预期失败并被忽略:

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

这也将阻止 shell 脚本在使用 errexit 选项时退出。

除了 ... || true,您还可以使用任何其他以返回码 0 退出的命令,例如

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

答案 5 :(得分:-3)

尝试/抓住宝宝!

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))