Gitでローカル側のマージ済みブランチを削除したい

標準

GitHub/Gitlab に Pull Request / Merge Requestを送ってリモートレポジトリでマージされたもう不要なブランチがローカル側に溜まっていく問題。

一個一個削除していくのは面倒だからまとめて削除したい。

[参考] Git Tip: Deleting Old Local Branches

git branch -vv でリモートのブランチとマージ済フラグ(gone)が見れる。

$ git branch -vv
develop c5cb4d0 [origin/develop] fixes ci
feature/issue001 8c80336 [origin/feature/issue001: gone] Add comment
master c0f134c [origin/master] update README

.gitconfig に alias 追加

[alias]
  merged-branch = !sh -c 'git branch -vv | grep \"origin/.*: gone]\" | awk \"{print \\$1}\"'
  delete-merged-branch = !sh -c 'git merged-branch | xargs git branch -d'

上記を設定することで、 git merged-branchでマージ済みブランチのリスト、git delete-merged-branch でマージ済みブランチの削除ができる

$ git merged-branch
feature/issue001
$ git delete-merged-branch
Deleted branch feature/issue001 (was 8c80336).

なお、ブランチ削除の前にローカルへリモートの状態を反映するため git fetch -p を事前に実行しておく。

※エイリアスでリモートをoriginとハードコーディングしているので、他のリモートにしたい場合はリポジトリの.git/configに個別にリモートを変更したエイリアスを作成しないといけない。
※マッチが簡易なのでコミットコメントに “: gone]” と入っていたらマージ済みと誤認識する。

コメントを残す

Page optimized by WP Minify WordPress Plugin