-
Notifications
You must be signed in to change notification settings - Fork 48
374 lines (339 loc) · 16.8 KB
/
post-metrics-comment.yml
File metadata and controls
374 lines (339 loc) · 16.8 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
name: Post PR Metrics Comment
# Triggered after the "Build and Package" workflow completes. Runs in the
# context of the *base* repository, so it has full GITHUB_TOKEN write access
# even when the source build was for a PR opened from a fork — which is the
# scenario where posting from inside the build job fails with 403.
on:
workflow_run:
workflows: ["Build and Package"]
types: [completed]
permissions:
pull-requests: write # post / update the metrics comment
actions: read # download the metrics-data artifact from the source run
jobs:
post-comment:
# Only run for PR-driven builds. We intentionally do NOT gate on
# workflow_run.conclusion == 'success' — the *Build and Package*
# workflow contains additional jobs (e.g. e2e-test-ui) that run
# after metrics are collected, and a failure there shouldn't block
# posting valid metrics. The download step below is the real gate:
# it succeeds only if the source build produced a complete
# metrics-data artifact (binary-sizes.json + test-summary.json
# are required at upload time), and we skip the comment otherwise.
if: github.event.workflow_run.event == 'pull_request'
runs-on: ubuntu-latest
steps:
- name: Download metrics-data artifact
id: download
uses: actions/download-artifact@v4
with:
name: metrics-data
path: metrics-data
run-id: ${{ github.event.workflow_run.id }}
github-token: ${{ secrets.GITHUB_TOKEN }}
continue-on-error: true
- name: Skip if no metrics artifact
if: steps.download.outcome != 'success'
run: |
echo "::notice::Source build did not produce a metrics-data artifact (likely failed before the report-metrics step). Nothing to comment."
- name: Post / update PR metrics comment
if: steps.download.outcome == 'success'
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const fs = require('fs');
const dataPath = 'metrics-data';
// === SECURITY MODEL ===
// The `metrics-data` artifact is produced by a `pull_request`
// build that ran the PR's code, so every byte in it must be
// treated as attacker-controlled. We:
// * use ONLY trusted workflow_run metadata for head_sha and
// the source run id (never the artifact's pr-context.json),
// * resolve the PR number from the GitHub API by trusted
// head_sha and verify the PR's current head still matches,
// * whitelist all keys we render into the Markdown body so a
// malicious build can't inject table breaks, mentions,
// hidden HTML, or links.
const trustedHeadSha = context.payload.workflow_run.head_sha;
const sourceRunId = context.payload.workflow_run.id;
// Find the PR (or PRs) whose head is trustedHeadSha.
const { data: pulls } = await github.rest.repos.listPullRequestsAssociatedWithCommit({
owner: context.repo.owner,
repo: context.repo.repo,
commit_sha: trustedHeadSha,
});
// Keep only OPEN PRs whose CURRENT head still matches (skip if the
// user has pushed a newer commit since this build started — an
// older run shouldn't overwrite metrics for a newer one).
const candidate = pulls.find(p => p.state === 'open' && p.head && p.head.sha === trustedHeadSha);
if (!candidate) {
core.info(`No open PR with current head ${trustedHeadSha}; skipping (likely a newer commit was pushed).`);
return;
}
const prNumber = candidate.number;
// === Whitelisted metric keys ===
const ALLOWED_SIZE_KEYS = new Set([
'cli-win-x64', 'cli-win-arm64',
'npm-package',
'msix-x64', 'msix-arm64',
'nuget-package',
'vscode-extension',
]);
const labels = {
'cli-win-x64': 'CLI (x64)',
'cli-win-arm64': 'CLI (ARM64)',
'npm-package': 'NPM Package',
'msix-x64': 'MSIX (x64)',
'msix-arm64': 'MSIX (ARM64)',
'nuget-package': 'NuGet Package',
'vscode-extension': 'VS Code Extension',
};
// safeNum: coerce to a finite non-negative number or 0
function safeNum(v) {
const n = Number(v);
return Number.isFinite(n) && n >= 0 ? n : 0;
}
// sanitizeSizes: drop unknown keys, coerce values
function sanitizeSizes(obj) {
const out = {};
if (obj && typeof obj === 'object') {
for (const [k, v] of Object.entries(obj)) {
if (ALLOWED_SIZE_KEYS.has(k)) out[k] = safeNum(v);
}
}
return out;
}
// --- Load + sanitize current metrics ---
let current = {};
try { current = sanitizeSizes(JSON.parse(fs.readFileSync(`${dataPath}/binary-sizes.json`, 'utf8'))); } catch {}
let tests = { total: 0, passed: 0, failed: 0, skipped: 0, durationMs: 0 };
try {
const raw = JSON.parse(fs.readFileSync(`${dataPath}/test-summary.json`, 'utf8'));
tests = {
total: safeNum(raw.total),
passed: safeNum(raw.passed),
failed: safeNum(raw.failed),
skipped: safeNum(raw.skipped),
durationMs: safeNum(raw.durationMs),
};
} catch {}
let startup = { medianMs: 0 };
try {
const raw = JSON.parse(fs.readFileSync(`${dataPath}/startup-time.json`, 'utf8'));
startup = { medianMs: safeNum(raw.medianMs) };
} catch {}
// safePct: coerce to a finite number clamped to [0, 100], or null
function safePct(v) {
const n = Number(v);
if (!Number.isFinite(n)) return null;
if (n < 0 || n > 100) return null;
return n;
}
let coverage = { lineCoverage: null, branchCoverage: null };
try {
const raw = JSON.parse(fs.readFileSync(`${dataPath}/coverage-summary.json`, 'utf8'));
coverage = {
lineCoverage: safePct(raw.lineCoverage),
branchCoverage: safePct(raw.branchCoverage),
};
} catch {}
// --- Load + sanitize baselines (may be missing on first-ever PR) ---
let sizeBaseline = {};
let testsBaseline = null;
let startupBaseline = null;
let coverageBaseline = null;
let hasBaseline = false;
try {
sizeBaseline = sanitizeSizes(JSON.parse(fs.readFileSync(`${dataPath}/baseline/sizes.json`, 'utf8')));
hasBaseline = true;
} catch {}
try {
const raw = JSON.parse(fs.readFileSync(`${dataPath}/baseline/tests.json`, 'utf8'));
testsBaseline = { total: safeNum(raw.total), durationMs: safeNum(raw.durationMs) };
} catch {}
try {
const raw = JSON.parse(fs.readFileSync(`${dataPath}/baseline/startup.json`, 'utf8'));
startupBaseline = { medianMs: safeNum(raw.medianMs) };
} catch {}
try {
const raw = JSON.parse(fs.readFileSync(`${dataPath}/baseline/coverage.json`, 'utf8'));
coverageBaseline = { lineCoverage: safePct(raw.lineCoverage) };
} catch {}
// --- Artifact download links (resolved against the SOURCE run) ---
const artifactLinks = {};
try {
const { data: { artifacts } } = await github.rest.actions.listWorkflowRunArtifacts({
owner: context.repo.owner,
repo: context.repo.repo,
run_id: sourceRunId,
});
const artifactNameMap = {
'cli-win-x64': 'cli-binaries',
'cli-win-arm64': 'cli-binaries',
'npm-package': 'npm-package',
'msix-x64': 'msix-packages',
'msix-arm64': 'msix-packages',
'nuget-package': 'nuget-packages',
'vscode-extension': 'vscode-extension',
};
const runUrl = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${sourceRunId}`;
for (const [sizeKey, artifactName] of Object.entries(artifactNameMap)) {
const artifact = artifacts.find(a => a.name === artifactName);
if (artifact) {
artifactLinks[sizeKey] = `${runUrl}/artifacts/${artifact.id}`;
}
}
} catch (e) {
core.warning(`Could not fetch artifact links: ${e.message}`);
}
// --- Helpers ---
const COVERAGE_GOOD_THRESHOLD = 80;
const COVERAGE_WARN_THRESHOLD = 60;
const COVERAGE_MIN_DELTA = 0.1;
function formatBytes(bytes) {
const abs = Math.abs(bytes);
const mb = abs / (1024 * 1024);
if (mb >= 1) return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
const kb = bytes / 1024;
return `${kb.toFixed(1)} KB`;
}
function formatDelta(curr, base) {
const delta = curr - base;
const pct = base > 0 ? ((delta / base) * 100).toFixed(2) : 'N/A';
const sign = delta > 0 ? '+' : '';
let icon = ':white_check_mark:';
if (delta > 0) icon = ':chart_with_upwards_trend:';
else if (delta < 0) icon = ':chart_with_downwards_trend:';
return `${icon} ${sign}${formatBytes(delta)} (${sign}${pct}%)`;
}
function deltaMs(curr, base) {
const delta = curr - base;
if (Math.abs(delta) < 5) return ':white_check_mark: no change';
const sign = delta > 0 ? '+' : '';
const icon = delta > 10 ? ':warning:' : delta < -10 ? ':chart_with_downwards_trend:' : ':white_check_mark:';
return `${icon} ${sign}${delta}ms`;
}
function artifactLink(key, label) {
const url = artifactLinks[key];
return url ? `[${label}](${url})` : label;
}
let body = '## Build Metrics Report\n\n';
// --- Binary sizes ---
// (keys are already whitelisted via sanitizeSizes; labels[key] is always defined)
body += '### Binary Sizes\n\n';
if (hasBaseline) {
body += '| Artifact | Baseline | Current | Delta |\n';
body += '|----------|----------|---------|-------|\n';
const allKeys = [...new Set([...Object.keys(sizeBaseline), ...Object.keys(current)])].sort();
for (const key of allKeys) {
const label = labels[key];
if (!label) continue;
const linkedLabel = artifactLink(key, label);
const baseSize = sizeBaseline[key] || 0;
const currSize = current[key] || 0;
if (currSize === 0 && baseSize === 0) continue;
const baseStr = baseSize > 0 ? formatBytes(baseSize) : 'N/A';
const currStr = currSize > 0 ? formatBytes(currSize) : 'N/A';
const deltaStr = (baseSize > 0 && currSize > 0)
? formatDelta(currSize, baseSize) : 'N/A';
body += `| ${linkedLabel} | ${baseStr} | ${currStr} | ${deltaStr} |\n`;
}
} else {
body += '> No baseline found. Showing absolute sizes only.\n\n';
body += '| Artifact | Size |\n';
body += '|----------|------|\n';
for (const [key, size] of Object.entries(current).sort()) {
const label = labels[key];
if (!label) continue;
const linkedLabel = artifactLink(key, label);
body += `| ${linkedLabel} | ${formatBytes(size)} |\n`;
}
}
// --- Test summary ---
body += '\n### Test Results\n\n';
const testIcon = tests.failed > 0 ? ':x:' : ':white_check_mark:';
const durationSec = (tests.durationMs / 1000).toFixed(1);
body += `${testIcon} **${tests.passed}** passed`;
if (tests.failed > 0) body += `, **${tests.failed}** failed`;
if (tests.skipped > 0) body += `, **${tests.skipped}** skipped`;
body += ` out of **${tests.total}** tests in **${durationSec}s**`;
if (testsBaseline) {
const items = [];
const testDelta = tests.total - testsBaseline.total;
if (testDelta !== 0) {
const sign = testDelta > 0 ? '+' : '';
items.push(`${sign}${testDelta} test${Math.abs(testDelta) !== 1 ? 's' : ''}`);
}
const durDelta = tests.durationMs - testsBaseline.durationMs;
if (Math.abs(durDelta) >= 500) {
const sign = durDelta > 0 ? '+' : '';
items.push(`${sign}${(durDelta / 1000).toFixed(1)}s`);
}
if (items.length > 0) {
body += ` (${items.join(', ')} vs. baseline)`;
}
}
body += '\n';
// --- Test coverage ---
if (coverage.lineCoverage !== null) {
body += '\n### Test Coverage\n\n';
const coverageIcon = coverage.lineCoverage >= COVERAGE_GOOD_THRESHOLD ? ':white_check_mark:' : coverage.lineCoverage >= COVERAGE_WARN_THRESHOLD ? ':warning:' : ':x:';
body += `${coverageIcon} **${coverage.lineCoverage}%** line coverage`;
if (coverage.branchCoverage !== null) {
body += `, **${coverage.branchCoverage}%** branch coverage`;
}
if (coverageBaseline && coverageBaseline.lineCoverage !== null) {
const lineDelta = coverage.lineCoverage - coverageBaseline.lineCoverage;
if (Math.abs(lineDelta) >= COVERAGE_MIN_DELTA) {
const sign = lineDelta > 0 ? '+' : '';
const icon = lineDelta < 0 ? ':warning:' : ':white_check_mark:';
body += ` · ${icon} ${sign}${lineDelta.toFixed(1)}% vs. baseline`;
} else {
body += ' · :white_check_mark: no change vs. baseline';
}
}
body += '\n';
}
// --- Startup time ---
if (startup.medianMs > 0) {
body += '\n### CLI Startup Time\n\n';
body += `**${startup.medianMs}ms** median (x64, \`winapp --version\`)`;
if (startupBaseline && startupBaseline.medianMs > 0) {
body += ` · ${deltaMs(startup.medianMs, startupBaseline.medianMs)} vs. baseline`;
}
body += '\n';
}
// --- Footer (uses TRUSTED head_sha + source run id) ---
const timestamp = new Date().toISOString().replace('T', ' ').replace(/\.[0-9]+Z$/, ' UTC');
const shortSha = trustedHeadSha.substring(0, 7);
const commitUrl = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/commit/${trustedHeadSha}`;
const runUrl = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${sourceRunId}`;
body += `\n---\n*Updated ${timestamp} · commit [\`${shortSha}\`](${commitUrl}) · [workflow run](${runUrl})*\n`;
body += '\n<!-- build-metrics-report -->';
// --- Find existing comment (paginated) and update; otherwise create ---
const allComments = await github.paginate(github.rest.issues.listComments, {
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: prNumber,
per_page: 100,
});
const existing = allComments.find(c => c.body &&
(c.body.includes('<!-- build-metrics-report -->') || c.body.includes('<!-- binary-size-report -->')));
if (existing) {
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: existing.id,
body,
});
core.info(`Updated existing comment ${existing.id}`);
} else {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: prNumber,
body,
});
core.info('Created new metrics report comment');
}