Skip to content

[Pull Request] Review State Labeler #16

[Pull Request] Review State Labeler

[Pull Request] Review State Labeler #16

name: "[Pull Request] Review State Labeler"
on:
pull_request_review:
types: [submitted, edited, dismissed]
pull_request_target:
types: [synchronize, reopened, opened]
jobs:
update-labels:
runs-on: ubuntu-latest
steps:
- name: Check if it is self approved review PR
id: check_self_approved
uses: actions/github-script@v6
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const prNumber = context.payload.pull_request.number;
const owner = context.repo.owner;
const repo = context.repo.repo;
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
owner,
repo,
issue_number: prNumber
});
const hasSelfApprovedReview = currentLabels.some(label => label.name === 'self_approved/review');
core.setOutput('isSelfApprovedPR', hasSelfApprovedReview);
- name: Add 'pending/review' label based on PR label on pull_request_target event
if: github.event_name == 'pull_request_target' && steps.check_self_approved.outputs.isSelfApprovedPR == 'false'
uses: actions/github-script@v6
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const prNumber = context.payload.pull_request.number;
const owner = context.repo.owner;
const repo = context.repo.repo;
const hasSelfApprovedReview = context.payload.pull_request.labels.some(label => label.name === 'self_approved/review');
if(hasSelfApprovedReview) {
return;
}
await github.rest.issues.addLabels({
owner,
repo,
issue_number: prNumber,
labels: ['pending/review']
});
- name: Add or remove labels based on review state on pull_request_review event
if: github.event_name == 'pull_request_review' && steps.check_self_approved.outputs.isSelfApprovedPR == 'false'
uses: actions/github-script@v6
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const prNumber = context.payload.pull_request.number;
const owner = context.repo.owner;
const repo = context.repo.repo;
const reviewState = context.payload.review.state
console.log('reviewState', reviewState)
if (reviewState === 'approved' || reviewState === 'changes_requested') {
// Labels to remove based on review state
const labelsToRemove = ['pending/review']
if (reviewState === 'approved') labelsToRemove.push('changes_requested/review')
else if (reviewState === 'changes_requested') labelsToRemove.push('approved/review')
// Remove each label individually
for (const label of labelsToRemove) {
try {
await github.rest.issues.removeLabel({
owner,
repo,
issue_number: prNumber,
name: label
});
} catch (error) {
if (error.status === 404) {
console.log(`Label ${label} not found, skipping removal`);
} else {
throw error;
}
}
}
// Add 'approved/review' or 'changes_requested/review' label
await github.rest.issues.addLabels({
owner,
repo,
issue_number: prNumber,
labels: [reviewState + '/review']
});
}