プルリクエストがマージされてリモート上のソースブランチは削除されたけど、ローカルのリポジトリではブランチが残ったまま… あれ、どれがマージされたんだっけ…?
ってことが時々あったりするので、普段使用することが多い PowerShell の環境で、リモート (origin) に同名のブランチが存在しないローカルブランチを列挙して確認するための関数を作成してみたというお話。
git branch -vv
の出力を参照するという方法はよく見かけるのですが、upstream ブランチを設定していないケースも多いので、単に名前だけで存在を確認するようにしました。
関数
$PROFILE に以下の関数を定義。
function Show-LocalOnlyBranches {
if (-not (Test-Path .git)) {
Write-Output "Current directory is not a git repository."
return
}
git fetch origin
$branches = git branch --format='%(refname:short)'
foreach ($branch in $branches) {
git show-ref --verify --quiet "refs/remotes/origin/$branch"
if (!$?) {
Write-Output $branch
}
}
}
名前が長いので適当に Set-Alias
するなどするとよろしいかと。
実行結果
PS> $PSVersionTable.PSVersion
Major Minor Patch PreReleaseLabel BuildLabel
----- ----- ----- --------------- ----------
7 4 4
PS> cd
PS> Show-LocalOnlyBranches
Current directory is not a git repository.
PS> cd repos\hoge
PS> git branch -a
foo
fuga
* main
remotes/origin/HEAD -> origin/main
remotes/origin/foo
remotes/origin/fuga
remotes/origin/main
PS> Show-LocalOnlyBranches
PS> git push origin --delete fuga
To github.com:xxxxxxx/hoge.git
- [deleted] fuga
PS> Show-LocalOnlyBranches
fuga