-
Notifications
You must be signed in to change notification settings - Fork 0
/
github.js
717 lines (642 loc) · 20.9 KB
/
github.js
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
// const { Octokit } = require('@octokit/rest') // https://github.com/octokit/rest.js
const fs = require('fs')
const github = require('@actions/github')
const core = require('@actions/core')
const { DefaultArtifactClient } = require('@actions/artifact')
const cp = require('child_process')
function exec (cmd) {
console.log('$ ', cmd)
// inherit stderr, capture stdout
return cp.execSync(cmd, { stdio: ['inherit', 'pipe'] }).toString()
}
// const runningOverActions = !!process.env.GITHUB_ACTIONS
function mod (githubContext, githubToken) {
const debug = github.context?.action
? console.log
: (process.env.DEBUG ? console.debug.bind(null, '[GAH]') : () => {})
const context = githubContext || github.context
if (!context?.repo) throw new Error('Invalid arguments')
const token = githubToken || core.getInput('token') || process.env.GITHUB_TOKEN
if (!token) {
console.error('No Github token was specified, please see the documentation for correct Action usage.')
process.exit(1)
}
// Depending on if we are using a PAT or the default GITHUB_TOKEN, the currentAuthor is different which matters when searching for bot PRs
// https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/about-authentication-to-github#githubs-token-formats
const isPAT = !token.startsWith('ghs_')
const currentAuthor = isPAT ? '@me' : 'app/github-actions'
const octokit = github.getOctokit(token)
// Full context object: https://github.com/actions/toolkit/blob/main/packages/github/src/context.ts
const fullName = context.repo.fullName || (context.repo.owner + '/' + context.repo.repo)
const artifact = new DefaultArtifactClient()
const getInput = (name, required = false) => core.getInput(name, { required })
let currentUserData
async function getCurrentUser () {
if (currentUserData) return currentUserData
const user = await octokit.rest.users.getAuthenticated()
currentUserData = {
login: user.data.login,
name: user.data.name,
email: user.data.email,
avatar: user.data.avatar_url
}
return currentUserData
}
function _sendRequestWithCURL (url, jsonPayload) {
jsonPayload = typeof jsonPayload === 'string' ? jsonPayload : JSON.stringify(jsonPayload)
const escapedPayload = jsonPayload.replace(/'/g, "\\'")
const cmd = `curl -X POST -H "Accept: application/vnd.github.v3+json" -H "Authorization: token ${token}" -d '${escapedPayload}' ${url}`
const result = exec(cmd)
console.log('> ', result)
return JSON.parse(result)
}
// Artifacts
async function uploadArtifact (name, files, filesRoot, options) {
const { id, size } = await artifact.uploadArtifact(name, files, filesRoot, {
retentionDays: 1,
...options
})
return { id, size }
}
async function deleteArtifactId (id) {
return await artifact.deleteArtifact(id)
}
async function deleteArtifactIdFrom (owner, repo, id) {
return await artifact.deleteArtifact(id, {
token,
repositoryOwner: owner,
repositoryName: repo
})
}
async function downloadArtifactId (id, path) {
return await artifact.downloadArtifact(id, { path })
}
async function downloadArtifactIdFrom (owner, repo, id, path) {
return await artifact.downloadArtifact(id, {
token,
repositoryOwner: owner,
repositoryName: repo,
path
})
}
async function _readTextArtifact (id, owner, repo) {
const tempFolder = __dirname + '/atemp-' + Date.now() // eslint-disable-line
if (owner) {
await downloadArtifactIdFrom(owner, repo, id, tempFolder)
} else {
await downloadArtifactId(id, tempFolder)
}
const files = {}
for (const file of fs.readdirSync(tempFolder)) {
files[file] = fs.readFileSync(tempFolder + '/' + file, 'utf8')
}
fs.rmSync(tempFolder, { recursive: true })
return files
}
async function readTextArtifact (id) {
return _readTextArtifact(id)
}
async function readTextArtifactFrom (owner, repo, id) {
return _readTextArtifact(id, owner, repo)
}
async function createTextArtifact (name, fileContents, options) {
const tempFolder = __dirname + '/atemp-' + Date.now() // eslint-disable-line
fs.mkdirSync(tempFolder, { recursive: true })
const filePaths = []
for (const file in fileContents) {
const path = tempFolder + '/' + file
fs.writeFileSync(path, fileContents[file])
filePaths.push(path)
}
const { id, size } = await uploadArtifact(name, filePaths, tempFolder, options)
fs.rmdirSync(tempFolder, { recursive: true })
return { id, size }
}
async function listArtifacts () {
const ret = await artifact.listArtifacts()
return ret.artifacts
}
async function listArtifactsFrom (owner, repo) {
const ret = await artifact.listArtifacts({
token,
repositoryOwner: owner,
repositoryName: repo
})
return ret.artifacts
}
// End Artifacts
async function findIssues ({ titleIncludes, number, status, author = currentAuthor }) {
if (number) {
return [await getIssue(number)]
}
// https://docs.github.com/en/rest/reference/search#search-issues-and-pull-requests
let q = `is:issue repo:${fullName}`
if (titleIncludes) q += ` in:title ${titleIncludes}`
if (author) q += ` author:${author}`
if (status) q += ` is:${status}`
debug(`Searching issues with query [${q}]`)
const existingIssues = await octokit.rest.search.issuesAndPullRequests({ q })
debug('Existing issues', q, existingIssues)
const results = existingIssues.data.items
return results.map(issue => ({
state: issue.state,
id: issue.number,
number: issue.number,
title: issue.title,
url: issue.html_url,
author: issue.user.login,
body: issue.body,
created: issue.created_at,
isOpen: issue.state === 'open',
isClosed: issue.state === 'closed'
}))
}
async function findIssue (options) {
const existingIssues = await findIssues(options)
return existingIssues[0]
}
async function updateIssue (id, payload) {
const issue = await octokit.rest.issues.update({
...context.repo,
issue_number: id,
body: payload.body
})
debug(`Updated issue ${issue.data.title}#${issue.data.number}: ${issue.data.html_url}`)
}
async function createIssue (payload) {
const issue = await octokit.rest.issues.create({
...context.repo,
...payload
})
debug(`Created issue ${issue.data.title}#${issue.data.number}: ${issue.data.html_url}`)
return {
number: issue.data.number,
url: issue.data.html_url
}
}
async function close (id, reason) {
if (reason) await octokit.rest.issues.createComment({ ...context.repo, issue_number: id, body: reason })
const issue = await octokit.rest.issues.update({ ...context.repo, issue_number: id, state: 'closed' })
debug(`Closed issue ${issue.data.title}#${issue.data.number}: ${issue.data.html_url}`)
}
async function comment (id, body) {
if (typeof id === 'string' && id.length > 16) {
// this is a commit sha hash
const data = await octokit.rest.repos.createCommitComment({ ...context.repo, commit_sha: id, body })
return {
type: 'commit',
id: data.data.id,
url: data.data.html_url
}
} else {
// this is an issue or PR number
const data = await octokit.rest.issues.createComment({ ...context.repo, issue_number: id, body })
return {
type: 'issue',
id: data.data.id,
url: data.data.html_url
}
}
}
async function updateComment (id, body, type = 'issue') {
if (type === 'commit') {
const data = await octokit.rest.repos.updateCommitComment({ ...context.repo, comment_id: id, body })
return {
id: data.data.id,
url: data.data.html_url
}
} else {
const data = await octokit.rest.issues.updateComment({ ...context.repo, comment_id: id, body })
return {
id: data.data.id,
url: data.data.html_url
}
}
}
let repoDetails
async function getRepoDetails () {
if (repoDetails) return repoDetails
const { data } = await octokit.rest.repos.get({ ...context.repo })
repoDetails = {
owner: data.owner.login,
repo: data.name,
fullName: data.full_name,
private: data.private,
description: data.description,
defaultBranch: data.default_branch,
url: data.html_url
}
return repoDetails
}
async function getDefaultBranch () {
const branchFromContext = context.payload?.repository?.default_branch
if (branchFromContext) {
return branchFromContext
}
const details = await getRepoDetails()
return details.defaultBranch
}
if (context.payload) {
// This was triggered by Github Actions
getDefaultBranch().then(branch => debug('Default branch is', branch, 'current author is', currentAuthor))
}
async function findPullRequests ({
titleIncludes,
number,
author = currentAuthor,
status = 'open'
}) {
if (number) {
return [await getPullRequest(number)]
}
// https://docs.github.com/en/rest/reference/search#search-issues-and-pull-requests
let q = `is:pr repo:${fullName}`
if (titleIncludes) q += ` in:title ${titleIncludes}`
if (author) q += ` author:${author}`
if (status) q += ` is:${status}`
debug(`Searching issues with query [${q}]`)
const existingPulls = await octokit.rest.search.issuesAndPullRequests({ q })
debug('Existing issue for query [', q, '] are', existingPulls.data.items)
const results = existingPulls.data.items
return results.map(issue => ({
state: issue.state,
id: issue.number,
number: issue.number,
title: issue.title,
url: issue.html_url,
author: issue.user.login,
body: issue.body,
created: issue.created_at,
isOpen: issue.state === 'open',
isClosed: issue.state === 'closed'
}))
}
async function findPullRequest (options) {
const pulls = await findPullRequests(options)
return pulls[0]
}
async function updatePull (id, { title, body }) {
const pull = await octokit.rest.pulls.update({
...context.repo,
pull_number: id,
title,
body
})
debug(`Updated pull ${pull.data.title}#${pull.data.number}: ${pull.data.html_url}`)
}
async function getComments (id) {
const { data } = await octokit.rest.issues.listComments({
...context.repo,
issue_number: id
})
return data.map(comment => ({
id: comment.id,
author: comment.user.login,
body: comment.body,
created: comment.created_at,
url: comment.html_url,
role: comment.author_association
}))
}
async function getIssue (id, includeComments = false) {
const { data } = await octokit.rest.issues.get({
...context.repo,
issue_number: id
})
if (includeComments) {
data.comments = await getComments(id)
}
return {
comments: data.comments || [],
title: data.title,
body: data.body,
state: data.state,
number: data.number,
author: data.user.login,
created: data.created_at,
url: data.html_url
}
}
async function getPullRequest (id, includeComments = false) {
const { data } = await octokit.rest.pulls.get({
...context.repo,
pull_number: id
})
if (includeComments) {
data.comments = await getComments(id)
}
return {
comments: data.comments || [],
canMaintainerModify: data.maintainer_can_modify || (data.base.repo.full_name === data.head.repo.full_name),
targetBranch: data.base.ref,
targetRepo: data.base.repo.full_name,
headBranch: data.head.ref,
headRepo: data.head.repo.full_name,
headCloneURL: data.head.repo.clone_url,
title: data.title,
body: data.body,
state: data.state,
number: data.number,
author: data.user.login,
created: data.created_at,
url: data.html_url
}
}
async function getPullRequestChecks (number) {
const { data } = await octokit.rest.checks.listForRef({
...context.repo,
ref: `pull/${number}/head`
})
return data.check_runs.map(check => ({
name: check.name,
status: check.status,
conclusion: check.conclusion,
url: check.html_url,
startedAt: check.started_at,
completedAt: check.completed_at,
output: check.output,
id: check.id
}))
}
async function waitForPullRequestChecks (number, maxWait = 60000) {
const start = Date.now()
let checks
do {
checks = await getPullRequestChecks(number)
if (checks.length) {
const pending = checks.filter(check => check.status === 'in_progress')
if (!pending.length) {
return checks
}
}
await new Promise(resolve => setTimeout(resolve, 10000))
} while (Date.now() - start < maxWait)
return checks
}
async function retryPullRequestCheck (id) {
await octokit.rest.checks.rerequestRun({
...context.repo,
check_run_id: id
})
}
async function retryPullRequestChecks (number) {
// Rerun failed checks
const checks = await getPullRequestChecks(number)
const failed = checks.filter(check => check.conclusion === 'failure')
for (const check of failed) {
await retryPullRequestCheck(number, check.id)
}
}
async function createPullRequest (title, body, fromBranch, intoBranch) {
if (!intoBranch) {
intoBranch = await getDefaultBranch()
}
const pr = await octokit.rest.pulls.create({
...context.repo,
title,
body,
head: fromBranch,
base: intoBranch
})
return {
number: pr.data.number,
url: pr.data.html_url
}
}
function _createPullRequestCURL (title, body, fromBranch, intoBranch) {
const result = _sendRequestWithCURL(`https://api.github.com/repos/${context.repo.owner}/${context.repo.repo}/pulls`, JSON.stringify({
title,
body,
head: fromBranch,
base: intoBranch
}))
return {
number: result.number,
url: result.html_url
}
}
async function createPullRequestReview (id, payload) {
debug('createPullRequestReview', id, payload)
await octokit.rest.pulls.createReview({
...context.repo,
pull_number: id,
...payload
})
}
async function mergePullRequest (id, { method, title, message }) {
const pr = await octokit.rest.pulls.merge({
...context.repo,
pull_number: id,
merge_method: method,
commit_title: title,
commit_message: message
})
return pr.data
}
async function addCommentReaction (commentId, reaction) {
await octokit.rest.reactions.createForIssueComment({
...context.repo,
comment_id: commentId,
content: reaction
})
}
async function getDiffForPR (id) {
const diff = await octokit.rest.pulls.get({
...context.repo,
pull_number: id,
mediaType: {
format: 'diff'
}
})
return {
diff: diff.data
}
}
async function getDiffForCommit (sha) {
const diff = await octokit.rest.repos.getCommit({
...context.repo,
ref: sha,
mediaType: {
format: 'diff'
}
})
return {
diff: diff.data
}
}
async function getRecentCommitsInRepo (max = 100) {
const { data } = await octokit.rest.repos.listCommits({
...context.repo,
per_page: max
})
return data.map(commit => ({
sha: commit.sha,
login: commit.author?.login,
name: commit.commit.author.name,
email: commit.commit.author.email,
message: commit.commit.message,
url: commit.html_url
}))
}
// Send a workflow dispatch event to a repository in the specified owner
function sendWorkflowDispatch ({ owner, repo, branch, workflow, inputs }) {
return octokit.rest.actions.createWorkflowDispatch({
owner: owner || context.repo.owner,
repo: repo || context.repo.repo,
workflow_id: workflow,
ref: branch || 'main',
inputs
})
}
// For debugging purposes, we can also send a workflow dispatch event using CURL
function _sendWorkflowDispatchCURL ({ owner, repo, branch, workflow, inputs }) {
return _sendRequestWithCURL(`https://api.github.com/repos/${owner}/${repo}/actions/workflows/${workflow}/dispatches`, JSON.stringify({
ref: branch || 'main',
inputs
}))
}
function onRepoComment (fn) {
const payload = context.payload
if (payload.comment && payload.issue) {
fn({
repository: payload.repository,
repoId: payload.repository.full_name,
type: payload.issue.pull_request ? 'pull' : 'issue',
// Comment data
username: payload.comment.user.login,
role: payload.comment.author_association,
body: payload.comment.body,
id: payload.comment.id,
url: payload.comment.html_url,
// Helpful checks
isAuthor: payload.issue.user.login === payload.comment.user.login,
issue: {
author: payload.issue.user.login,
number: payload.issue.number,
title: payload.issue.title,
url: payload.issue.html_url,
state: payload.issue.state,
// Helpful checks
isClosed: payload.issue.state === 'closed',
isOpen: payload.issue.state === 'open',
isMerged: payload.issue.pull_request?.merged,
isMergeable: payload.issue.pull_request?.mergeable
}
}, payload)
}
}
function onUpdatedPR (fn) {
const payload = context.payload
if (payload.action === 'edited' && payload.pull_request && payload.changes) {
const author = payload.pull_request.user.login
fn({
repository: payload.repository,
repoId: payload.repository.full_name,
changeType: payload.changes.title ? 'title' : payload.changes.body ? 'body' : 'unknown',
// username is who triggered the event, pr.author is the PR creator
username: payload.sender.login,
title: {
old: payload.changes.title ? payload.changes.title.from : undefined,
now: payload.pull_request.title
},
// check if change was triggered by our current PAT
isTriggeredByUs: (context.actor === payload.sender.login) || (payload.sender.login.includes('github-actions')),
pr: {
number: payload.pull_request.number,
title: payload.pull_request.title,
body: payload.pull_request.body,
url: payload.pull_request.html_url,
author,
// Helpful checks
isAuthor: author === payload.sender.login,
isOpen: payload.pull_request.state === 'open',
isClosed: payload.pull_request.state === 'closed',
isMerged: payload.pull_request.merged,
isMergeable: payload.pull_request.mergeable,
isCreatedByUs: (author === context.actor) || (author.includes('github-actions'))
}
}, payload)
}
}
function onWorkflowDispatch (fn) {
const payload = context.payload
if (context.eventName === 'workflow_dispatch') {
fn({
repository: payload.repository,
repoId: payload.repository.full_name,
inputs: payload.inputs,
ref: payload.ref,
workflowId: payload.workflow,
workflowName: payload.workflow.split('/').pop(),
sender: payload.sender.login
}, payload)
}
}
async function checkRepoExists (id) {
if (Array.isArray(id)) id = id.join('/')
else if (typeof id === 'object') id = id.owner + '/' + id.repo
else if (typeof id === 'string' && !id.includes('/')) id = context.repo.owner + '/' + id
try {
await fetch('https://api.github.com/repos/' + id)
return true
} catch {
return false
}
}
const repoURL = context.payload?.repository.html_url ?? `https://github.com/${context.repo.owner}/${context.repo.repo}`
function using ({ owner = context.repo.owner, repo }) {
return mod({ repo: { owner, repo } }, githubToken)
}
return {
getCurrentUser,
getRepoDetails,
getDefaultBranch,
getInput,
artifacts: {
upload: uploadArtifact,
deleteId: deleteArtifactId,
deleteIdFrom: deleteArtifactIdFrom,
downloadId: downloadArtifactId,
downloadIdFrom: downloadArtifactIdFrom,
list: listArtifacts,
listFrom: listArtifactsFrom,
readTextArtifact,
readTextArtifactFrom,
createTextArtifact
},
findIssues,
findIssue,
getIssue,
getComments,
findPullRequests,
findPullRequest,
getPullRequest,
getPullRequestChecks,
waitForPullRequestChecks,
retryPullRequestCheck,
retryPullRequestChecks,
getDiffForPR,
getDiffForCommit,
updateIssue,
createIssue,
updatePull,
createPullRequest,
createPullRequestReview,
mergePullRequest,
close,
comment,
updateComment,
addCommentReaction,
getRecentCommitsInRepo,
sendWorkflowDispatch,
onRepoComment,
onUpdatedPR,
onWorkflowDispatch,
repoURL,
checkRepoExists,
using,
_createPullRequestCURL,
_sendWorkflowDispatchCURL
}
}
module.exports = mod