-
-
Notifications
You must be signed in to change notification settings - Fork 368
/
GitLab.ts
362 lines (314 loc) · 12.6 KB
/
GitLab.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
import GitLabAPI from "./gitlab/GitLabAPI"
import { inlinePositionParser } from "./gitlab/inlinePositionParser"
import { Comment, Platform } from "./platform"
import { GitDSL, GitJSONDSL } from "../dsl/GitDSL"
import { GitCommit } from "../dsl/Commit"
import { GitLabDSL, GitLabJSONDSL } from "../dsl/GitLabDSL"
import { debug } from "../debug"
import { dangerIDToString } from "../runner/templates/githubIssueTemplate"
import type * as Types from "@gitbeaker/rest"
const d = debug("GitLab")
/**
* Determines whether Danger should use threads for the "main" Danger comment.
*/
const useThreads = () =>
process.env.DANGER_GITLAB_USE_THREADS === "1" || process.env.DANGER_GITLAB_USE_THREADS === "true"
class GitLab implements Platform {
public readonly name: string
constructor(public readonly api: GitLabAPI) {
this.name = "GitLab"
}
getReviewInfo = async (): Promise<any> => {
return this.api.getMergeRequestInfo()
}
// returns the `danger.gitlab` object
getPlatformReviewDSLRepresentation = async (): Promise<GitLabJSONDSL> => {
const mr = await this.getReviewInfo()
const commits = await this.api.getMergeRequestCommits()
const approvals = await this.api.getMergeRequestApprovals()
return {
metadata: this.api.repoMetadata,
mr,
commits,
approvals,
}
}
// TODO: test
getPlatformGitRepresentation = async (): Promise<GitJSONDSL> => {
const diffs = await this.api.getMergeRequestDiffs()
const commits = await this.api.getMergeRequestCommits()
const mappedCommits: GitCommit[] = commits.map((commit) => {
return {
sha: commit.id,
author: {
name: commit.author_name,
email: commit.author_email as string,
date: commit.authored_date as string,
},
committer: {
name: commit.committer_name as string,
email: commit.committer_email as string,
date: commit.committed_date as string,
},
message: commit.message,
parents: commit.parent_ids as string[],
url: `${this.api.projectURL}/commit/${commit.id}`,
tree: null,
}
})
// XXX: does "renamed_file"/move count is "delete/create", or "modified"?
const modified_files: string[] = diffs
.filter((diff) => !diff.new_file && !diff.deleted_file)
.map((diff) => diff.new_path)
const created_files: string[] = diffs.filter((diff) => diff.new_file).map((diff) => diff.new_path)
const deleted_files: string[] = diffs.filter((diff) => diff.deleted_file).map((diff) => diff.new_path)
return {
modified_files,
created_files,
deleted_files,
commits: mappedCommits,
}
}
getInlineComments = async (dangerID: string): Promise<Comment[]> => {
d("getInlineComments", { dangerID })
const dangerUserID = (await this.api.getUser()).id
let dangerDiscussions = await this.getDangerDiscussions(dangerID)
// Remove system resolved danger discussions to not end up deleting danger inline comments
// on old versions of the diff. This is preferred as otherwise the discussion ends up in a state where
// the auto resolve system note can become the first note on the discussion resulting in poor change history on the MR.
dangerDiscussions = dangerDiscussions.filter((discussion) => !this.isDangerDiscussionSystemResolved(discussion))
d("getInlineComments found danger discussions", dangerDiscussions)
const diffNotes = this.getDiffNotesFromDiscussions(dangerDiscussions)
return diffNotes.map((note) => {
return {
id: `${note.id}`,
body: note.body,
ownedByDanger: note.author.id === dangerUserID && note.body.includes(dangerID),
}
})
}
supportsCommenting() {
return true
}
supportsInlineComments() {
return true
}
updateOrCreateComment = async (dangerID: string, newComment: string): Promise<string> => {
d("updateOrCreateComment", { dangerID, newComment })
if (useThreads()) {
const discussions = await this.getDangerDiscussions(dangerID)
d("updateOrCreateComment using threads, discussions", discussions)
const firstDiscussion = discussions.shift()
const existingNote = firstDiscussion?.notes?.[0]
await this.deleteDiscussions(discussions)
let newOrUpdatedNote: Types.DiscussionNoteSchema | undefined
if (existingNote) {
// update the existing comment
newOrUpdatedNote = await this.api.updateMergeRequestNote(existingNote.id, newComment)
} else {
// create a new comment
newOrUpdatedNote = (await this.api.createMergeRequestDiscussion(newComment))?.notes?.[0]
}
if (!newOrUpdatedNote) {
throw new Error("Could not update or create comment")
}
// create URL from note
// "https://gitlab.com/group/project/merge_requests/154#note_132143425"
return `${this.api.mergeRequestURL}#note_${newOrUpdatedNote.id}`
} else {
const notes = await this.getMainDangerNotes(dangerID)
d("updateOrCreateComment not using threads, main danger notes", notes)
let note: Types.MergeRequestNoteSchema
if (notes.length) {
// update the first
note = await this.api.updateMergeRequestNote(notes[0].id, newComment)
// delete the rest
for (let deleteme of notes) {
if (deleteme === notes[0]) {
continue
}
await this.api.deleteMergeRequestNote(deleteme.id)
}
} else {
// create a new note
note = await this.api.createMergeRequestNote(newComment)
}
// create URL from note
// "https://gitlab.com/group/project/merge_requests/154#note_132143425"
return `${this.api.mergeRequestURL}#note_${note.id}`
}
}
createComment = async (
_dangerID: string,
comment: string
): Promise<Types.DiscussionNoteSchema | Types.MergeRequestNoteSchema | undefined> => {
d("createComment", { comment })
if (useThreads()) {
return (await this.api.createMergeRequestDiscussion(comment))?.notes?.[0]
}
return this.api.createMergeRequestNote(comment)
}
createInlineComment = async (
git: GitDSL,
comment: string,
path: string,
line: number
): Promise<Types.DiscussionSchema> => {
d("createInlineComment", { git, comment, path, line })
const structuredDiffForFile = await git.structuredDiffForFile(path)
if (!structuredDiffForFile) {
return Promise.reject(`Unable to find diff for file ${path}`)
}
const inlinePosition = inlinePositionParser(structuredDiffForFile, path, line)
d("createInlineComment inlinePosition", inlinePosition)
const mr = await this.api.getMergeRequestInfo()
const position = {
positionType: "text",
baseSha: mr.diff_refs.base_sha,
startSha: mr.diff_refs.start_sha,
headSha: mr.diff_refs.head_sha,
oldPath: inlinePosition.pathDiff.oldPath,
newPath: inlinePosition.pathDiff.newPath,
oldLine: inlinePosition.lineDiff.oldLine?.toString(),
newLine: inlinePosition.lineDiff.newLine?.toString(),
} as Types.Camelize<Types.DiscussionNotePositionTextSchema>
return this.api.createMergeRequestDiscussion(comment, {
position: position,
})
}
updateInlineComment = async (comment: string, id: string): Promise<Types.MergeRequestNoteSchema> => {
d("updateInlineComment", { comment, id })
const nid = parseInt(id) // fingers crossed
return await this.api.updateMergeRequestNote(nid, comment)
}
deleteInlineComment = async (id: string): Promise<boolean> => {
d("deleteInlineComment", { id })
const nid = parseInt(id) // fingers crossed
return await this.api.deleteMergeRequestNote(nid)
}
/**
* Attempts to delete the "main" Danger comment. If the "main" Danger
* comment has any comments on it then that comment will not be deleted.
*/
deleteMainComment = async (dangerID: string): Promise<boolean> => {
if (useThreads()) {
const discussions = await this.getDangerDiscussions(dangerID)
return await this.deleteDiscussions(discussions)
} else {
const notes = await this.getMainDangerNotes(dangerID)
for (let note of notes) {
d("deleteMainComment", { id: note.id })
await this.api.deleteMergeRequestNote(note.id)
}
return notes.length > 0
}
}
deleteDiscussions = async (discussions: Types.DiscussionSchema[]): Promise<boolean> => {
d("deleteDiscussions", { length: discussions.length })
for (const discussion of discussions) {
await this.deleteDiscussion(discussion)
}
return discussions.length > 0
}
deleteDiscussion = async (discussion: Types.DiscussionSchema): Promise<boolean> => {
d("deleteDiscussion", { discussionId: discussion.id })
// There is no API to delete entire discussion. They can only be deleted fully by deleting every note
const discussionNotes = discussion.notes ?? []
for (const discussionNote of discussionNotes) {
await this.api.deleteMergeRequestNote(discussionNote.id)
}
return discussionNotes.length > 0
}
/**
* Only fetches the discussions where danger owns the top note
*/
getDangerDiscussions = async (dangerID: string): Promise<Types.DiscussionSchema[]> => {
const noteFilter = await this.getDangerDiscussionNoteFilter(dangerID)
const discussions = await this.api.getMergeRequestDiscussions()
return discussions.filter(({ notes }) => notes && notes.length && noteFilter(notes[0]))
}
isDangerDiscussionSystemResolved = (discussion: Types.DiscussionSchema): boolean => {
const notes = discussion.notes
if (!notes) {
return false
}
const dangerNote = notes[0]
if (!dangerNote || !dangerNote.resolved) {
return false
}
// Check for a system note that resolved it
return notes.some((note) => {
return note.system === true
})
}
getDiffNotesFromDiscussions = (discussions: Types.DiscussionSchema[]): Types.DiscussionNoteSchema[] => {
const diffNotes = discussions.map((discussion) => {
const note = discussion.notes?.[0]
if (!note || note.type != "DiffNote") {
return undefined
}
return note
})
return diffNotes.filter(Boolean) as Types.DiscussionNoteSchema[]
}
/**
* Attempts to find the "main" Danger note and should return at most
* one item. If the "main" Danger note has any comments on it then that
* note will not be returned.
*/
getMainDangerNotes = async (dangerID: string): Promise<Types.MergeRequestNoteSchema[]> => {
const noteFilter = await this.getDangerMainNoteFilter(dangerID)
const notes = await this.api.getMergeRequestNotes()
return notes.filter(noteFilter)
}
/**
* Filters a note to determine if it was created by Danger.
*/
getDangerDiscussionNoteFilter = async (dangerID: string): Promise<(note: Types.DiscussionNoteSchema) => boolean> => {
const { id: dangerUserId } = await this.api.getUser()
return ({ author: { id }, body, system }: Types.DiscussionNoteSchema): boolean => {
return (
!system && // system notes are generated when the user interacts with the UI e.g. changing a PR title
id === dangerUserId &&
body.includes(dangerIDToString(dangerID))
)
}
}
/**
* Filters a note to the "main" Danger note. If that note has any
* comments on it then it will not be found.
*/
getDangerMainNoteFilter = async (dangerID: string): Promise<(note: Types.MergeRequestNoteSchema) => boolean> => {
const { id: dangerUserId } = await this.api.getUser()
return ({ author: { id }, body, system, type }): boolean => {
return (
!system && // system notes are generated when the user interacts with the UI e.g. changing a PR title
id === dangerUserId &&
// This check for the type being `null` seems to be the best option
// we have to determine whether this note is the "main" Danger note.
// This assumption does not hold if there are any comments on the
// "main" Danger note and in that case a new "main" Danger note will
// be created instead of updating the existing note. This behavior is better
// than the current alternative which is the bug described here:
// https://github.com/danger/danger-js/issues/1351
type == null &&
body.includes(dangerIDToString(dangerID))
)
}
}
updateStatus = async (): Promise<boolean> => {
d("updateStatus", {})
return true
}
getFileContents = this.api.getFileContents
}
export default GitLab
export const gitlabJSONToGitLabDSL = (gl: GitLabDSL, api: GitLabAPI): GitLabDSL => ({
...gl,
utils: {
fileContents: api.getFileContents,
addLabels: api.addLabels,
removeLabels: api.removeLabels,
},
api: api.apiInstance,
})