0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

GitHub: デフォルトブランチじゃなくても Issue を自動 Close する方法

Posted at

背景

こんにちは。
普段お仕事では開発用のリポジトリがあり、その main ブランチに PR を作成し merge しておりました。
PR作成時close #000のようにすることで PR が merge されると同時に issue も close になり便利でした。
しかし、ブランチの運用方法が少し変わり、
main ではなくリリースブランチで運用していこう!」
となったのです。
要は、v1.1.0とかv1.2.0とかです。

いつも通り PR を作って merge されますが、ある事に気付きます。

「あれ? PR が merge されているのにどうして issue は close しないんだ?」

となりまして、調べてみると下記の記事を見つけました。

自動クローズ機能は、PRがdefault branch(通常はmainまたはmaster)にマージされた場合にのみ動作します。

え?まじ?

ちなみに公式サイトにも

default branch of a repository, its linked issue is automatically closed.

と書いてます。

Oh....

まぁ、手間ですが、デフォルトブランチを都度変えれば一応解決します...
でもそれは嫌なので他の方法を探そうと冒険に出たのが本記事です。

解決策

結論、ワークフロー作ればいけました。

.github/workflows/auto-close-issue.yml ファイルを作ってあげます。

name: Auto Close Issues With Action

on:
  pull_request:
    types: [closed]
    branches: ["*"]

jobs:
  auto-close-issues:
    if: github.event.pull_request.merged == true
    runs-on: ubuntu-latest
    permissions:
      issues: write
    steps:
      - name: Close issues fixed in this PR
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          PR_BODY: ${{ github.event.pull_request.body }}
        run: |
          ISSUE_NUMBERS=$(echo "$PR_BODY" | grep -o -E '(issues/[0-9]+|#[0-9]+)' | grep -o '[0-9]\+')

          for ISSUE_NUMBER in $ISSUE_NUMBERS; do
            curl -X PATCH \
              -H "Authorization: token $GH_TOKEN" \
              -H "Accept: application/vnd.github.v3+json" \
              "https://api.github.com/repos/${{ github.repository }}/issues/$ISSUE_NUMBER" \
              -d '{"state":"closed"}'
            
            curl -X POST \
              -H "Authorization: token $GH_TOKEN" \
              -H "Accept: application/vnd.github.v3+json" \
              "https://api.github.com/repos/${{ github.repository }}/issues/$ISSUE_NUMBER/comments" \
              -d "{\"body\":\"このイシューはPR #${{ github.event.pull_request.number }} のマージによって解決されました。\"}"
          done

これで、デフォルトブランチではなくとも、同様の操作が実現します。

又、PR に issue を書く際2つの方法があります。

(例)
# 数字 形式(例:#000)
close #100

# URL 形式(例:https://github.com/nichicom/nolab-app/issues/000)
close https://github.com/nichicom/nolab-app/issues/2136

今回のワークフローではどっちでも対応するようにしてます。
ちなみに私は後者のパターンをいつも使ってます。(楽なので)

動作確認

適当に PR 作って、issue は2つ作ります。(数字形式とURL形式)
merge後、2つの issue が close となっています。

  • close 前の issue

image.png

  • URL 形式の自動close

image.png

  • #形式の自動close

image.png

  • Github Action のワークフロー成功時

image.png

問題なくできてますね。
いや〜出来てよかったです。
今日はよく眠れそうです。

関連記事

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?