2025-05-11

Squash and merge した後のブランチを掃除する

プログラミング
プログラミングgit

はじめに

GitHub を使ってブランチをマージするときには 3 つの選択肢がある。

  • Create a merge commit
  • Rebase and merge
  • Squash and merge

仕事では Create a merge commit を使うことが多いが、個人開発では Squash and merge を使った場合の面倒事が発生することが少ないため、master ブランチにちょっとした修正のコミット履歴を残さないように Squash and merge を使うことがある。

Squash and merge を使ったときの面倒事についてはググると記事が見つかるのでそちらを参照して欲しい。

Squash and merge した後にコンフリクトが発生する問題については、rebase するときのオプションで解決できるらしい。

しかし、マージ済みブランチを削除するとき -d ではなく -D で消さなければいけない。定期的に git pull --prune してローカルのマージ済みブランチも掃除しているのでコマンド一発でマージ済みブランチを消せないのは不便に感じる。

--no-ff の場合

Create a merge commit でマージしたときは次の alias を ~/.config/git/config に設定しているので git delete-merged-branch コマンドでマージ済みブランチを削除している。

1
[alias]
2
delete-merged-branch = "!f () { git checkout $1; git branch --merged|egrep -v '\\*|develop|main|master'|xargs git branch -d; git fetch --prune; };f"

このエイリアスは以下の記事を参考に developmainmaster ブランチを保護するようにしたものだ。

しかし、これだと Squash and merge でマージしたブランチが消えない問題がある。

Squash and merge に対応したい

ググってみると方法は 4 つ見つかった。

一つ目は gh コマンドの拡張として開発されている poi、二つ目と三つ目は npx を使って実行できる Node パッケージとして配布されている git-delete-squashed、四つ目は git-delete-squashed をシェルスクリプトで実装したものになっている。

gh-poi

今回は poi を試してみる。 gh コマンドを使うので最初にログインする。

1
$ gh auth login
2
? Where do you use GitHub? GitHub.com
3
? What is your preferred protocol for Git operations on this host? SSH
4
? Generate a new SSH key to add to your GitHub account? Yes
5
? Enter a passphrase for your new SSH key (Optional):
6
? Title for your SSH key: GitHub CLI
7
? How would you like to authenticate GitHub CLI? Login with a web browser
8
9
! First copy your one-time code: XXXX-XXXX
10
Press Enter to open https://github.com/login/device in your browser...
11
Authentication complete.
12
- gh config set -h github.com git_protocol ssh
13
Configured git protocol
14
Uploaded the SSH key to your GitHub account: /Users/suzumiyaaoba/.ssh/id_ed25519.pub
15
Logged in as SuzumiyaAoba

gh コマンドを使ったことがない方は Installation を参考にインストールしてください。

ログインできたら gh-poi をインストールする。

1
$ gh extension install seachicken/gh-poi
2
Installed extension seachicken/gh-poi

Squash マージ済みのブランチを消すためのコマンド gh poi を実行すると次のようになった。

1
$ gh poi
2
Fetching pull requests...
3
Deleting branches...
4
5
Deleted branches
6
improve-header
7
└─ #38 https://github.com/SuzumiyaAoba/SuzumiyaAoba.github.io/pull/38 SuzumiyaAoba
8
posts
9
└─ #42 https://github.com/SuzumiyaAoba/SuzumiyaAoba.github.io/pull/42 SuzumiyaAoba
10
11
Branches not deleted
12
clean
13
└─ #29 https://github.com/SuzumiyaAoba/SuzumiyaAoba.github.io/pull/29 SuzumiyaAoba
14
* master
15
pagefind
16
└─ #24 https://github.com/SuzumiyaAoba/SuzumiyaAoba.github.io/pull/24 SuzumiyaAoba

確かに Squash マージしたブランチを削除できた。 git-delete-squashed と違って GitHub の PR 情報を元に Squash マージ済みのブランチか否かを判定しているようだ。

GitHub からデータを取得するのはいまいちな気もするがしばらく使ってみる。問題があれば git-delete-squashed も試してみたい。