name: Auto Delete Branch After Merge
on:
pull_request:
types: [closed]
jobs:
delete_branch:
if: github.event.pull_request.merged == true
runs-on: ubuntu-latest
steps:
- name: Delete branch if not main or develop
uses: actions/github-script@v7
with:
script: |
const headBranch = context.payload.pull_request.head.ref; // PR元ブランチ
const baseBranch = context.payload.pull_request.base.ref; // マージ先ブランチ
const owner = context.repo.owner;
const repo = context.repo.repo;
core.info(`PR base: ${baseBranch}, head: ${headBranch}`);
if (baseBranch === "develop" && headBranch !== "main" && headBranch !== "develop") {
await github.rest.git.deleteRef({
owner,
repo,
ref: `heads/${headBranch}`,
});
core.info(`✅ Deleted branch: ${headBranch}`);
} else {
core.info(`⏩ Skipped deleting branch: ${headBranch}`);
}
1. ワークフロー名
name: Auto Delete Branch After Merge
- これはワークフローの名前(自由につけられます)。
- GitHubのActionsタブに出てくる名前になります。
2. いつ実行するか(トリガー)
on:
pull_request:
types: [closed]
-
on:は「どんなイベントで実行するか」を指定。 -
pull_request:は「PR関連のイベント」。 -
types: [closed]は「PRが閉じられたとき」に実行される、という意味。- 閉じられた=「マージされた」か「手動で閉じられた」両方を含みます。
3. ジョブ定義
jobs:
delete_branch:
if: github.event.pull_request.merged == true
runs-on: ubuntu-latest
-
jobs:は「処理のまとまり」。 -
delete_branch:はジョブの名前(自由に命名可)。 -
if:は実行条件。-
github.event.pull_request.merged == true→ 「閉じられたPRのうち、マージされたものだけ」実行。
-
-
runs-on: ubuntu-latestは GitHub が用意している「仮想マシン」の種類。- 普通は
ubuntu-latestを使ってOKです。
- 普通は
4. 実行するステップ
steps:
- name: Delete branch if not main or develop
uses: actions/github-script@v7
-
steps:は「このジョブの中で実行する処理のリスト」。 -
name:はそのステップの説明。 -
uses: actions/github-script@v7は「公式の GitHub Script Action を利用する」という意味。- これを使うと JavaScript で GitHub API を簡単に呼べます。
5. スクリプトの中身
with:
script: |
const headBranch = context.payload.pull_request.head.ref; // PR元ブランチ
const baseBranch = context.payload.pull_request.base.ref; // マージ先ブランチ
-
with:はgithub-scriptに渡すパラメータ。 -
script:に書いた内容は JavaScript として実行されます。 -
context.payload.pull_request→ 今回トリガーになったPRの情報が入っています。-
head.ref→ PRの「元ブランチ名」(例:feature/add-login) -
base.ref→ PRの「マージ先ブランチ名」(例:develop)
-
6. 削除するかの判定
if (baseBranch === "develop" && headBranch !== "main" && headBranch !== "develop") {
await github.rest.git.deleteRef({
owner,
repo,
ref: `heads/${headBranch}`,
});
core.info(`✅ Deleted branch: ${headBranch}`);
} else {
core.info(`⏩ Skipped deleting branch: ${headBranch}`);
}
- 条件:
- マージ先が
develop - 元ブランチが
mainでもdevelopでもない
- マージ先が
- 上記を満たしたら GitHub API (
github.rest.git.deleteRef) を呼んでリモートブランチを削除。 - ログに「Deleted」または「Skipped」と出す。
まとめ
- PRが閉じられたときに発火する
- マージされたPRのみ処理する
- developにマージされた作業用ブランチだけを削除
- main / develop は削除対象外