Repository navigation
Expand file tree
/
Copy pathnotify-non-employee-comments.yml
More file actions
296 lines (283 loc) · 12.3 KB
/
Copy pathnotify-non-employee-comments.yml
File metadata and controls
296 lines (283 loc) · 12.3 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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
name: Daily non-employee comment and review digest
# Include conversation comments, inline review comments, and submitted reviews without their bodies.
on:
workflow_dispatch:
schedule:
- cron: '20 16 * * *'
permissions:
contents: read
jobs:
notify:
if: github.repository == 'github/docs'
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- name: Check out repo
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
with:
persist-credentials: false
- name: Build daily digest
id: digest
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
with:
github-token: ${{ secrets.DOCS_BOT_PAT_BASE }}
script: |
// Octokit request logs include author names, even for expected non-member 404s.
github.log = {
...github.log,
debug: () => {},
info: () => {},
warn: () => {},
error: () => {},
};
// Fixed schedule boundaries avoid gaps or overlaps when scheduled runs start late.
const { data: run } = await github.rest.actions.getWorkflowRun({
...context.repo,
run_id: context.runId,
}).catch((error) => {
throw new Error(`Fetching workflow run failed (HTTP ${error.status || 'unknown'}).`);
});
const runCreatedAt = new Date(run.created_at);
const until = new Date(runCreatedAt.getTime());
until.setUTCHours(16, 20, 0, 0);
if (until.getTime() > runCreatedAt.getTime()) {
until.setUTCDate(until.getUTCDate() - 1);
}
const since = new Date(until.getTime() - 24 * 60 * 60 * 1000);
core.info(`Building digest for ${since.toISOString()} to ${until.toISOString()}.`);
const authors = new Map();
function addActivity({ author, createdAt, url, kind }) {
const timestamp = Date.parse(createdAt);
if (!(timestamp >= since.getTime() && timestamp < until.getTime())) {
return;
}
if (!author) {
core.warning('Skipping an activity whose author is unavailable.');
return;
}
const login = author.login.toLowerCase();
if (author.type === 'Bot' || author.__typename === 'Bot' ||
['docs-bot', 'copilot'].includes(login)) {
return;
}
if (!authors.has(login)) {
authors.set(login, { login: author.login, activities: [] });
}
authors.get(login).activities.push({ url, kind });
}
let page = 0;
try {
for (const listComments of [
github.rest.issues.listCommentsForRepo,
github.rest.pulls.listReviewCommentsForRepo,
]) {
for await (const { data: comments } of github.paginate.iterator(
listComments,
{
owner: 'github',
repo: 'docs',
since: since.toISOString(),
sort: 'created',
direction: 'asc',
per_page: 100,
},
)) {
core.info(`Fetched comments page ${++page} (${comments.length} comments).`);
for (const comment of comments) {
addActivity({
author: comment.user,
createdAt: comment.created_at,
url: comment.html_url,
kind: 'comment',
});
}
}
}
} catch (error) {
throw new Error(`Fetching digest comments failed (HTTP ${error.status || 'unknown'}).`);
}
const reviewFields = `
fragment digestReviews on PullRequest {
reviews(first: 100, after: $reviewsCursor) {
nodes {
author { login __typename }
submittedAt
url
}
pageInfo { hasNextPage endCursor }
}
}
`;
let pullRequestsCursor = null;
try {
do {
const { repository } = await github.graphql(`
query DigestPullRequests($pullRequestsCursor: String, $reviewsCursor: String) {
repository(owner: "github", name: "docs") {
pullRequests(first: 50, after: $pullRequestsCursor,
orderBy: { field: UPDATED_AT, direction: DESC }) {
nodes { id updatedAt ...digestReviews }
pageInfo { hasNextPage endCursor }
}
}
}
${reviewFields}
`, { pullRequestsCursor, reviewsCursor: null });
const pullRequests = repository.pullRequests;
const recentPullRequests = pullRequests.nodes.filter(
(pullRequest) => Date.parse(pullRequest.updatedAt) >= since.getTime(),
);
for (const pullRequest of recentPullRequests) {
let reviews = pullRequest.reviews;
while (true) {
for (const review of reviews.nodes) {
addActivity({
author: review.author,
createdAt: review.submittedAt,
url: review.url,
kind: 'review',
});
}
if (!reviews.pageInfo.hasNextPage) {
break;
}
const { node } = await github.graphql(`
query DigestReviewPage($id: ID!, $reviewsCursor: String) {
node(id: $id) { ...digestReviews }
}
${reviewFields}
`, { id: pullRequest.id, reviewsCursor: reviews.pageInfo.endCursor });
reviews = node.reviews;
}
}
// Updated ordering includes closed/merged PRs and lets us stop at the cutoff.
pullRequestsCursor = recentPullRequests.length === pullRequests.nodes.length &&
pullRequests.pageInfo.hasNextPage ? pullRequests.pageInfo.endCursor : null;
} while (pullRequestsCursor);
} catch (error) {
throw new Error(`Fetching digest reviews failed (HTTP ${error.status || 'unknown'}).`);
}
const nonEmployees = [];
let checked = 0;
for (const author of authors.values()) {
core.info(`Checking employee membership (${++checked}/${authors.size}).`);
try {
await github.rest.teams.getMembershipForUserInOrg({
org: 'github',
team_slug: 'employees',
username: author.login,
});
} catch (error) {
if (error.status !== 404) {
throw new Error(`Employee membership check failed (HTTP ${error.status || 'unknown'}).`);
}
nonEmployees.push(author);
}
}
const activities = nonEmployees.flatMap((author) => author.activities);
const totalComments = activities.filter((activity) => activity.kind === 'comment').length;
const totalReviews = activities.length - totalComments;
core.info(`Found ${totalComments} comments and ${totalReviews} reviews by ${nonEmployees.length} non-employees.`);
if (activities.length === 0) {
return;
}
const title = 'Daily non-employee comment and review digest for github/docs';
// Slack caps a table at 100 rows and 10,000 characters across its cells.
// Count link URLs as well as link text, because Slack does not document whether URLs count.
const maximumRows = 100;
let remainingCharacters = 10000;
let shortened = false;
const rawText = (text) => {
remainingCharacters -= text.length;
return { type: 'raw_text', text };
};
const richText = (elements) => ({
type: 'rich_text',
elements: [{ type: 'rich_text_section', elements }],
});
const rows = [[rawText('User'), rawText('Comments'), rawText('Reviews')]];
for (const author of nonEmployees) {
const profileUrl = `https://github.com/${author.login}`;
const rowCharacters = author.login.length + profileUrl.length + 2;
if (rows.length >= maximumRows || rowCharacters > remainingCharacters) {
shortened = true;
break;
}
remainingCharacters -= rowCharacters;
const row = [richText([{ type: 'link', url: profileUrl, text: author.login }])];
for (const kind of ['comment', 'review']) {
const urls = author.activities
.filter((activity) => activity.kind === kind)
.map((activity) => activity.url);
const links = [];
for (const [index, url] of urls.entries()) {
const text = `${index + 1}`;
const characters = text.length + url.length + (index ? 1 : 0);
if (shortened || characters > remainingCharacters) {
shortened = true;
break;
}
remainingCharacters -= characters;
if (index) {
links.push({ type: 'text', text: ' ' });
}
links.push({ type: 'link', url, text });
}
// The row reserves characters for this placeholder.
row.push(links.length ? richText(links) : { type: 'raw_text', text: '-' });
}
rows.push(row);
if (shortened) {
break;
}
}
if (shortened) {
core.warning('Digest shortened to fit one Slack table.');
}
const blocks = [
{
type: 'section',
text: {
type: 'mrkdwn',
text: `*${title}*\nCovers the 24 hours up to the most recent 16:20 UTC.` +
(shortened ? '\n_Digest shortened to fit one Slack table. Some authors or links are omitted._' : ''),
},
},
{
type: 'table',
column_settings: [{ is_wrapped: false }, { is_wrapped: true }, { is_wrapped: true }],
rows,
},
];
for (const author of nonEmployees) {
core.setSecret(author.login);
}
core.setOutput('slack_text', title);
core.setOutput('slack_blocks', JSON.stringify(blocks));
- name: Notify the docs-open-source channel
if: ${{ steps.digest.outputs.slack_blocks != '' }}
uses: slackapi/slack-github-action@dcb1066f776dd043e64d0e8ba94ca15cc7e1875d # v4.0.0
with:
method: chat.postMessage
token: ${{ secrets.SLACK_DOCS_BOT_TOKEN }}
errors: true
# Slack channel ID for docs-open-source.
payload: |
channel: C017M6T23GA
text: ${{ toJSON(steps.digest.outputs.slack_text) }}
blocks: ${{ steps.digest.outputs.slack_blocks }}
link_names: false
unfurl_links: false
unfurl_media: false
- uses: ./.github/actions/create-workflow-failure-issue
id: create-failure-issue
if: ${{ failure() }}
with:
token: ${{ secrets.DOCS_BOT_PAT_BASE }}
- name: Notify Slack about workflow failure
if: ${{ failure() }}
uses: ./.github/actions/slack-alert
with:
slack_token: ${{ secrets.SLACK_DOCS_BOT_TOKEN }}
slack_channel_id: C017M6T23GA
issue_url: ${{ steps.create-failure-issue.outputs.issue_url }}