-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathmain.ts
More file actions
167 lines (146 loc) · 5.36 KB
/
main.ts
File metadata and controls
167 lines (146 loc) · 5.36 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
import * as core from '@actions/core'
import * as github from '@actions/github'
import {features, Octokit, optional, required} from '../lib'
import {ForbiddenError} from '../lib/api'
import {approve as approveFromServer} from '../lib/github'
import {track} from '../lib/track'
import {list as listMessages} from '../lib/jobs/messages'
const jobID = optional('codeball-job-id')
const shouldApprove = required('approve') === 'true'
const githubToken = required('GITHUB_TOKEN')
const octokit = new Octokit({auth: githubToken})
const approvalMessage = required('message')
const defaultMessages = [
`> [[dashboard](https://codeball.ai/${process.env.GITHUB_REPOSITORY})]`
]
const getServerSideMessages = (jobId: string) =>
listMessages(jobId).then(messages => [
...messages.map(message => message.text)
])
const getMessages = async (jobId: string | undefined): Promise<string[]> => {
const messages = jobId
? await getServerSideMessages(jobId).catch(() => defaultMessages)
: defaultMessages
return shouldApprove ? [approvalMessage, ...messages] : messages
}
const approveFromActions = async (params: {
owner: string
repo: string
pull_number: number
commit_id: string
body: string
event: 'APPROVE' | 'COMMENT'
}) => {
const existingReviews = await octokit.pulls
.listReviews({
owner: params.owner,
repo: params.repo,
pull_number: params.pull_number
})
.catch(e => {
throw new Error(`failed to current existing reviews ${e}`)
})
.then(r => r.data)
const previousReviews = existingReviews
.filter(r => r.user?.type === 'Bot')
.sort(
(a, b) =>
new Date(a.submitted_at ?? 0).getTime() -
new Date(b.submitted_at ?? 0).getTime()
)
const latestReview = previousReviews.slice(-1).at(0)
const latestReviewExists = latestReview !== undefined
const latestReviewIsApproval = latestReview?.state === 'APPROVED'
if (latestReviewExists && shouldApprove) {
await octokit.pulls.createReview(params).catch(e => {
throw new Error(`failed to create review ${e}`)
})
} else if (latestReviewExists && !shouldApprove && latestReviewIsApproval) {
await octokit.pulls
.dismissReview({
review_id: latestReview.id,
owner: params.owner,
repo: params.repo,
pull_number: params.pull_number,
message: params.body
})
.catch(e => {
throw new Error(`failed to dismiss review ${e}`)
})
} else if (!latestReviewExists && shouldApprove) {
await octokit.pulls.createReview(params).catch(e => {
throw new Error(`failed to create review ${e}`)
})
}
}
async function run(): Promise<void> {
const pullRequestURL = github.context.payload?.pull_request?.html_url
if (!pullRequestURL) throw new Error('No pull request URL found')
const pullRequestNumber = github.context.payload?.pull_request?.number
if (!pullRequestNumber) throw new Error('No pull request number found')
const commitId = github.context.payload.pull_request?.head.sha
if (!commitId) throw new Error('No commit ID found')
const repoOwner = github.context.payload.repository?.owner.login
if (!repoOwner) throw new Error('No repo owner found')
const repoName = github.context.payload.repository?.name
if (!repoName) throw new Error('No repo name found')
const reviewMessage = (await getMessages(jobID)).join('\n\n')
const pr = await octokit.pulls
.get({
owner: repoOwner,
repo: repoName,
pull_number: pullRequestNumber
})
.then(r => r.data)
const isPrivate = pr.base.repo.private
const isFromFork = pr.head.repo?.fork
const isToFork = pr.base.repo.fork
const feats = await features({jobID})
if (!feats.approve) {
core.error(
'Unable to run this action as the feature is not available for your organization. Please upgrade your Codeball plan, or contact support@codeball.ai'
)
return
}
await approveFromActions({
owner: repoOwner,
repo: repoName,
pull_number: pullRequestNumber,
commit_id: commitId,
body: reviewMessage,
event: feats.approve ? 'APPROVE' : 'COMMENT'
}).catch(async error => {
core.error(error)
if (
error instanceof Error &&
error.message === 'Resource not accessible by integration'
) {
// If the token is not allowed to create reviews (for example it's a pull request from a public fork),
// we can try to approve the pull request from the backend with the app token.
return approveFromServer({
link: pullRequestURL,
message: reviewMessage,
approve: shouldApprove
}).catch(error => {
if (error.name === ForbiddenError.name) {
throw new Error(
!isPrivate && isFromFork && !isToFork
? 'Codeball Approver failed to access GitHub. Install https://github.com/apps/codeball-ai-writer to the base repository to give Codeball permission to approve Pull Requests.'
: 'Codeball Approver failed to access GitHub. Check the "GITHUB_TOKEN Permissions" of this job and make sure that the job has WRITE permissions to Pull Requests.'
)
}
throw error
})
} else {
throw error
}
})
}
run()
.then(async () => await track({jobID, actionName: 'approver'}))
.catch(async error => {
if (error instanceof Error) {
await track({jobID, actionName: 'approver', error: error.message})
core.setFailed(error.message)
}
})