Smile Engineering Blog

ジェイエスピーからTipsや技術特集、プロジェクト物語を発信します

初めての git-prompt

はじめに

git-worktree で複数のブランチを渡り歩いていると、今どこのブランチにいるのか?どんな状態なのか?がわからなくなることが多々あります。

プロンプトにブランチ名、状態を色で表現させる方法をご紹介します。git-prompt.sh のコメントの他、下記サイトを多分に参考にさせていただきました!

こんなの

例によって zsh 用です。.zshrc あたりに書くのですが、まず git-prompt.sh を導入します。GitHub あたりから取得し、 ~/.git-prompt.sh にコピーします。

git-prompt.shcontrib/completion/ にあります。で、 .zshrc に以下を追記します。

source ~/.git-prompt.sh
setopt PROMPT_SUBST ; RPROMPT=$'`branch-status-check`'

autoload -U colors; colors

function branch-status-check {
  local prefix branchname suffix
    branchname=`__git_ps1 "%s"`
    if [[ -z $branchname ]]; then
      return
    fi
    prefix=`get-branch-status-color`
    suffix='%{'${reset_color}'%}'
    echo ${prefix}${branchname}${suffix}
}

function get-branch-status-color {
  local output color
    output=`git status -s -uno 2> /dev/null`
    if [[ -z $output ]]; then
      color='%{'${fg[green]}'%}'
    elif [[ $output =~ "[\n]? M " ]]; then
      color='%{'${fg[red]}'%}'
    else
      color='%{'${fg[cyan]}'%}'
    fi
    echo ${color}
}

こんな感じ。

f:id:jspnet:20191209224513p:plain

マージでコンフリクトした時はこんな感じ。

f:id:jspnet:20191209224534p:plain

.git/ の中ではこんな感じ。

f:id:jspnet:20191211002033p:plain

解説

上記サイトのスクリプトとの差異ですが、

  • get-branch-name の代わりに __git_ps1 を使用している
  • -uno オプションで untracked はレポートされない(はずな)ので、 Yellow を撤廃

くらいです。普段使いではこれくらいで十分事足りてます。