-
-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathgithub-helper.ts
More file actions
218 lines (199 loc) · 6.18 KB
/
github-helper.ts
File metadata and controls
218 lines (199 loc) · 6.18 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
import * as core from '@actions/core'
import {Octokit, PullsGetResponseData} from './octokit-client'
import {Command, SlashCommandPayload} from './command-helper'
import {inspect} from 'util'
import * as utils from './utils'
type ReposCreateDispatchEventParamsClientPayload = {
[key: string]: ReposCreateDispatchEventParamsClientPayloadKeyString
}
// eslint-disable-next-line
type ReposCreateDispatchEventParamsClientPayloadKeyString = {}
export interface ClientPayload extends ReposCreateDispatchEventParamsClientPayload {
// eslint-disable-next-line
github: any
// eslint-disable-next-line
pull_request?: any
// eslint-disable-next-line
slash_command?: SlashCommandPayload | any
}
interface Repository {
owner: string
repo: string
}
export class GitHubHelper {
private octokit: InstanceType<typeof Octokit>
constructor(token: string) {
this.octokit = new Octokit({
auth: token,
baseUrl: process.env['GITHUB_API_URL'] || 'https://api.github.com'
})
}
private parseRepository(repository: string): Repository {
const [owner, repo] = repository.split('/')
return {
owner: owner,
repo: repo
}
}
async getActorPermission(
repo: Repository,
actor: string
): Promise<utils.RepoPermission> {
// Use the REST API approach which can detect both direct and team-based permissions
// This is more reliable than the GraphQL approach for team permissions and works better with default GITHUB_TOKEN
try {
const {data: collaboratorPermission} =
await this.octokit.rest.repos.getCollaboratorPermissionLevel({
...repo,
username: actor
})
const permissions = collaboratorPermission.user?.permissions
core.debug(`REST API collaborator permission: ${inspect(permissions)}`)
// Use the detailed permissions object to get the highest permission level
if (permissions) {
// Check permissions in order of highest to lowest
if (permissions.admin) {
return 'admin'
} else if (permissions.maintain) {
return 'maintain'
} else if (permissions.push) {
return 'write'
} else if (permissions.triage) {
core.debug(`User ${actor} has triage permission via REST API`)
return 'triage'
} else if (permissions.pull) {
core.debug(`User ${actor} has read permission via REST API`)
return 'read'
}
}
return 'none'
} catch (error) {
core.debug(
`REST API permission check failed: ${utils.getErrorMessage(error)}`
)
return 'none'
}
}
async tryAddReaction(
repo: Repository,
commentId: number,
reaction:
| '+1'
| '-1'
| 'laugh'
| 'confused'
| 'heart'
| 'hooray'
| 'rocket'
| 'eyes'
): Promise<void> {
try {
await this.octokit.rest.reactions.createForIssueComment({
...repo,
comment_id: commentId,
content: reaction
})
} catch (error) {
core.debug(utils.getErrorMessage(error))
core.warning(`Failed to set reaction on comment ID ${commentId}.`)
}
}
async getPull(
repo: Repository,
pullNumber: number
): Promise<PullsGetResponseData> {
const {data: pullRequest} = await this.octokit.rest.pulls.get({
...repo,
pull_number: pullNumber
})
return pullRequest
}
async createDispatch(
cmd: Command,
clientPayload: ClientPayload
): Promise<void> {
if (cmd.dispatch_type == 'repository') {
await this.createRepositoryDispatch(cmd, clientPayload)
} else {
await this.createWorkflowDispatch(cmd, clientPayload)
}
}
private async createRepositoryDispatch(
cmd: Command,
clientPayload: ClientPayload
): Promise<void> {
const eventType = `${cmd.command}${cmd.event_type_suffix}`
await this.octokit.rest.repos.createDispatchEvent({
...this.parseRepository(cmd.repository),
event_type: `${cmd.command}${cmd.event_type_suffix}`,
client_payload: clientPayload
})
core.info(
`Command '${cmd.command}' dispatched to '${cmd.repository}' ` +
`with event type '${eventType}'.`
)
}
async createWorkflowDispatch(
cmd: Command,
clientPayload: ClientPayload
): Promise<void> {
const workflowName = `${cmd.command}${cmd.event_type_suffix}`
const workflow = await this.getWorkflow(cmd.repository, workflowName)
const slashCommand: SlashCommandPayload = clientPayload.slash_command
const ref = slashCommand.args.named.ref
? slashCommand.args.named.ref
: await this.getDefaultBranch(cmd.repository)
// Take max 10 named arguments, excluding 'ref'.
const inputs = {}
let count = 0
for (const key in slashCommand.args.named) {
if (key != 'ref') {
inputs[key] = slashCommand.args.named[key]
count++
}
if (count == 10) break
}
await this.octokit.request(
'POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches',
{
...this.parseRepository(cmd.repository),
workflow_id: workflow,
ref: ref,
inputs: inputs
}
)
core.info(
`Command '${cmd.command}' dispatched to workflow '${workflow}' in '${cmd.repository}'`
)
}
private async getWorkflow(
repository: string,
workflowName: string
): Promise<string> {
core.debug(`Getting workflow ${workflowName} for repository ${repository}`)
const workflows = await this.octokit.paginate(
'GET /repos/{owner}/{repo}/actions/workflows',
{
...this.parseRepository(repository),
per_page: 100
}
)
for (const workflow of workflows) {
core.debug(`Found workflow: ${workflow.path}`)
if (
workflow.path.endsWith(`${workflowName}.yml`) ||
workflow.path.endsWith(`${workflowName}.yaml`)
) {
core.debug(`Selecting workflow file ${workflow.path}`)
return workflow.path
}
}
throw new Error(`Workflow ${workflowName} not found`)
}
private async getDefaultBranch(repository: string): Promise<string> {
const {data: repo} = await this.octokit.rest.repos.get({
...this.parseRepository(repository)
})
return repo.default_branch
}
}