Bash PROMPT_COMMAND用于在git更新到1.8之前显示git分支

时间:2014-02-14 17:38:02

标签: git bash

我之前从一些博客文章中获得了这个bash代码,它用于在我的提示中显示我当前的git分支和脏状态。将git从1.7.11.4更新为1.8.5.4后,它不再显示分支或脏状态。

以下是我的提示:

[~/some/project (master)↑⚡] ->

它显示了(当前的git分支),箭头表示我在遥控器之前,我应该推动,闪电意味着我有未完成的更改。

更新后,就是这样(没有对repo进行任何更改):

[~/some/project] ->

以下是我的.bash_profile代码:

        RED="\[\033[0;31m\]"
     YELLOW="\[\033[0;33m\]"
        GREEN="\[\033[0;32m\]"
       BLUE="\[\033[0;34m\]"
  LIGHT_RED="\[\033[1;31m\]"
LIGHT_GREEN="\[\033[1;32m\]"
      WHITE="\[\033[1;37m\]"
 LIGHT_GRAY="\[\033[0;37m\]"
 COLOR_NONE="\[\e[0m\]"

function parse_git_branch {
  git rev-parse --git-dir &> /dev/null
  git_status="$(git status 2> /dev/null)"
  branch_pattern="^# On branch ([^${IFS}]*)"
  remote_pattern="# Your branch is (.*) of"
  diverge_pattern="# Your branch and (.*) have diverged"

  if [[ ! ${git_status}} =~ "working directory clean" ]]; then
    state="${RED}⚡"
  fi

  # add an else if or two here if you want to get more specific
  if [[ ${git_status} =~ ${remote_pattern} ]]; then
    if [[ ${BASH_REMATCH[1]} == "ahead" ]]; then
      remote="${YELLOW}↑"
    else
      remote="${YELLOW}↓"
    fi
  fi

  if [[ ${git_status} =~ ${diverge_pattern} ]]; then
    remote="${YELLOW}↕"
  fi

  if [[ ${git_status} =~ ${branch_pattern} ]]; then
    branch=${BASH_REMATCH[1]}
    echo " (${branch})${remote}${state}"
  fi
}

function prompt_func() {
    previous_return_value=$?;
    prompt="${TITLEBAR}${BLUE}[${YELLOW}\w${GREEN}$(parse_git_branch)${BLUE}]${COLOR_NONE} "
    if test $previous_return_value -eq 0
    then
        PS1="${prompt}➔ "
    else
        PS1="${prompt}${RED}➔${COLOR_NONE} "
    fi
}

PROMPT_COMMAND=prompt_func

我对bash不是很好,所以有人能发现问题,或者有更好的解决方案吗?

我正在玩bash代码,但还是无法搞清楚。求助。

  • Mac 10.9.1
  • Git 1.8.5.4
  • iTerm 2

2 个答案:

答案 0 :(得分:1)

嗯,这比我想象的要容易。结果证明问题是在git 1.7中git status命令会回显:

# On branch master
nothing to commit (working directory clean)

前面有一个前导#。现在git 1.8输出相同的内容,除了没有#

所以我所要做的就是改变这些界限:

branch_pattern="^# On branch ([^${IFS}]*)"
remote_pattern="# Your branch is (.*) of"
diverge_pattern="# Your branch and (.*) have diverged"

为:

branch_pattern="^On branch ([^${IFS}]*)"
remote_pattern="Your branch is (.*) of"
diverge_pattern="Your branch and (.*) have diverged"

删除了#,一切正常。

答案 1 :(得分:1)

请注意,此模式仍然失败:

remote_pattern="Your branch is (.*) of"

新的git输出如下:

Your branch is behind 'origin/master' by 2 commits, and can be fast-forwarded.
Your branch is ahead of 'origin/master' by 1 commit.

因此模式应更改为:

remote_pattern="Your branch is (behind|ahead) "