/
GitLabAPI.ts
282 lines (241 loc) · 9.39 KB
/
GitLabAPI.ts
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
import { RepoMetaData } from "../../dsl/BitBucketServerDSL"
import { api as fetch } from "../../api/fetch"
import {
GitLabDiscussionTextPosition,
GitLabInlineNote,
GitLabMR,
GitLabMRChange,
GitLabMRChanges,
GitLabMRCommit,
GitLabNote,
GitLabUserProfile,
GitLabRepositoryFile,
GitLabRepositoryCompare,
GitLabApproval,
} from "../../dsl/GitLabDSL"
import { Gitlab } from "gitlab"
import { Env } from "../../ci_source/ci_source"
import { debug } from "../../debug"
export type GitLabAPIToken = string
export type GitLabOAuthToken = string
export interface GitLabAPICredentials {
host: string
token?: GitLabAPIToken
oauthToken?: GitLabOAuthToken
}
export function getGitLabAPICredentialsFromEnv(env: Env): GitLabAPICredentials {
let host = "https://gitlab.com"
const envHost = env["DANGER_GITLAB_HOST"]
const envCIAPI = env["CI_API_V4_URL"]
if (envHost) {
// We used to support DANGER_GITLAB_HOST being just the host e.g. "gitlab.com"
// however it is possible to have a custom host without SSL, ensure we only add the protocol if one is not provided
const protocolRegex = /^https?:\/\//i
host = protocolRegex.test(envHost) ? envHost : `https://${envHost}`
} else if (envCIAPI) {
// GitLab >= v11.7 supplies the API Endpoint in an environment variable and we can work out our host value from that.
// See https://docs.gitlab.com/ce/ci/variables/predefined_variables.html
const hostRegex = /^(https?):\/\/([^\/]+)\//i
if (hostRegex.test(envCIAPI)) {
const matches = hostRegex.exec(envCIAPI)!
const matchProto = matches[1]
const matchHost = matches[2]
host = `${matchProto}://${matchHost}`
}
}
return {
host,
token: env["DANGER_GITLAB_API_TOKEN"],
oauthToken: env["DANGER_GITLAB_API_OAUTH_TOKEN"],
}
}
class GitLabAPI {
fetch: typeof fetch
private api: InstanceType<typeof Gitlab>
private readonly hostURL: string
private readonly d = debug("GitLabAPI")
constructor(public readonly repoMetadata: RepoMetaData, public readonly repoCredentials: GitLabAPICredentials) {
this.fetch = fetch
this.api = new Gitlab(repoCredentials)
this.hostURL = repoCredentials.host
}
get projectURL(): string {
return `${this.hostURL}/${this.repoMetadata.repoSlug}`
}
get mergeRequestURL(): string {
return `${this.projectURL}/merge_requests/${this.repoMetadata.pullRequestID}`
}
get apiInstance() {
return this.api
}
getUser = async (): Promise<GitLabUserProfile> => {
this.d("getUser")
const user = (await this.api.Users.current()) as GitLabUserProfile
this.d("getUser", user)
return user
}
getMergeRequestInfo = async (): Promise<GitLabMR> => {
this.d(`getMergeRequestInfo for repo: ${this.repoMetadata.repoSlug} pr: ${this.repoMetadata.pullRequestID}`)
const mr = (await this.api.MergeRequests.show(
this.repoMetadata.repoSlug,
Number(this.repoMetadata.pullRequestID)
)) as GitLabMR
this.d("getMergeRequestInfo", mr)
return mr
}
updateMergeRequestInfo = async (changes: object): Promise<object> => {
const mr = this.api.MergeRequests.edit(this.repoMetadata.repoSlug, Number(this.repoMetadata.pullRequestID), changes)
this.d("updateMergeRequestInfo", mr)
return mr
}
getMergeRequestApprovals = async (): Promise<GitLabApproval> => {
this.d(`getMergeRequestApprovals for repo: ${this.repoMetadata.repoSlug} pr: ${this.repoMetadata.pullRequestID}`)
const approvals = (await this.api.MergeRequests.approvals(this.repoMetadata.repoSlug, {
mergerequestIId: Number(this.repoMetadata.pullRequestID),
})) as GitLabApproval
this.d("getMergeRequestApprovals", approvals)
return approvals
}
getMergeRequestChanges = async (): Promise<GitLabMRChange[]> => {
this.d(`getMergeRequestChanges for repo: ${this.repoMetadata.repoSlug} pr: ${this.repoMetadata.pullRequestID}`)
const mr = (await this.api.MergeRequests.changes(
this.repoMetadata.repoSlug,
Number(this.repoMetadata.pullRequestID)
)) as GitLabMRChanges
this.d("getMergeRequestChanges", mr.changes)
return mr.changes
}
getMergeRequestCommits = async (): Promise<GitLabMRCommit[]> => {
this.d("getMergeRequestCommits", this.repoMetadata.repoSlug, this.repoMetadata.pullRequestID)
const commits = (await this.api.MergeRequests.commits(
this.repoMetadata.repoSlug,
Number(this.repoMetadata.pullRequestID)
)) as GitLabMRCommit[]
this.d("getMergeRequestCommits", commits)
return commits
}
getMergeRequestNotes = async (): Promise<GitLabNote[]> => {
this.d("getMergeRequestNotes", this.repoMetadata.repoSlug, this.repoMetadata.pullRequestID)
const api = this.api.MergeRequestNotes
const notes = (await api.all(this.repoMetadata.repoSlug, this.repoMetadata.pullRequestID)) as GitLabNote[]
this.d("getMergeRequestNotes", notes)
return notes
}
getMergeRequestInlineNotes = async (): Promise<GitLabInlineNote[]> => {
this.d("getMergeRequestInlineNotes")
const notes: GitLabNote[] = await this.getMergeRequestNotes()
const inlineNotes = notes.filter((note: GitLabNote) => note.type == "DiffNote") as GitLabInlineNote[]
this.d("getMergeRequestInlineNotes", inlineNotes)
return inlineNotes
}
createMergeRequestDiscussion = async (content: string, position: GitLabDiscussionTextPosition): Promise<string> => {
this.d(
"createMergeRequestDiscussion",
this.repoMetadata.repoSlug,
this.repoMetadata.pullRequestID,
content,
position
)
const api = this.api.MergeRequestDiscussions
try {
// @ts-ignore
const result: string = await api.create(this.repoMetadata.repoSlug, this.repoMetadata.pullRequestID, content, {
position: position,
})
this.d("createMergeRequestDiscussion", result)
return result
} catch (e) {
this.d("createMergeRequestDiscussion", e)
throw e
}
}
createMergeRequestNote = async (body: string): Promise<GitLabNote> => {
this.d("createMergeRequestNote", this.repoMetadata.repoSlug, this.repoMetadata.pullRequestID, body)
const api = this.api.MergeRequestNotes
try {
this.d("createMergeRequestNote")
const note = (await api.create(this.repoMetadata.repoSlug, this.repoMetadata.pullRequestID, body)) as GitLabNote
this.d("createMergeRequestNote", note)
return note
} catch (e) {
this.d("createMergeRequestNote", e)
}
return Promise.reject()
}
updateMergeRequestNote = async (id: number, body: string): Promise<GitLabNote> => {
this.d("updateMergeRequestNote", this.repoMetadata.repoSlug, this.repoMetadata.pullRequestID, id, body)
const api = this.api.MergeRequestNotes
try {
const note = (await api.edit(this.repoMetadata.repoSlug, this.repoMetadata.pullRequestID, id, body)) as GitLabNote
this.d("updateMergeRequestNote", note)
return note
} catch (e) {
this.d("updateMergeRequestNote", e)
}
return Promise.reject()
}
// note: deleting the _only_ note in a discussion also deletes the discussion \o/
deleteMergeRequestNote = async (id: number): Promise<boolean> => {
this.d("deleteMergeRequestNote", this.repoMetadata.repoSlug, this.repoMetadata.pullRequestID, id)
const api = this.api.MergeRequestNotes
try {
await api.remove(this.repoMetadata.repoSlug, this.repoMetadata.pullRequestID, id)
this.d("deleteMergeRequestNote", true)
return true
} catch (e) {
this.d("deleteMergeRequestNote", e)
return false
}
}
getFileContents = async (path: string, slug?: string, ref?: string): Promise<string> => {
this.d(`getFileContents requested for path:${path}, slug:${slug}, ref:${ref}`)
const api = this.api.RepositoryFiles
const projectId = slug || this.repoMetadata.repoSlug
// Use the current state of PR if no ref is passed
if (!ref) {
const mr: GitLabMR = await this.getMergeRequestInfo()
ref = mr.diff_refs.head_sha
}
try {
this.d("getFileContents", projectId, path, ref)
const response = (await api.show(projectId, path, ref)) as GitLabRepositoryFile
const result: string = Buffer.from(response.content, "base64").toString()
this.d("getFileContents", result)
return result
} catch (e) {
this.d("getFileContents", e)
// GitHubAPI.fileContents returns "" when the file does not exist, keep it consistent across providers
if ((e as any).response.status === 404) {
return ""
}
throw e
}
}
getCompareChanges = async (base?: string, head?: string): Promise<GitLabMRChange[]> => {
if (!base || !head) {
return this.getMergeRequestChanges()
}
const api = this.api.Repositories
const projectId = this.repoMetadata.repoSlug
const compare = (await api.compare(projectId, base, head)) as GitLabRepositoryCompare
return compare.diffs
}
addLabels = async (...labels: string[]): Promise<boolean> => {
const mr = await this.getMergeRequestInfo()
mr.labels.push(...labels)
await this.updateMergeRequestInfo({ labels: mr.labels.join(",") })
return true
}
removeLabels = async (...labels: string[]): Promise<boolean> => {
const mr = await this.getMergeRequestInfo()
for (const label of labels) {
const index = mr.labels.indexOf(label)
if (index > -1) {
mr.labels.splice(index, 1)
}
}
await this.updateMergeRequestInfo({ labels: mr.labels.join(",") })
return true
}
}
export default GitLabAPI