Skip to content

Auto Merge Approved PRs #332

Auto Merge Approved PRs

Auto Merge Approved PRs #332

name: "Auto Merge Approved PRs"
on:
pull_request_review:
types: [submitted]
jobs:
auto_merge:
runs-on: ubuntu-latest
steps:
- name: "Check Approvals"
id: check
uses: actions/github-script@v6
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
result-encoding: string
script: |
const pull_number = context.payload.pull_request.number;
const reviews = await github.rest.pulls.listReviews({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: pull_number,
});
const approvals = reviews.data.filter(review => review.state === 'APPROVED');
const approvalCount = approvals.length;
core.info(`PR #${pull_number} has ${approvalCount} approval(s).`);
return approvalCount >= 2;
- name: "Merge PR"
if: ${{ steps.check.outputs.result == 'true' }}
uses: actions/github-script@v6
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const pull_number = context.payload.pull_request.number;
// PR 정보 및 병합 κ°€λŠ₯ μƒνƒœ 확인
let pr;
for (let i = 0; i < 5; i++) { // μ΅œλŒ€ 5회 μž¬μ‹œλ„
const { data } = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: pull_number,
});
pr = data;
if (pr.state !== 'open') {
core.info(`PR #${pull_number} is not open (state: ${pr.state}).`);
return;
}
if (pr.mergeable === true) {
break; // 병합 κ°€λŠ₯ν•˜λ©΄ 루프 μ’…λ£Œ
} else if (pr.mergeable === false) {
core.info(`PR #${pull_number} cannot be merged due to conflicts or other issues.`);
return;
} else {
// mergeable이 null인 경우 (계산 쀑), μž μ‹œ λŒ€κΈ° ν›„ μž¬μ‹œλ„
await new Promise(resolve => setTimeout(resolve, 2000)); // 2초 λŒ€κΈ°
}
}
if (pr.mergeable !== true) {
core.info(`PR #${pull_number} mergeable status is unknown after retries.`);
return;
}
// PR 병합 μ‹œλ„
try {
await github.rest.pulls.merge({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: pull_number,
});
core.info(`PR #${pull_number} has been merged successfully.`);
} catch (error) {
core.info(`Failed to merge PR #${pull_number}: ${error.message}`);
}