Gitを使用しているなら現在のブランチ名は常時表示するべし

ブランチ名は常時表示するべし

Gitを使用している際に現在のブランチ名の確認のために「git branch」を実行している人をよく見かけますが、ブランチ名はターミナル(またはPowerShell)の画面上に常時表示できます。

ブランチ名を画面上に常時表示させておけば、何度も「git branch」を実行する必要がなくなり、作業するブランチを間違えることも少なくなるので必ずブランチ名は常時表示に設定したほうが良いです。

ターミナルでブランチ名を常時表示する方法

Macのターミナルでブランチ名を常時表示するには、まず.zshrcファイルを以下のコマンドで開きます。

open ~/.zshrc

.zshrcファイルを開いたら以下のコードを.zshrcに貼り付けて保存します。

autoload -Uz vcs_info
precmd() { vcs_info }
setopt PROMPT_SUBST
zstyle ':vcs_info:git:*' formats ' (%b)'
PROMPT='
%F{green}%~%f%F{cyan}${vcs_info_msg_0_}%f
%F{yellow}$%f '

PowerShell (Windows)でブランチ名を常時表示する方法

PowerShell (Windows)でブランチ名を常時表示するには、DocumentsフォルダにWindowsPowerShellフォルダを作成して、この中にMicrosoft.PowerShell_profile.ps1というファイル名で以下のコードを書いて保存するだけです。

C:\Users\<ユーザー名>\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
Microsoft.PowerShell_profile.ps1
function prompt {
  $branch = ""
  $git_change_count = 0
  $git_staged_count = 0

  if (git branch) {
    (git branch | select-string "^\*").ToString() | set-variable -name branch
    $branch = $branch.trim() -replace "^\* *", ""
    git diff --shortstat | %{ echo $_.Trim().Substring(0, $_.Trim().indexof(" ")) } | set-variable -name git_change_count
    git diff --shortstat --cached | %{ echo $_.Trim().Substring(0, $_.Trim().indexof(" ")) } | set-variable -name git_staged_count
  }
  Write-Host("[") -NoNewline -ForegroundColor White
  $mylocal_path = $(get-location) -replace "C:\\Users", "~"
  Write-Host($mylocal_path) -NoNewline -ForegroundColor Cyan
  Write-Host("] ") -NoNewline -ForegroundColor White
  if ($branch -ne "") {
    Write-Host("(") -NoNewline -ForegroundColor White
    if ($git_change_count -ne $git_staged_count) {
      if ($git_change_count -ne "0") {
        Write-Host($branch) -NoNewline -ForegroundColor DarkRed
      } else {
        Write-Host($branch) -NoNewline -ForegroundColor DarkYellow
      }  
    } else {
      Write-Host($branch) -NoNewline -ForegroundColor DarkGreen
    }
    Write-Host(")`n") -NoNewline -ForegroundColor White
  }
  return "PS > "
}

「C:\\Users」の部分は "~" に置換するので、置換したい任意のパスに変えてください。

カテゴリーgit