LoginSignup
26
24

More than 5 years have passed since last update.

PowerShell に Git と Mercurial のブランチ名を表示する

Last updated at Posted at 2014-07-01

bashでgitとmercurialを使いやすくする - YAMAGUCHI::weblogbashにgitとmercurialのブランチ名を表示する - アジャイルSEを目指すブログ を読んで、「お、PowerShell でもブランチ名表示できたら嬉しいな」って思ったので(スゴイ今さら感は否めませんが)書いてみました。

環境

  • PowerShell 3.0
  • Mercurial 2.9
  • Git 1.9.0

Git、Mercurial ブランチ名の取得

ブランチ名が欲しいだけなので、手でごりごりっと書いてしまいます。

# Git 管理ディレクトリ
function git_branch {
    git branch 2>$null |
    where { -not [System.String]::IsNullOrEmpty($_.Split()[0]) } |
    % { $bn = $_.Split()[1]
        Write-Output "(git:$bn)" }
}

# Mercurial 管理ディレクトリ
function hg_branch {
    hg branch 2>$null | % { Write-Output "(hg:$_)" }
}

この結果、それぞれのブランチ名を表示するための文字列が取得できるようになります。

$ git_branch
(git:master)

$ hg_branch
(hg:default)

プロンプトをイケてる感じにする

何が言いたいかというと、山口さんの記事みたいに時刻とか出して、さらに色も付けたいんですよね。

それを実現しようとしたコードがこちら。

# プロンプト表示を変更する
function prompt {
   # カレントディレクトリをウィンドウタイトルにする
   (Get-Host).UI.RawUI.WindowTitle = "Windows PowerShell " + $pwd

   # GitBashっぽく表示
   # カレントディレクトリを取得
   $idx = $pwd.ProviderPath.LastIndexof("\") + 1
   $cdn = $pwd.ProviderPath.Remove(0, $idx)

   # 現在時刻を取得
   $t = (Get-Date).ToLongTimeString()

   # ブランチ名を取得
   $gitBranch = git_branch
   $hgBranch = hg_branch

   # プロンプトをセット
   Write-Host "[" -NoNewline -ForegroundColor White
   Write-Host "$t " -NoNewline -ForegroundColor Green
   Write-Host $env:USERNAME -NoNewline -ForegroundColor Cyan
   Write-Host "@$env:USERDOMAIN $gitBranch$hgBranch" -NoNewline -ForegroundColor White
   Write-Host $pwd -NoNewline -ForegroundColor Green
   Write-Host "]
$" -NoNewline -ForegroundColor White
   return " "
}

profile に書いたり、この関数を直接実行することで、PowerShell のプロンプトがイケてる感じになります。

編集履歴

  • 2014/08/17: git_branch に不要なブランチ名を除去するための条件を追加。

see also

カレントディレクトリをウィンドウタイトルに表示してプロンプトを短くする - Qiita

シェルでechoの文字に色をつける方法 - webネタ

ConsoleColor 列挙体 - MSDN Library

26
24
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
24