Github Action で Branch Protection を変更する

2024-10-19

Branch Protection の操作には Administration 級権限が必要になる

以下のドキュメントに "Administration" repository permissions (write) の記載があるように、“Administration” の permission 付与が必要になる。

保護されたブランチ用 REST API エンドポイント - Update branch protection

permission は GitHub App を作って権限セットを割り当てているだろうから、その App に “Administration” セットを割り当てる。 “Administration” を割り当てた上で token を発行し、GitHub API を叩く。

以下は雑に required_approving_review_count を更新する例。

on:
  pull_request:
    types:
      - synchronize
      - labeled
      - unlabeled
      - opened
      - reopened

jobs:
  protect_pr_branch:
    runs-on: ubuntu-latest
    timeout-minutes: 1

    steps:
      - name: checkout
        uses: actions/checkout@v4

      - name: Generate a github token
        id: generate_token
        uses: actions/create-github-app-token@v1
        with:
          app-id: ${{ secrets.APP_ID }}
          private-key: ${{ secrets.PRIVATE_KEY }}
          owner: ${{ github.repository_owner }}
          repositories: "repo_name"

      - name: protect branch
         env:
           GH_BRANCH: ${{ github.head_ref }}
           GH_TOKEN: ${{ steps.generate_token.outputs.token }}
         run: |
           gh api --method PATCH \
             -H "Accept: application/vnd.github+json" \
             -H "X-GitHub-Api-Version: 2022-11-28" \
             /repos/<ORG>/<REPO>/branches/$GH_BRANCH/protection/required_pull_request_reviews \           
         -F "required_approving_review_count=6"

更新には対象 Branch にあらかじめ Branch Protection をつくる

現時点では Branch Protection の API には作成用の API がない?ようだが、更新用は用意されている。 そのため、Branch Protection 作らずに更新用 API にリクエストすると、以下のようなエラーが発生する。

gh: Branch not protected (HTTP 404)
{"message":"Branch not protected","documentation_url":"https://docs.github.com/rest/branches/branch-protection#update-pull-request-review-protection","status":"404"}
Error: Process completed with exit code 1.

リポジトリの Settings > Code and Automation - Branches からルールを作る。 Branches

更新対象の branch が含まれるようにルールを設定すればよい。以下は ruleset からの作成画面。 Branch naming pattern

パターンで対象の branch を指定した場合、前述のように個別 branch を指定した更新をした場合、その指定した branch のみのルールが作成されるようになっている。