-
Notifications
You must be signed in to change notification settings - Fork 31.9k
Expand file tree
/
Copy pathpr-logs.js
More file actions
426 lines (366 loc) · 10.6 KB
/
Copy pathpr-logs.js
File metadata and controls
426 lines (366 loc) · 10.6 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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
#!/usr/bin/env node
const { execFileSync, spawn } = require('child_process')
const fs = require('fs/promises')
const path = require('path')
const OWNER = 'vercel'
const REPO = 'next.js'
const WORKFLOW_NAME = 'build-and-test'
const OUTPUT_ROOT = path.join(__dirname, 'pr-logs')
const FAILED_CONCLUSIONS = new Set(['failure', 'timed_out', 'startup_failure'])
const LOG_TIMESTAMP_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z\s?/
function execGh(args) {
try {
return execFileSync('gh', args, {
encoding: 'utf8',
maxBuffer: 50 * 1024 * 1024,
}).trim()
} catch (error) {
const command = `gh ${args.join(' ')}`
console.error(`Command failed: ${command}`)
console.error(error.stderr || error.message)
throw error
}
}
function execGhJson(args) {
const output = execGh(args)
return JSON.parse(output)
}
function execGhLines(args) {
const output = execGh(args)
if (!output) return []
return output
.split('\n')
.filter((line) => line.trim())
.map((line) => JSON.parse(line))
}
function execGhTextAsync(args) {
return new Promise((resolve, reject) => {
const child = spawn('gh', args, {
stdio: ['ignore', 'pipe', 'pipe'],
})
const chunks = []
let stderr = ''
child.stdout.on('data', (chunk) => chunks.push(chunk))
child.stderr.on('data', (chunk) => {
stderr += chunk
})
child.on('close', (code) => {
if (code !== 0) {
const error = new Error(`Command failed: gh ${args.join(' ')}`)
error.stderr = stderr.trim()
reject(error)
return
}
resolve(Buffer.concat(chunks).toString('utf8'))
})
child.on('error', reject)
})
}
function stripLogTimestamps(logs) {
return logs
.split('\n')
.map((line) => line.replace(LOG_TIMESTAMP_RE, ''))
.join('\n')
}
function sanitizeFilename(name) {
return String(name)
.replace(/[^a-zA-Z0-9._-]/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '')
.slice(0, 100)
}
function formatDuration(startedAt, completedAt) {
if (!startedAt || !completedAt) return 'N/A'
const start = new Date(startedAt)
const end = new Date(completedAt)
if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) return 'N/A'
const totalSeconds = Math.floor((end - start) / 1000)
if (totalSeconds < 0) return 'N/A'
if (totalSeconds < 60) return `${totalSeconds}s`
const minutes = Math.floor(totalSeconds / 60)
const seconds = totalSeconds % 60
return `${minutes}m ${seconds}s`
}
function formatStatus(job) {
return job.conclusion ? `${job.status}/${job.conclusion}` : job.status
}
function usage() {
console.log(`Usage: node scripts/pr-logs.js [PR_NUMBER] [--wait] [--failed-only]
Downloads CI job logs for the latest "${WORKFLOW_NAME}" run on the current PR.
Options:
--wait Wait for the current run to finish before downloading logs
--failed-only Only download logs for failed jobs
--help Show this help text
`)
}
function getBranchInfo(prNumberArg) {
if (prNumberArg) {
try {
const data = execGhJson([
'pr',
'view',
String(prNumberArg),
'--json',
'number,headRefName',
])
return {
prNumber: String(data.number),
branchName: data.headRefName,
}
} catch {
console.error(`Failed to fetch PR #${prNumberArg}`)
process.exit(1)
}
}
try {
const data = execGhJson(['pr', 'view', '--json', 'number,headRefName'])
return {
prNumber: String(data.number),
branchName: data.headRefName,
}
} catch {
console.error(
'Could not detect a PR from the current branch. Pass a PR number explicitly.'
)
process.exit(1)
}
}
function getLatestWorkflowRun(branchName) {
const route = `repos/${OWNER}/${REPO}/actions/runs?branch=${encodeURIComponent(branchName)}&per_page=20`
const runs = execGhLines([
'api',
route,
'--jq',
`.workflow_runs[] | select(.name == "${WORKFLOW_NAME}") | {id, name, status, conclusion, run_attempt, html_url, created_at, updated_at}`,
])
return runs[0] || null
}
function getRunMetadata(runId) {
return execGhJson([
'api',
`repos/${OWNER}/${REPO}/actions/runs/${runId}`,
'--jq',
'{id, name, status, conclusion, run_attempt, html_url, created_at, updated_at}',
])
}
function getJobsForRunAttempt(runId, runAttempt) {
const jobs = []
let page = 1
while (true) {
const pageJobs = execGhLines([
'api',
`repos/${OWNER}/${REPO}/actions/runs/${runId}/attempts/${runAttempt}/jobs?per_page=100&page=${page}`,
'--jq',
'.jobs[] | {id, name, status, conclusion, started_at, completed_at, html_url}',
])
if (pageJobs.length === 0) {
break
}
jobs.push(...pageJobs)
if (pageJobs.length < 100) {
break
}
page += 1
}
return jobs
}
async function downloadJobLog(jobId) {
const logs = await execGhTextAsync([
'api',
`repos/${OWNER}/${REPO}/actions/jobs/${jobId}/logs`,
])
return stripLogTimestamps(logs)
}
async function mapLimit(items, limit, mapper) {
const queue = [...items]
const workers = Array.from(
{ length: Math.min(limit, queue.length) },
async () => {
while (queue.length > 0) {
const item = queue.shift()
await mapper(item)
}
}
)
await Promise.all(workers)
}
function buildOutputDir(prNumber, runId, runAttempt) {
return path.join(
OUTPUT_ROOT,
`pr-${prNumber}`,
`run-${runId}-attempt-${runAttempt}`
)
}
function buildIndexLog(branchInfo, runMetadata, jobs, results, outputDir) {
const lines = [
`PR: #${branchInfo.prNumber}`,
`Branch: ${branchInfo.branchName}`,
`Workflow: ${runMetadata.name}`,
`Run: ${runMetadata.id} (attempt ${runMetadata.run_attempt})`,
`Status: ${
runMetadata.conclusion
? `${runMetadata.status}/${runMetadata.conclusion}`
: runMetadata.status
}`,
`Created: ${runMetadata.created_at}`,
`Updated: ${runMetadata.updated_at || 'N/A'}`,
`URL: ${runMetadata.html_url}`,
`Output: ${outputDir}`,
'',
`Jobs considered: ${jobs.length}`,
`Logs downloaded: ${results.filter((result) => result.downloaded).length}`,
`Logs skipped: ${results.filter((result) => result.skippedReason).length}`,
`Log download errors: ${results.filter((result) => result.error).length}`,
'',
'Jobs:',
'',
]
for (const result of results) {
const duration = formatDuration(
result.job.started_at,
result.job.completed_at
)
lines.push(
`- ${result.job.id} | ${formatStatus(result.job)} | ${duration} | ${result.job.name}`
)
if (result.fileName) {
lines.push(` file: ${result.fileName}`)
}
if (result.skippedReason) {
lines.push(` skipped: ${result.skippedReason}`)
}
if (result.error) {
lines.push(` error: ${result.error}`)
}
}
return `${lines.join('\n')}\n`
}
async function main() {
const args = process.argv.slice(2)
if (args.includes('--help')) {
usage()
return
}
const waitFlag = args.includes('--wait')
const failedOnly = args.includes('--failed-only')
const prNumberArg = args.find((arg) => !arg.startsWith('--'))
console.log('Resolving PR...')
const branchInfo = getBranchInfo(prNumberArg)
console.log(`Using PR #${branchInfo.prNumber} (${branchInfo.branchName})`)
console.log('Finding latest workflow run...')
let runMetadata = getLatestWorkflowRun(branchInfo.branchName)
if (!runMetadata) {
console.error(
`No "${WORKFLOW_NAME}" workflow runs found for branch ${branchInfo.branchName}.`
)
process.exit(1)
}
if (
waitFlag &&
(runMetadata.status === 'queued' || runMetadata.status === 'in_progress')
) {
console.log(`Waiting for run ${runMetadata.id} to complete...`)
try {
execFileSync(
'gh',
[
'run',
'watch',
String(runMetadata.id),
'--compact',
'-R',
`${OWNER}/${REPO}`,
],
{ stdio: 'inherit' }
)
} catch {
// gh run watch exits non-zero when the run fails, which is expected here.
}
runMetadata = getRunMetadata(runMetadata.id)
}
console.log(
`Fetching jobs for run ${runMetadata.id} (attempt ${runMetadata.run_attempt})...`
)
const allJobs = getJobsForRunAttempt(runMetadata.id, runMetadata.run_attempt)
const jobs = failedOnly
? allJobs.filter((job) => FAILED_CONCLUSIONS.has(job.conclusion))
: allJobs
const outputDir = buildOutputDir(
branchInfo.prNumber,
runMetadata.id,
runMetadata.run_attempt
)
await fs.rm(outputDir, { recursive: true, force: true })
await fs.mkdir(outputDir, { recursive: true })
if (jobs.length === 0) {
const indexLog = buildIndexLog(branchInfo, runMetadata, jobs, [], outputDir)
await fs.writeFile(path.join(outputDir, 'index.log'), indexLog)
console.log(
`No matching jobs found. Wrote summary to ${outputDir}/index.log`
)
return
}
const results = new Array(jobs.length)
console.log(`Downloading logs for ${jobs.length} job(s)...`)
await mapLimit(
jobs.map((job, index) => ({ job, index })),
4,
async (entry) => {
const { job, index } = entry
const fileName = `job-${job.id}-${sanitizeFilename(job.name || 'job')}.log`
const filePath = path.join(outputDir, fileName)
if (job.status === 'queued') {
results[index] = {
job,
downloaded: false,
skippedReason: 'job is still queued',
}
return
}
if (job.conclusion === 'skipped') {
results[index] = {
job,
downloaded: false,
skippedReason: 'job was skipped',
}
return
}
try {
const logs = await downloadJobLog(job.id)
await fs.writeFile(filePath, logs)
results[index] = {
job,
downloaded: true,
fileName,
}
} catch (error) {
const message =
error.stderr || error.message || 'Unknown error while fetching logs'
await fs.writeFile(
filePath,
`Failed to download logs for job ${job.id} (${job.name})\n\n${message}\n`
)
results[index] = {
job,
downloaded: false,
fileName,
error: message.replace(/\s+/g, ' ').trim(),
}
}
}
)
const indexLog = buildIndexLog(
branchInfo,
runMetadata,
jobs,
results,
outputDir
)
await fs.writeFile(path.join(outputDir, 'index.log'), indexLog)
console.log(`Done. Logs written to ${outputDir}`)
console.log(`Summary: ${outputDir}/index.log`)
}
main().catch((error) => {
console.error(error)
process.exit(1)
})