如何以编程方式确定是否存在未提交的更改? [英] How do I programmatically determine if there are uncommitted changes?

查看:72
本文介绍了如何以编程方式确定是否存在未提交的更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Makefile中,如果有未提交的更改(在工作树或索引中),我想执行某些操作。最干净和最有效的方法是什么?一个返回值为零的命令在一个情况下退出,而另一个情况下非零的命令将适合我的目的。

In a Makefile, I'd like to perform certain actions if there are uncommitted changes (either in the working tree or the index). What's the cleanest and most efficient way to do that? A command that exits with a return value of zero in one case and non-zero in the other would suit my purposes.

我可以运行 git状态,并通过 grep 管道输出,但我觉得必须有更好的方法。

I can run git status and pipe the output through grep, but I feel like there must be a better way.

推荐答案

更新:OP Daniel Stutzbach 在评论中指出 ,这个简单的命令 git diff-index

UPDATE: the OP Daniel Stutzbach points out in the comments that this simple command git diff-index worked for him:

git diff-index --quiet HEAD --

然后您就可以看到如何检查命令是否成功?如果您在bash脚本中使用它:

You can then see "How to check if a command succeeded?" if you are using it in a bash script:

git diff-index --quiet HEAD -- || echo "untracked"; // do something about it

注意:as 评论 Anthony Sottile


git diff-index HEAD ... 会在没有提交的分支上失败(例如新初始化的存储库)。

我找到的一个解决方法是 git diff-index $ (git write-tree)...

git diff-index HEAD ... will fail on a branch which has no commits (such as a newly initialized repository).
One workaround I've found is git diff-index $(git write-tree) ...






以编程方式意味着永远不要依赖瓷器命令

始终依靠管道命令


"Programmatically" means never ever rely on porcelain commands.
Always rely on plumbing commands.

另请参阅使用Git检查脏指数或未跟踪的文件 替代品(如 git status --porcelain

See also "Checking for a dirty index or untracked files with Git" for alternatives (like git status --porcelain)

您可以从中获得灵感来自新的 require_clean_work_tree 功能,其中(2010年10月初)

You can take inspiration from the new "require_clean_work_tree function" which is written as we speak ;) (early October 2010)

require_clean_work_tree () {
    # Update the index
    git update-index -q --ignore-submodules --refresh
    err=0

    # Disallow unstaged changes in the working tree
    if ! git diff-files --quiet --ignore-submodules --
    then
        echo >&2 "cannot $1: you have unstaged changes."
        git diff-files --name-status -r --ignore-submodules -- >&2
        err=1
    fi

    # Disallow uncommitted changes in the index
    if ! git diff-index --cached --quiet HEAD --ignore-submodules --
    then
        echo >&2 "cannot $1: your index contains uncommitted changes."
        git diff-index --cached --name-status -r --ignore-submodules HEAD -- >&2
        err=1
    fi

    if [ $err = 1 ]
    then
        echo >&2 "Please commit or stash them."
        exit 1
    fi
}

这篇关于如何以编程方式确定是否存在未提交的更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆