/
BitBucketServerAPI.ts
395 lines (330 loc) · 12.2 KB
/
BitBucketServerAPI.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
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
import { debug } from "../../debug"
import * as node_fetch from "node-fetch"
import { Agent } from "http"
import HttpsProxyAgent from "https-proxy-agent"
import {
BitBucketServerPRDSL,
BitBucketServerCommit,
BitBucketServerPRComment,
JIRAIssue,
BitBucketServerPRActivity,
BitBucketServerDiff,
RepoMetaData,
BitBucketServerChangesValue,
BitBucketServerPagedResponse,
BitBucketServerAPIDSL,
} from "../../dsl/BitBucketServerDSL"
import { Comment } from "../platform"
import { Env } from "../../ci_source/ci_source"
import { dangerIDToString } from "../../runner/templates/bitbucketServerTemplate"
import { api as fetch } from "../../api/fetch"
// Note that there are parts of this class which don't seem to be
// used by Danger, they are exposed for Peril support.
export interface BitBucketRepoCredentials {
host: string
username?: string
password?: string
token?: string
}
interface CommentDeletionException {
errors: {
content: null
message: string
exceptionName: "com.atlassian.bitbucket.comment.CommentDeletionException"
}
}
type DeleteCommentResponse = CommentDeletionException
export function bitbucketServerRepoCredentialsFromEnv(env: Env): BitBucketRepoCredentials {
if (!env["DANGER_BITBUCKETSERVER_HOST"]) {
throw new Error(`DANGER_BITBUCKETSERVER_HOST is not set`)
}
return {
host: env["DANGER_BITBUCKETSERVER_HOST"],
username: env["DANGER_BITBUCKETSERVER_USERNAME"],
password: env["DANGER_BITBUCKETSERVER_PASSWORD"],
token: env["DANGER_BITBUCKETSERVER_TOKEN"],
}
}
/** This represent the BitBucketServer API */
export class BitBucketServerAPI implements BitBucketServerAPIDSL {
fetch: typeof fetch
private readonly d = debug("BitBucketServerAPI")
private pr: BitBucketServerPRDSL | undefined
constructor(public readonly repoMetadata: RepoMetaData, public readonly repoCredentials: BitBucketRepoCredentials) {
// This allows Peril to DI in a new Fetch function
// which can handle unique API edge-cases around integrations
this.fetch = fetch
}
getPRBasePath(service = "api") {
const { repoSlug, pullRequestID } = this.repoMetadata
return `rest/${service}/1.0/${repoSlug}/pull-requests/${pullRequestID}`
}
getPullRequestsFromBranch = async (branch: string): Promise<BitBucketServerPRDSL[]> => {
let nextPageStart: null | number = 0
let values: BitBucketServerPRDSL[] = []
const { repoSlug } = this.repoMetadata
do {
const path = `rest/api/1.0/${repoSlug}/pull-requests?at=refs/heads/${branch}&withProperties=false&withAttributes=false&start=${nextPageStart}`
const res = await this.get(path)
throwIfNotOk(res)
const data = (await res.json()) as BitBucketServerPagedResponse<BitBucketServerPRDSL>
values = values.concat(data.values)
if (data.isLastPage) {
nextPageStart = null
} else {
nextPageStart = data.nextPageStart
}
} while (nextPageStart !== null)
return values
}
getPullRequestInfo = async (): Promise<BitBucketServerPRDSL> => {
if (this.pr) {
return this.pr
}
const path = this.getPRBasePath()
const res = await this.get(path)
throwIfNotOk(res)
const prDSL = (await res.json()) as BitBucketServerPRDSL
this.pr = prDSL
return prDSL
}
getPullRequestCommits = async (): Promise<BitBucketServerCommit[]> => {
let nextPageStart: null | number = 0
let values: BitBucketServerCommit[] = []
do {
const path = `${this.getPRBasePath()}/commits?start=${nextPageStart}`
const res = await this.get(path)
throwIfNotOk(res)
const data = (await res.json()) as BitBucketServerPagedResponse<BitBucketServerCommit>
values = values.concat(data.values)
if (data.isLastPage) {
nextPageStart = null
} else {
nextPageStart = data.nextPageStart
}
} while (nextPageStart !== null)
return values
}
getStructuredDiffForFile = async (base: string, head: string, filename: string): Promise<BitBucketServerDiff[]> => {
const { repoSlug } = this.repoMetadata
const path = `rest/api/1.0/${repoSlug}/compare/diff/${encodeURI(
filename
)}?withComments=false&from=${head}&to=${base}`
const res = await this.get(path)
throwIfNotOk(res)
return (await res.json()).diffs
}
getPullRequestChanges = async (): Promise<BitBucketServerChangesValue[]> => {
let nextPageStart: null | number = 0
let values: BitBucketServerChangesValue[] = []
do {
const path = `${this.getPRBasePath()}/changes?start=${nextPageStart}`
const res = await this.get(path)
throwIfNotOk(res)
const data = (await res.json()) as BitBucketServerPagedResponse<BitBucketServerChangesValue>
values = values.concat(data.values)
if (data.isLastPage) {
nextPageStart = null
} else {
nextPageStart = data.nextPageStart
}
} while (nextPageStart !== null)
return values
}
getPullRequestComments = async (): Promise<BitBucketServerPRActivity[]> => {
return this.getPullRequestActivities("COMMENT")
}
getPullRequestActivities = async (
type: "COMMENT" | "ACTIVITY" = "ACTIVITY"
): Promise<BitBucketServerPRActivity[]> => {
let nextPageStart: null | number = 0
let values: BitBucketServerPRActivity[] = []
do {
const path = `${this.getPRBasePath()}/activities?fromType=${type}&start=${nextPageStart}`
const res = await this.get(path)
throwIfNotOk(res)
const data = (await res.json()) as BitBucketServerPagedResponse<BitBucketServerPRActivity>
values = values.concat(data.values)
if (data.isLastPage) {
nextPageStart = null
} else {
nextPageStart = data.nextPageStart
}
} while (nextPageStart !== null)
return values
}
getIssues = async (): Promise<JIRAIssue[]> => {
if (process.env.DANGER_NO_BITBUCKET_JIRA_INTEGRATION) {
return [] as JIRAIssue[]
}
const path = `${this.getPRBasePath("jira")}/issues`
const res = await this.get(path)
throwIfNotOk(res)
return await res.json()
}
getDangerComments = async (dangerID: string): Promise<BitBucketServerPRComment[]> => {
const username = this.repoCredentials.username
const activities = await this.getPullRequestComments()
const dangerIDMessage = dangerIDToString(dangerID)
const comments = activities.map(activity => activity.comment).filter(Boolean) as BitBucketServerPRComment[]
return comments
.filter(comment => comment!.text.includes(dangerIDMessage))
.filter(comment => username || comment!.author.name === username)
.filter(comment => comment!.text.includes("Generated by"))
}
getDangerInlineComments = async (dangerID: string): Promise<Comment[]> => {
const username = this.repoCredentials.username
const activities = await this.getPullRequestComments()
const dangerIDMessage = dangerIDToString(dangerID)
const comments = activities
.filter(activity => activity.commentAnchor)
.map(activity => activity.comment)
.filter(Boolean) as BitBucketServerPRComment[]
return new Promise<Comment[]>(resolve => {
resolve(
comments
.map((i: any) => {
return {
id: i.id,
ownedByDanger: i.author.name === username && i.text.includes(dangerIDMessage),
body: i.text,
}
})
.filter((i: any) => i.ownedByDanger)
)
})
}
// The last two are "optional" in the protocol, but not really optional WRT the BBSAPI
getFileContents = async (filePath: string, repoSlug?: string, refspec?: string) => {
const path = `rest/api/1.0/${repoSlug}/` + `raw/${encodeURI(filePath)}` + `?at=${refspec}`
const res = await this.get(path, undefined, true)
if (res.status === 404) {
return ""
}
throwIfNotOk(res)
return await res.text()
}
postBuildStatus = async (
commitId: string,
payload: {
state: string
key: string
name: string
url: string
description: string
}
) => {
const res = await this.post(`rest/build-status/1.0/commits/${commitId}`, {}, payload)
throwIfNotOk(res)
// If the response status does not contain anything (error code === 204), do not return anything. Otherwise return the json response (seems like bitbucket server v4.10.1 returns 204 with empty response after setting the status)
if (res.status !== 204) {
return await res.json()
}
}
postPRComment = async (comment: string) => {
const path = `${this.getPRBasePath()}/comments`
const res = await this.post(path, {}, { text: comment })
return await res.json()
}
postInlinePRComment = async (comment: string, line: number, type: string, filePath: string) => {
const path = `${this.getPRBasePath()}/comments`
const t = { add: "ADDED", normal: "CONTEXT", del: "REMOVED" }[type]
const res = await this.post(
path,
{},
{
text: comment,
anchor: {
line: line,
lineType: t,
fileType: "TO",
path: filePath,
},
}
)
if (res.ok) {
return res.json()
} else {
throw await res.json()
}
}
deleteComment = async ({ id, version }: { id: number; version: number }) => {
const path = `${this.getPRBasePath()}/comments/${id}?version=${version}`
const res = await this.delete(path)
if (res.status === 409) {
const errors = ((await res.json()) as DeleteCommentResponse).errors
if (errors.exceptionName === "com.atlassian.bitbucket.comment.CommentDeletionException") {
return this.updateComment({ id, version }, "(Review Retracted)")
}
}
if (!res.ok) {
throw new Error(`Failed to delete comment "${id}`)
}
}
updateComment = async ({ id, version }: { id: number; version: number }, comment: string) => {
const path = `${this.getPRBasePath()}/comments/${id}`
const res = await this.put(
path,
{},
{
text: comment,
version,
}
)
if (res.ok) {
return res.json()
} else {
throw await res.json()
}
}
// API implementation
private api = (path: string, headers: any = {}, body: any = {}, method: string, suppressErrors?: boolean) => {
if (this.repoCredentials.token) {
headers["Authorization"] = `Bearer ${this.repoCredentials.token}`
} else if (this.repoCredentials.password) {
headers["Authorization"] = `Basic ${Buffer.from(
this.repoCredentials.username + ":" + this.repoCredentials.password
).toString("base64")}`
}
const url = `${this.repoCredentials.host}/${path}`
this.d(`${method} ${url}`)
// Allow using a proxy configured through environmental variables
// Remember that to avoid the error "Error: self signed certificate in certificate chain"
// you should also do: "export NODE_TLS_REJECT_UNAUTHORIZED=0". See: https://github.com/request/request/issues/2061
let agent: Agent | undefined = undefined
let proxy = process.env.http_proxy || process.env.https_proxy
if (proxy) {
agent = new HttpsProxyAgent(proxy)
}
return this.fetch(
url,
{
method,
body,
headers: {
"Content-Type": "application/json",
...headers,
},
agent,
},
suppressErrors
)
}
get = (path: string, headers: any = {}, suppressErrors?: boolean): Promise<node_fetch.Response> =>
this.api(path, headers, null, "GET", suppressErrors)
post = (path: string, headers: any = {}, body: any = {}, suppressErrors?: boolean): Promise<node_fetch.Response> =>
this.api(path, headers, JSON.stringify(body), "POST", suppressErrors)
put = (path: string, headers: any = {}, body: any = {}): Promise<node_fetch.Response> =>
this.api(path, headers, JSON.stringify(body), "PUT")
delete = (path: string, headers: any = {}, body: any = {}): Promise<node_fetch.Response> =>
this.api(path, headers, JSON.stringify(body), "DELETE")
}
function throwIfNotOk(res: node_fetch.Response) {
if (!res.ok) {
let message = `${res.status} - ${res.statusText}`
if (res.status >= 400 && res.status < 500) {
message += ` (Have you set DANGER_BITBUCKETSERVER_USERNAME and DANGER_BITBUCKETSERVER_PASSWORD or DANGER_BITBUCKETSERVER_TOKEN?)`
}
throw new Error(message)
}
}