Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
352 changes: 296 additions & 56 deletions .github/workflows/contribution-policy.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
name: Contribution policy

name: Contribution Policy

on:
pull_request_target:
branches: [main, Development]
types: [opened, reopened, ready_for_review, edited, synchronize]
branches:
- main
- Development
types:
- opened
- reopened
- ready_for_review
- edited
- synchronize

permissions:
contents: read
Expand All @@ -12,75 +20,307 @@ permissions:

jobs:
enforce:
name: Assigned issue and one open PR
name: Enforce Contribution Policy
runs-on: ubuntu-latest

steps:
- name: Enforce contribution policy
- name: Validate contribution requirements
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}

script: |
const trusted = new Set(['OWNER', 'MEMBER', 'COLLABORATOR']);
const maxIssueReferences = 10;
const isExempt = (pull) => trusted.has(pull.author_association) || pull.user.type === 'Bot';
const parseIssueNumbers = (body) => [...body.matchAll(/\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s+#(\d+)\b/gi)]
.map((match) => Number(match[1]));
const evaluate = ({ issueNumbers, invalidIssues, tooManyIssueReferences, otherPull }) => [
...(issueNumbers.length === 0 ? ['Link an open issue with `Fixes #123`, `Closes #123`, or `Resolves #123`.'] : []),
...(tooManyIssueReferences ? [`Link at most ${maxIssueReferences} issues in one PR.`] : []),
...invalidIssues.map((issueNumber) => `Issue #${issueNumber} must be open and assigned to the PR author.`),
...(otherPull ? [`Only one open PR is allowed per external contributor; #${otherPull.number} is already open.`] : []),
];
const { owner, repo } = context.repo;

const TRUSTED_ASSOCIATIONS = new Set([
'OWNER',
'MEMBER',
'COLLABORATOR'
]);

const MAX_ISSUE_REFERENCES = 10;
const COMMENT_MARKER = '<!-- contribution-policy -->';

// Check whether the contributor is exempt
function isExempt(pull) {
return (
TRUSTED_ASSOCIATIONS.has(pull.author_association) ||
pull.user.type === 'Bot'
);
}

// Extract closing issue references
function parseIssueNumbers(body) {
return [
...body.matchAll(
/\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s+#(\d+)\b/gi
)
].map(match => Number(match[1]));
}

// Evaluate policy violations
function evaluate({
issueNumbers,
invalidIssues,
tooManyIssueReferences,
otherPull
}) {
return [
...(issueNumbers.length === 0
? [
'Link an open issue assigned to you using `Fixes #123`, `Closes #123`, or `Resolves #123`.'
]
: []),

...(tooManyIssueReferences
? [`Link at most ${MAX_ISSUE_REFERENCES} issues in one PR.`]
: []),

...invalidIssues.map(
number =>
`Issue #${number} must be open and assigned to the PR author.`
),

...(otherPull
? [
`Only one open PR is allowed per external contributor. PR #${otherPull.number} is already open.`
]
: [])
];
}

// Verify policy logic
const assert = require('node:assert/strict');
assert.deepEqual(parseIssueNumbers('Fixes #123\ncloses #9'), [123, 9]);
assert.deepEqual(parseIssueNumbers('Related to #7'), []);
assert.deepEqual(evaluate({ issueNumbers: [1], invalidIssues: [], tooManyIssueReferences: false }), []);
assert.equal(evaluate({ issueNumbers: [1, 2], invalidIssues: [2] })[0].includes('#2'), true);
assert.equal(evaluate({ issueNumbers: [1], invalidIssues: [], tooManyIssueReferences: false, otherPull: { number: 2 } })[0].includes('#2'), true);
assert.equal(evaluate({ issueNumbers: Array(11).fill(1), invalidIssues: [], tooManyIssueReferences: true })[0].includes('at most'), true);
assert.equal(isExempt({ draft: false, author_association: 'MEMBER', user: { type: 'User' } }), true);
assert.equal(isExempt({ draft: false, author_association: 'NONE', user: { type: 'Bot' } }), true);
// Drafts are not exempt: opening PRs as drafts must not bypass the one-open-PR limit.
assert.equal(isExempt({ draft: true, author_association: 'NONE', user: { type: 'User' } }), false);

assert.deepEqual(
parseIssueNumbers('Fixes #123\ncloses #9'),
[123, 9]
);

assert.deepEqual(
parseIssueNumbers('Related to #7'),
[]
);

assert.deepEqual(
evaluate({
issueNumbers: [1],
invalidIssues: [],
tooManyIssueReferences: false,
otherPull: null
}),
[]
);

assert.equal(
evaluate({
issueNumbers: [1],
invalidIssues: [2],
tooManyIssueReferences: false,
otherPull: null
})[0].includes('#2'),
true
);

assert.equal(
evaluate({
issueNumbers: [1],
invalidIssues: [],
tooManyIssueReferences: false,
otherPull: { number: 2 }
})[0].includes('#2'),
true
);

assert.equal(
evaluate({
issueNumbers: Array(11).fill(1),
invalidIssues: [],
tooManyIssueReferences: true,
otherPull: null
})[0].includes('at most'),
true
);

assert.equal(
isExempt({
author_association: 'MEMBER',
user: { type: 'User' }
}),
true
);

assert.equal(
isExempt({
author_association: 'NONE',
user: { type: 'Bot' }
}),
true
);

assert.equal(
isExempt({
author_association: 'NONE',
user: { type: 'User' }
}),
false
);

// Get pull request information
const pull = context.payload.pull_request;
if (isExempt(pull)) return;

const issueNumbers = [...new Set(parseIssueNumbers(pull.body ?? ''))];
const { owner, repo } = context.repo;
if (!pull) {
core.setFailed('Pull request information is missing.');
return;
}

// Skip trusted contributors and bots
if (isExempt(pull)) {
core.info(
`Skipping policy enforcement for trusted contributor @${pull.user.login}.`
);
return;
}

const author = pull.user.login.toLowerCase();
const tooManyIssueReferences = issueNumbers.length > maxIssueReferences;
const pullNumber = pull.number;

core.info(`Checking contribution policy for PR #${pullNumber}`);

// Parse and deduplicate issue references
const issueNumbers = [
...new Set(parseIssueNumbers(pull.body ?? ''))
];

const tooManyIssueReferences =
issueNumbers.length > MAX_ISSUE_REFERENCES;

const invalidIssues = [];
for (const issue_number of tooManyIssueReferences ? [] : issueNumbers) {
try {
const { data: issue } = await github.rest.issues.get({ owner, repo, issue_number });
const assigned = issue.state === 'open' && !issue.pull_request &&
issue.assignees.some((assignee) => assignee.login.toLowerCase() === author);
if (!assigned) invalidIssues.push(issue_number);
} catch (error) {
if (error.status !== 404) throw error;
invalidIssues.push(issue_number);

// Validate linked issues
if (!tooManyIssueReferences) {
for (const issueNumber of issueNumbers) {
try {
const { data: issue } =
await github.rest.issues.get({
owner,
repo,
issue_number: issueNumber
});

const isValidIssue =
issue.state === 'open' &&
!issue.pull_request &&
issue.assignees.some(
assignee =>
assignee.login.toLowerCase() === author
);

if (!isValidIssue) {
invalidIssues.push(issueNumber);
}

} catch (error) {
if (error.status === 404) {
invalidIssues.push(issueNumber);
} else {
throw error;
}
}
}
}

const openPulls = await github.paginate(github.rest.pulls.list, {
owner, repo, state: 'open', per_page: 100,
});
const otherPull = openPulls.find((candidate) =>
candidate.number !== pull.number && candidate.user.login.toLowerCase() === author);
const violations = evaluate({ issueNumbers, invalidIssues, tooManyIssueReferences, otherPull });
// Check for other open PRs from the same contributor
const openPulls = await github.paginate(
github.rest.pulls.list,
{
owner,
repo,
state: 'open',
per_page: 100
}
);

if (violations.length === 0) return;
const otherPull = openPulls.find(candidate =>
candidate.number !== pullNumber &&
candidate.user.login.toLowerCase() === author
);

const marker = '<!-- contribution-policy -->';
const body = `${marker}\nThis PR was closed by the contribution policy:\n\n${violations.map((item) => `- ${item}`).join('\n')}\n\nPlease resolve the items above, then reopen the PR.`;
const comments = await github.paginate(github.rest.issues.listComments, {
owner, repo, issue_number: pull.number, per_page: 100,
// Evaluate all violations
const violations = evaluate({
issueNumbers,
invalidIssues,
tooManyIssueReferences,
otherPull
});
const previous = comments.find((comment) => comment.body.includes(marker));
if (previous) {
await github.rest.issues.updateComment({ owner, repo, comment_id: previous.id, body });

if (violations.length === 0) {
core.info(
`PR #${pullNumber} passed all contribution policy checks.`
);
return;
}

// Prepare policy violation comment
const commentBody = [
COMMENT_MARKER,
'## Contribution Policy Violation',
'',
'This pull request has been automatically closed because it does not meet the repository contribution requirements.',
'',
...violations.map(item => `- ${item}`),
'',
'### How to resolve',
'',
'1. Link a valid open issue assigned to you.',
'2. Ensure the issue reference follows the required format.',
'3. Maintain only one open PR at a time.',
'4. Resolve all the violations listed above.',
'5. Reopen your PR after correcting the issues.',
'',
'Thank you for contributing!'
].join('\n');

// Find an existing policy comment
const comments = await github.paginate(
github.rest.issues.listComments,
{
owner,
repo,
issue_number: pullNumber,
per_page: 100
}
);

const previousComment = comments.find(comment =>
comment.body.includes(COMMENT_MARKER)
);

// Update or create the policy comment
if (previousComment) {
await github.rest.issues.updateComment({
owner,
repo,
comment_id: previousComment.id,
body: commentBody
});
} else {
await github.rest.issues.createComment({ owner, repo, issue_number: pull.number, body });
await github.rest.issues.createComment({
owner,
repo,
issue_number: pullNumber,
body: commentBody
});
}
await github.rest.pulls.update({ owner, repo, pull_number: pull.number, state: 'closed' });
core.setFailed(violations.join(' '));

// Close the violating pull request
await github.rest.pulls.update({
owner,
repo,
pull_number: pullNumber,
state: 'closed'
});

core.setFailed(
`PR #${pullNumber} closed due to contribution policy violations: ${violations.join(' ')}`
);
Loading