【GitHub Actions】「auto-merge was automatically disabled」を検知し、再度有効にする方法
はじめに
弊社プロダクト[1]では、ベースブランチの保護ルールを変更することによって新たなPRのマージを防ぎ、複数のPRがまとまった単位でのリリースを行なっています。
詳しくは記事[2]をご覧ください。
リリースが完了した後、ブランチ保護ルールを変更してマージ可能な状態に戻します。この際、ブランチ保護ルールを戻す前に事前に auto-merge
を有効にしていたPRで、以下のように auto-merge
が勝手に解除されてしまう場合があります。
auto-merge was automatically disabled
Base branch was modified
勝手に自動マージが無効になることで、予定していた日のリリースを逃してしまう恐れがあります。
そこで、 auto-merge
が無効になったのを検知し、自動で再度有効にするGitHub Actionsを作りました。
本記事の内容は以下の通りです。
- GitHub Actionsの設定ファイル
-
auto-merge
が自動で無効になったPRの検知 - 対象のPRの
auto-merge
の再有効化
GitHub Actionsの設定ファイル
はじめに全体の設定ファイルを添付します。
name: Re-enable auto-merge
on:
pull_request:
types:
- auto_merge_disabled
jobs:
re-enable-auto-merge:
name: Re-enable auto-merge
runs-on: ubuntu-latest
if: ${{ github.event.reason == 'Base branch was modified' }}
steps:
- name: Generate token
id: github_app
uses: actions/create-github-app-token@v1
with:
app-id: ${{ secrets.GITHUB_APP_ID }}
private-key: ${{ secrets.GITHUB_APP_PRIVATE_KEY }}
- name: Enable auto-merge
env:
GITHUB_TOKEN: ${{ steps.github_app.outputs.token }}
run: |
gh pr merge -R OWNER/REPO --merge --auto "${{ github.event.pull_request.number }}"
auto-merge
が自動で無効になったPRの検知
以下に設定ファイルの一部を抜粋します。
name: Re-enable auto-merge
on:
pull_request:
types:
- auto_merge_disabled
jobs:
re-enable-auto-merge:
name: Re-enable auto-merge
runs-on: ubuntu-latest
if: ${{ github.event.reason == 'Base branch was modified' }}
steps:
(以下略)
まず、 pull_request
トリガー[3]で auto-merge
が無効になったこと (type: auto_merge_disabled
) を検知します。
しかし、これでは「手動で auto-merge
を有効にした場合」も検知されてしまうので、自動で無効になった場合に絞る必要があります。
ここで、上記イベントがトリガーされた際のペイロード[4]を見ると、 github.event.reason
に auto-merge
が無効になった理由が格納されていることが分かります。実際に動かしてみると、自動で無効になった際には 'Base branch was modified'
となっていたため、こちらを条件としました。
auto-merge
の再有効化
対象のPRの 以下に設定ファイルの一部を抜粋します。
- name: Generate token
id: github_app
uses: actions/create-github-app-token@v1
with:
app-id: ${{ secrets.GITHUB_APP_ID }}
private-key: ${{ secrets.GITHUB_APP_PRIVATE_KEY }}
- name: Enable auto-merge
env:
GITHUB_TOKEN: ${{ steps.github_app.outputs.token }}
run: |
gh pr merge -R OWNER/REPO --merge --auto "${{ github.event.pull_request.number }}"
GitHub Appによるtokenの生成
まず、PRの auto-merge
を有効にするのに必要なアクセス権限 (Contents
の Read and write
と Pull requests
の Read and write
) を持ったGitHub Appを作成し、都度tokenを生成しています。
auto-merge
のために必要な権限は Pull requests
への書き込み権限だけで十分な気がしてしまいますが、ステータスチェックがオールグリーンになった後にマージコミットを作るため、 Contents
への書き込み権限も必要です。
auto-merge
の再有効化
GitHub CLIによる 次に、生成したtokenを用いて対象のPRの auto-merge
を再度有効にします。
詳細は下記[5]をご覧ください。
注意点としては、 pull_request
トリガーによって発火されているためオーガニゼーションやリポジトリの指定 (-R OWNER/REPO
) は不要に見えますが、これはGitリポジトリへのチェックアウトをしていないためにGitHub CLIが自動的にオーガニゼーションとリポジトリの識別をできないためです。
動いたところ
実際に動いた様子です。
ベースブランチの変更により auto-merge
が無効になった際に、自動的に auto-merge
が再度有効になっています。
おわりに
リリースを予定していたPRがちゃんとマージされるようになったことで、開発体験が向上しました。
こういった改善を今後も続けていきたいです。
参考リンク
Discussion