-
Notifications
You must be signed in to change notification settings - Fork 287
Expand file tree
/
Copy pathbot-intermediate-assignment.js
More file actions
243 lines (200 loc) · 8.29 KB
/
Copy pathbot-intermediate-assignment.js
File metadata and controls
243 lines (200 loc) · 8.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
const shared = require('./shared/labels.js');
const COMMENT_MARKER = process.env.INTERMEDIATE_COMMENT_MARKER || '<!-- Intermediate Issue Guard -->';
const INTERMEDIATE_LABEL = process.env.INTERMEDIATE_LABEL?.trim() || shared.INTERMEDIATE_LABEL;
const BEGINNER_LABEL = process.env.BEGINNER_LABEL?.trim() || shared.BEGINNER_LABEL;
const EXEMPT_PERMISSION_LEVELS = (process.env.INTERMEDIATE_EXEMPT_PERMISSIONS || 'admin,maintain,write,triage')
.split(',')
.map((entry) => entry.trim().toLowerCase())
.filter(Boolean);
const DRY_RUN = /^true$/i.test(process.env.DRY_RUN || '');
const REQUIRED_BEGINNER_ISSUE_COUNT = 1 ;
function isSafeSearchToken(value) {
return typeof value === 'string' && /^[a-zA-Z0-9._/-]+$/.test(value);
}
function hasLabel(issue, labelName) {
if (!issue?.labels?.length) {
return false;
}
return issue.labels.some((label) => {
const name = typeof label === 'string' ? label : label?.name;
return typeof name === 'string' && name.toLowerCase() === labelName.toLowerCase();
});
}
async function hasExemptPermission(github, owner, repo, username) {
if (!EXEMPT_PERMISSION_LEVELS.length) {
console.log(`No exempt permission levels configured. Skipping permission check for ${username} in ${owner}/${repo}.`);
return false;
}
console.log(`Checking repository permissions for ${username} in ${owner}/${repo} against exempt levels: [${EXEMPT_PERMISSION_LEVELS.join(', ')}]`);
try {
const response = await github.rest.repos.getCollaboratorPermissionLevel({
owner,
repo,
username,
});
const permission = response?.data?.permission?.toLowerCase();
const isExempt = Boolean(permission) && EXEMPT_PERMISSION_LEVELS.includes(permission);
console.log(`Permission check for ${username} in ${owner}/${repo}: permission='${permission}', exempt=${isExempt}`);
return isExempt;
} catch (error) {
if (error?.status === 404) {
console.log(`User ${username} not found as collaborator in ${owner}/${repo} (404). Treating as non-exempt.`);
return false;
}
const message = error instanceof Error ? error.message : String(error);
console.log(`Unable to verify ${username}'s repository permissions in ${owner}/${repo}: ${message}`);
return false;
}
}
async function countCompletedBeginnerIssues(github, owner, repo, username) {
if (
!isSafeSearchToken(owner) ||
!isSafeSearchToken(repo) ||
!isSafeSearchToken(username) ||
!shared.isSafeLabel(BEGINNER_LABEL)
) {
console.log('Invalid search inputs', {
owner,
repo,
username,
label: BEGINNER_LABEL,
});
return null;
}
try {
const searchQuery = [
`repo:${owner}/${repo}`,
`label:"${BEGINNER_LABEL}"`,
'is:issue',
'is:closed',
`assignee:${username}`,
].join(' ');
console.log('GraphQL search query:', searchQuery);
const result = await github.graphql(
`
query ($searchQuery: String!) {
search(type: ISSUE, query: $searchQuery) {
issueCount
}
}
`,
{ searchQuery }
);
const count = result?.search?.issueCount ?? 0;
console.log(`Completed Beginner issues for ${username}: ${count}`);
return count;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.log(
`Failed to count Beginner issues for ${username}: ${message}`
);
return null;
}
}
async function hasExistingGuardComment(github, owner, repo, issueNumber, mentee) {
const comments = await github.paginate(github.rest.issues.listComments, {
owner,
repo,
issue_number: issueNumber,
per_page: 100,
});
return comments.some((comment) => {
if (!comment?.body?.includes(COMMENT_MARKER)) {
return false;
}
const normalizedBody = comment.body.toLowerCase();
const normalizedMentee = `@${mentee}`.toLowerCase();
return normalizedBody.includes(normalizedMentee);
});
}
function buildRejectionComment({ mentee, completedCount }) {
const plural = completedCount === 1 ? '' : 's';
return `${COMMENT_MARKER}
Hi @${mentee}! Thanks for your interest in contributing 💡
This issue is labeled as intermediate, which means it requires a bit more familiarity with the SDK.
Before you can take it on, please complete at least one Beginner Issue so we can make sure you have a smooth on-ramp.
You've completed **${completedCount}** Beginner Issue${plural} so far.
Once you wrap up your first Beginner issue, feel free to come back and we’ll gladly help you get rolling here!`;
}
module.exports = async ({ github, context }) => {
try {
if (DRY_RUN) {
console.log('Running intermediate guard in dry-run mode: no assignee removals or comments will be posted.');
}
const issue = context.payload.issue;
const assignee = context.payload.assignee;
if (!issue?.number || !assignee?.login) {
return console.log('Missing issue or assignee in payload. Skipping intermediate guard.');
}
const { owner, repo } = context.repo;
const mentee = assignee.login;
console.log(`Processing intermediate guard for issue #${issue.number} in ${owner}/${repo}: assignee=${mentee}, dry_run=${DRY_RUN}`);
if (!hasLabel(issue, INTERMEDIATE_LABEL)) {
return console.log(`Issue #${issue.number} is not labeled '${INTERMEDIATE_LABEL}'. Skipping.`);
}
if (assignee.type === 'Bot') {
return console.log(`Assignee ${mentee} is a bot. Skipping.`);
}
if (await hasExemptPermission(github, owner, repo, mentee)) {
console.log(`✅ ${mentee} has exempt repository permissions in ${owner}/${repo}. Skipping guard.`);
return;
}
const completedCount = await countCompletedBeginnerIssues(github, owner, repo, mentee);
if (completedCount === null) {
return console.log(`Skipping guard for @${mentee} on issue #${issue.number} due to API error when verifying Beginner issues.`);
}
if(REQUIRED_BEGINNER_ISSUE_COUNT === 0){
return console.log(`Skipping guard for @${mentee} on issue #${issue.number}: beginner requirement temporarily disabled`)
}
if (completedCount >= REQUIRED_BEGINNER_ISSUE_COUNT) {
console.log(`✅ ${mentee} has completed ${completedCount} Beginner issues. Assignment allowed.`);
return;
}
console.log(`❌ ${mentee} has completed ${completedCount} Beginner issues. Assignment not allowed; proceeding with removal and comment.`);
try {
if (DRY_RUN) {
console.log(`[dry-run] Would remove @${mentee} from issue #${issue.number} due to missing Beginner issue completion.`);
} else {
await github.rest.issues.removeAssignees({
owner,
repo,
issue_number: issue.number,
assignees: [mentee],
});
console.log(`Removed @${mentee} from issue #${issue.number} due to missing Beginner issue completion.`);
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.log(`Unable to remove assignee ${mentee} from issue #${issue.number}: ${message}`);
}
try {
if (await hasExistingGuardComment(github, owner, repo, issue.number, mentee)) {
return console.log(`Guard comment already exists on issue #${issue.number}. Skipping duplicate message.`);
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.log(`Unable to check for existing guard comment: ${message}. Proceeding to post comment anyway (accepting small risk of duplicate).`);
}
const comment = buildRejectionComment({ mentee, completedCount });
try {
if (DRY_RUN) {
console.log('[dry-run] Would post guard comment with body:\n', comment);
} else {
await github.rest.issues.createComment({
owner,
repo,
issue_number: issue.number,
body: comment,
});
console.log(`Posted guard comment for @${mentee} on issue #${issue.number}.`);
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.log(`Unable to post guard comment for @${mentee} on issue #${issue.number}: ${message}`);
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.log(`❌ Intermediate assignment guard failed: ${message}`);
throw error;
}
};