让 oh-my-zsh 的git插件飞起来

- hikerpig
#zsh#Git

更新:2020-03-26

作为一个伪文艺程序员,在ubuntu上使用zsh搭配OMG的插件oh-my-zsh,小日子曾经过的滋滋润润,各种auto-completion让我基本上爱上Tab键了。后来换了台旧MBP,每次跑到项目文件夹下git checkout feat (tab)就傻了,出去泡一杯咖啡回来shell还在哼哧哼哧地忙活着,分分钟有种再手贱<tab>就剁掉的冲动。

有位仁兄找到了问题的解决方法,原来作恶的是~/.oh-my-zsh/lib/git.zsh中的git_prompt_info() 调用的parse_git_dirty()函数。

更新:这段代码是 2020-03-26 时的版本

# Outputs current branch info in prompt format
function git_prompt_info() {
  local ref
  if [[ "$(command git config --get oh-my-zsh.hide-status 2>/dev/null)" != "1" ]]; then
    ref=$(command git symbolic-ref HEAD 2> /dev/null) || \
    ref=$(command git rev-parse --short HEAD 2> /dev/null) || return 0
    echo "$ZSH_THEME_GIT_PROMPT_PREFIX${ref#refs/heads/}$(parse_git_dirty)$ZSH_THEME_GIT_PROMPT_SUFFIX"
  fi
}

# Checks if working tree is dirty
function parse_git_dirty() {
  local STATUS
  local -a FLAGS
  FLAGS=('--porcelain')
  if [[ "$(command git config --get oh-my-zsh.hide-dirty)" != "1" ]]; then
    if [[ "$DISABLE_UNTRACKED_FILES_DIRTY" == "true" ]]; then
      FLAGS+='--untracked-files=no'
    fi
    case "$GIT_STATUS_IGNORE_SUBMODULES" in
      git)
        # let git decide (this respects per-repo config in .gitmodules)
        ;;
      *)
        # if unset: ignore dirty submodules
        # other values are passed to --ignore-submodules
        FLAGS+="--ignore-submodules=${GIT_STATUS_IGNORE_SUBMODULES:-dirty}"
        ;;
    esac
    STATUS=$(command git status ${FLAGS} 2> /dev/null | tail -n1)
  fi
  if [[ -n $STATUS ]]; then
    echo "$ZSH_THEME_GIT_PROMPT_DIRTY"
  else
    echo "$ZSH_THEME_GIT_PROMPT_CLEAN"
  fi
}

他贴出的gist是这样的:

function git_prompt_info() {
  ref=$(git symbolic-ref HEAD 2> /dev/null) || return
  echo "$ZSH_THEME_GIT_PROMPT_PREFIX${ref#refs/heads/}$ZSH_THEME_GIT_PROMPT_SUFFIX"
}

没有了parse_git_dirty,我们就看不到zsh 中git repo名字旁边提示当前分支是否dirty的小勾勾“✔”和小叉叉“✗”,但是人生体验流畅了不只十个数量级啊。比起肆意的人生,OOXX算什么呢!!!(话题没有跑偏没有跑偏(;¬_¬) )

当然如果你不想魔改源码, SO 上也有人问过这问题,解决方案存在于上面的源码里。

git config --add oh-my-zsh.hide-status 1
git config --add oh-my-zsh.hide-dirty 1

从此<tab>键又能肆意飞翔了。