-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathpr-statistics.js
More file actions
374 lines (312 loc) · 11.4 KB
/
pr-statistics.js
File metadata and controls
374 lines (312 loc) · 11.4 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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
const { PR_STATS_REPOS } = require('./constants');
const ORG = 'learningequality';
const ROLLING_WINDOW_DAYS = 30;
/**
* Unicode block characters for sparklines, from lowest to highest.
*/
const SPARKLINE_CHARS = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
/**
* Generate a sparkline string from an array of numeric values.
* Maps each value to a Unicode block character based on its relative position
* between the min and max values.
*/
function sparkline(values) {
if (!values || values.length === 0) return '';
const min = Math.min(...values);
const max = Math.max(...values);
// If all values are the same, return middle-height bars
if (max === min) {
return SPARKLINE_CHARS[3].repeat(values.length);
}
return values
.map(value => {
// Normalize to 0-1 range
const normalized = (value - min) / (max - min);
// Map to character index (0-7)
const index = Math.min(
Math.floor(normalized * SPARKLINE_CHARS.length),
SPARKLINE_CHARS.length - 1,
);
return SPARKLINE_CHARS[index];
})
.join('');
}
/**
* Create a histogram from an array of values using logarithmic binning.
* This handles skewed distributions (common in time-based metrics) much better
* than linear binning by spreading out long-tailed data.
* Returns an array of bin counts.
*/
function histogram(values, numBins = 10) {
if (!values || values.length === 0) return [];
const min = Math.min(...values);
const max = Math.max(...values);
// If all values are the same, put them all in one bin
if (max === min) {
const bins = new Array(numBins).fill(0);
bins[Math.floor(numBins / 2)] = values.length;
return bins;
}
// Use logarithmic binning for better visualization of skewed distributions
// Add 1 to avoid log(0) issues and ensure all values are positive
const logMin = Math.log(min + 1);
const logMax = Math.log(max + 1);
const logBinWidth = (logMax - logMin) / numBins;
const bins = new Array(numBins).fill(0);
values.forEach(value => {
const logValue = Math.log(value + 1);
let binIndex = Math.floor((logValue - logMin) / logBinWidth);
// Handle edge case where value equals max
if (binIndex >= numBins) binIndex = numBins - 1;
bins[binIndex]++;
});
return bins;
}
/**
* Generate a distribution sparkline from raw data values.
* Creates a histogram and converts bin counts to a sparkline.
*/
function distributionSparkline(values, numBins = 10) {
const bins = histogram(values, numBins);
return sparkline(bins);
}
/**
* Calculate percentile value from a sorted array of numbers.
* Uses linear interpolation between closest ranks.
*/
function percentile(sortedArr, p) {
if (sortedArr.length === 0) return null;
if (sortedArr.length === 1) return sortedArr[0];
const index = (p / 100) * (sortedArr.length - 1);
const lower = Math.floor(index);
const upper = Math.ceil(index);
const weight = index - lower;
if (upper >= sortedArr.length) return sortedArr[sortedArr.length - 1];
return sortedArr[lower] * (1 - weight) + sortedArr[upper] * weight;
}
/**
* Format milliseconds into human-readable duration.
*/
function formatDuration(ms) {
if (ms === null || ms === undefined) return 'N/A';
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
if (days > 0) {
const remainingHours = hours % 24;
if (remainingHours > 0) {
return `${days}d ${remainingHours}h`;
}
return `${days}d`;
}
if (hours > 0) {
const remainingMinutes = minutes % 60;
if (remainingMinutes > 0) {
return `${hours}h ${remainingMinutes}m`;
}
return `${hours}h`;
}
if (minutes > 0) {
return `${minutes}m`;
}
return '<1m';
}
/**
* Fetch all PRs for a repository updated within the rolling window.
*/
async function fetchPRsForRepo(github, owner, repo, sinceDate) {
const prs = [];
let page = 1;
const perPage = 100;
// eslint-disable-next-line no-constant-condition
while (true) {
try {
const response = await github.rest.pulls.list({
owner,
repo,
state: 'all',
sort: 'updated',
direction: 'desc',
per_page: perPage,
page,
});
if (response.data.length === 0) break;
// Filter PRs updated within the rolling window
const relevantPRs = response.data.filter(pr => new Date(pr.updated_at) >= sinceDate);
prs.push(...relevantPRs);
// If we got fewer PRs than requested or all remaining PRs are outside window, stop
if (response.data.length < perPage) break;
// If the last PR in this page is outside our window, we can stop
const lastPR = response.data[response.data.length - 1];
if (new Date(lastPR.updated_at) < sinceDate) break;
page++;
} catch (error) {
// eslint-disable-next-line no-console
console.error(`Error fetching PRs for ${owner}/${repo} page ${page}:`, error.message);
break;
}
}
return prs;
}
/**
* Fetch reviews for a PR and return the first review timestamp.
*/
async function getFirstReviewTime(github, owner, repo, pullNumber) {
try {
const response = await github.rest.pulls.listReviews({
owner,
repo,
pull_number: pullNumber,
per_page: 100,
});
if (response.data.length === 0) return null;
// Find the earliest review
const reviewTimes = response.data
.filter(review => review.submitted_at)
.map(review => new Date(review.submitted_at).getTime());
if (reviewTimes.length === 0) return null;
return Math.min(...reviewTimes);
} catch (error) {
// eslint-disable-next-line no-console
console.error(`Error fetching reviews for ${owner}/${repo}#${pullNumber}:`, error.message);
return null;
}
}
/**
* Main function to calculate PR statistics.
*/
module.exports = async ({ github, core }) => {
const now = new Date();
const sinceDate = new Date(now.getTime() - ROLLING_WINDOW_DAYS * 24 * 60 * 60 * 1000);
// eslint-disable-next-line no-console
console.log(`Calculating PR statistics for ${ROLLING_WINDOW_DAYS}-day rolling window`);
// eslint-disable-next-line no-console
console.log(`Since: ${sinceDate.toISOString()}`);
// eslint-disable-next-line no-console
console.log(`Repositories: ${PR_STATS_REPOS.join(', ')}`);
// Collect all time-to-first-review values (in milliseconds)
const timeToFirstReviewValues = [];
// Collect all PR lifespan values for closed/merged PRs (in milliseconds)
const lifespanValues = [];
// Count open PRs without reviews
const openUnreviewedPRs = [];
// Track totals for reporting
let totalPRsProcessed = 0;
let totalReviewedPRs = 0;
let totalClosedPRs = 0;
for (const repo of PR_STATS_REPOS) {
// eslint-disable-next-line no-console
console.log(`\nProcessing ${ORG}/${repo}...`);
const prs = await fetchPRsForRepo(github, ORG, repo, sinceDate);
// eslint-disable-next-line no-console
console.log(` Found ${prs.length} PRs updated in rolling window`);
for (const pr of prs) {
totalPRsProcessed++;
const prCreatedAt = new Date(pr.created_at).getTime();
// Get first review time
const firstReviewTime = await getFirstReviewTime(github, ORG, repo, pr.number);
if (pr.state === 'open') {
// Check if open PR has no reviews
if (firstReviewTime === null) {
openUnreviewedPRs.push({
repo,
number: pr.number,
title: pr.title,
url: pr.html_url,
createdAt: pr.created_at,
});
} else {
// Open PR with review - calculate time to first review
const timeToReview = firstReviewTime - prCreatedAt;
if (timeToReview >= 0) {
timeToFirstReviewValues.push(timeToReview);
totalReviewedPRs++;
}
}
} else {
// Closed or merged PR
const prClosedAt = new Date(pr.closed_at).getTime();
const lifespan = prClosedAt - prCreatedAt;
if (lifespan >= 0) {
lifespanValues.push(lifespan);
totalClosedPRs++;
}
// If it had a review, calculate time to first review
if (firstReviewTime !== null) {
const timeToReview = firstReviewTime - prCreatedAt;
if (timeToReview >= 0) {
timeToFirstReviewValues.push(timeToReview);
totalReviewedPRs++;
}
}
}
}
}
// Sort arrays for percentile calculations
timeToFirstReviewValues.sort((a, b) => a - b);
lifespanValues.sort((a, b) => a - b);
// Calculate statistics
const timeToReviewMedian = percentile(timeToFirstReviewValues, 50);
const timeToReviewP95 = percentile(timeToFirstReviewValues, 95);
const lifespanMedian = percentile(lifespanValues, 50);
const lifespanP95 = percentile(lifespanValues, 95);
// eslint-disable-next-line no-console
console.log('\n--- Statistics ---');
// eslint-disable-next-line no-console
console.log(`Total PRs processed: ${totalPRsProcessed}`);
// eslint-disable-next-line no-console
console.log(`Reviewed PRs: ${totalReviewedPRs}`);
// eslint-disable-next-line no-console
console.log(`Closed/Merged PRs: ${totalClosedPRs}`);
// eslint-disable-next-line no-console
console.log(`Open unreviewed PRs: ${openUnreviewedPRs.length}`);
// eslint-disable-next-line no-console
console.log(
`Time to first review - Median: ${formatDuration(timeToReviewMedian)}, P95: ${formatDuration(timeToReviewP95)}`,
);
// eslint-disable-next-line no-console
console.log(
`PR lifespan - Median: ${formatDuration(lifespanMedian)}, P95: ${formatDuration(lifespanP95)}`,
);
// Format date for report
const reportDate = now.toLocaleDateString('en-US', {
weekday: 'short',
month: 'short',
day: 'numeric',
year: 'numeric',
});
// Build Slack message
let slackMessage = `*Weekly PR Statistics Report*\n`;
slackMessage += `_${ROLLING_WINDOW_DAYS}-day rolling window | Generated ${reportDate}_\n\n`;
slackMessage += `*Time to First Review*\n`;
if (timeToFirstReviewValues.length > 0) {
slackMessage += `Median: ${formatDuration(timeToReviewMedian)} | 95th percentile: ${formatDuration(timeToReviewP95)}\n`;
slackMessage += `Distribution: ${distributionSparkline(timeToFirstReviewValues)}\n`;
slackMessage += `_Based on ${totalReviewedPRs} reviewed PRs_\n\n`;
} else {
slackMessage += `_No reviewed PRs in this period_\n\n`;
}
slackMessage += `*PR Lifespan (Open to Close/Merge)*\n`;
if (lifespanValues.length > 0) {
slackMessage += `Median: ${formatDuration(lifespanMedian)} | 95th percentile: ${formatDuration(lifespanP95)}\n`;
slackMessage += `Distribution: ${distributionSparkline(lifespanValues)}\n`;
slackMessage += `_Based on ${totalClosedPRs} closed/merged PRs_\n\n`;
} else {
slackMessage += `_No closed PRs in this period_\n\n`;
}
slackMessage += `*Open Unreviewed PRs*\n`;
if (openUnreviewedPRs.length > 0) {
slackMessage += `${openUnreviewedPRs.length} PR${openUnreviewedPRs.length === 1 ? '' : 's'} awaiting first review\n`;
} else {
slackMessage += `All open PRs have been reviewed\n`;
}
slackMessage += `\n_Repos: ${PR_STATS_REPOS.join(', ')}_`;
// Set outputs
core.setOutput('slack_message', slackMessage);
core.setOutput('total_prs', totalPRsProcessed);
core.setOutput('reviewed_prs', totalReviewedPRs);
core.setOutput('closed_prs', totalClosedPRs);
core.setOutput('open_unreviewed_prs', openUnreviewedPRs.length);
return slackMessage;
};