获得git状态布尔值而不需要缓慢的差异列表

5

我有一个bash PS1,如果我的git目录已更改,则变为红色,如果未更改,则变为绿色。

if [ $? -eq 0 ]; then \
   echo "$(echo `git status` | grep "nothing to commit" > /dev/null 2>&1; \
   if [ "$?" -eq "0" ]; then \
     # @4 - Clean repository - nothing to commit
     echo "\n'$Green'"$(__git_ps1 "(%s)"'$Color_Off'); \
   else \
     # @5 - Changes to working tree
     echo "\n'$IRed'"$(__git_ps1 "(%s)"'$Color_Off'); \
   fi)\$ "; \
 fi)'

这个功能很好用!但问题在于,在某些工作目录中,由于存在许多更改和大量差异,速度非常慢。

有没有更好的方法来获取git状态布尔值(是更改还是未更改),而不需要全量更新?

我已经尝试了git status --shortgit status --porcelain,但仍然很慢。


我建议使用posh git而不是自己动手做。它可以完成你所描述的功能,还有更多其他功能。 - adrianbanks
2个回答

5
也许这个回答会对您有用:https://dev59.com/M3E85IYBdhLWcg3wr1qx#2659808 简而言之,您可以根据需求调整以下检查。更多细节请参见链接的答案。
if ! git diff-index --quiet --cached HEAD; then
    # Index has changes.
    exit 1;
elif ! git diff-files --quiet; then
    # Working tree has changes.
    exit 1;
elif [ -n "`git ls-files --others --exclude-standard`" ]; then
    # There are untracked unignored files.
    exit 1;
fi

这段代码 ```! git diff-files --quiet; then

Working tree has changes.``` 是我需要的。谢谢!希望在未来的 Git 版本中不会有任何破坏性的更改。

- pegasuspect

0

我在这里找到了答案:https://gist.github.com/sindresorhus/3898739 git diff --quiet --ignore-submodules HEAD 2>/dev/null

这个方法非常快,但是如果你有一个未跟踪的文件,你将会得到一个 changed==0 的布尔值,但对我来说还是不错的。

git_ps1_style ()
{
    local GREEN="\001\033[0;32m\002"
    local RED="\001\033[0;91m\002"
    local git_branch="$(git rev-parse --abbrev-ref HEAD 2>/dev/null)";
    local git_ps1_style="";
    if [ -n "$git_branch" ]; then
        (git diff --quiet --ignore-submodules HEAD 2>/dev/null)
        local git_changed=$?
        if [ "$git_changed" == 0 ]; then
            git_ps1_style=$GREEN$git_branch;
        else
            git_ps1_style=$RED$git_branch;
        fi
    fi
    echo -e "$git_ps1_style"
}
echo $(git_ps1_style)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接