-
-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathcomment.ts
385 lines (332 loc) · 10.9 KB
/
comment.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
import { ValidationError } from '@changesets/errors'
import type {
ComprehensiveRelease,
ReleasePlan,
VersionType,
} from '@changesets/types'
import type { Gitlab } from '@gitbeaker/core'
import type {
DiscussionNoteSchema,
DiscussionSchema,
MergeRequestChangesSchema,
MergeRequestNoteSchema,
NoteSchema,
} from '@gitbeaker/rest'
import { captureException } from '@sentry/node'
import { humanId } from 'human-id'
import { markdownTable } from 'markdown-table'
import * as context from './context.js'
import { env } from './env.js'
import { getChangedPackages } from './get-changed-packages.js'
import type { LooseString } from './types.js'
import { getUsername } from './utils.js'
import { createApi } from './index.js'
const generatedByBotNote = 'Generated By Changesets GitLab Bot'
const getReleasePlanMessage = (releasePlan: ReleasePlan | null) => {
if (!releasePlan) return ''
const publishableReleases = releasePlan.releases.filter(
(x): x is ComprehensiveRelease & { type: Exclude<VersionType, 'none'> } =>
x.type !== 'none',
)
const table = markdownTable([
['Name', 'Type'],
...publishableReleases.map(x => [
x.name,
{
major: 'Major',
minor: 'Minor',
patch: 'Patch',
}[x.type],
]),
])
return `<details><summary>This MR includes ${
releasePlan.changesets.length > 0
? `changesets to release ${
publishableReleases.length === 1
? '1 package'
: `${publishableReleases.length} packages`
}`
: 'no changesets'
}</summary>
${
publishableReleases.length > 0
? table
: "When changesets are added to this MR, you'll see the packages that this MR includes changesets for and the associated semver types"
}
</details>`
}
const getAbsentMessage = (
commitSha: string,
addChangesetUrl: string,
releasePlan: ReleasePlan | null,
) => `### ⚠️ No Changeset found
Latest commit: ${commitSha}
Merging this MR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. **If these changes should result in a version bump, you need to add a changeset.**
${getReleasePlanMessage(releasePlan)}
[Click here to learn what changesets are, and how to add one](https://github.com/changesets/changesets/blob/master/docs/adding-a-changeset.md).
[Click here if you're a maintainer who wants to add a changeset to this MR](${addChangesetUrl})
__${generatedByBotNote}__
`
const getApproveMessage = (
commitSha: string,
addChangesetUrl: string,
releasePlan: ReleasePlan | null,
) => `### 🦋 Changeset detected
Latest commit: ${commitSha}
**The changes in this MR will be included in the next version bump.**
${getReleasePlanMessage(releasePlan)}
Not sure what this means? [Click here to learn what changesets are](https://github.com/changesets/changesets/blob/master/docs/adding-a-changeset.md).
[Click here if you're a maintainer who wants to add another changeset to this MR](${addChangesetUrl})
__${generatedByBotNote}__
`
const getNewChangesetTemplate = (changedPackages: string[], title: string) =>
encodeURIComponent(`---
${changedPackages.map(x => `"${x}": patch`).join('\n')}
---
${title}
`)
const isMrNote = (
discussionOrNote: DiscussionSchema | MergeRequestNoteSchema,
): discussionOrNote is MergeRequestNoteSchema =>
'noteable_type' in discussionOrNote &&
discussionOrNote.noteable_type === 'MergeRequest'
const RANDOM_BOT_NAME_PATTERN = /^((?:project|group)_\d+_bot\w*)_[\da-z]+$/i
const isChangesetBotNote = (
note: DiscussionNoteSchema | NoteSchema,
username: string,
random?: boolean,
) =>
(note.author.username === username ||
(random &&
note.author.username.match(RANDOM_BOT_NAME_PATTERN)?.[1] === username)) &&
// We need to ensure the note is generated by us, but we don't have an app bot like GitHub
// @see https://github.com/apps/changeset-bot
note.body.includes(generatedByBotNote)
async function getNoteInfo(
api: Gitlab,
mrIid: number | string,
commentType: LooseString<'discussion'>,
random?: boolean,
): Promise<{ discussionId: string; noteId: number } | null | undefined>
async function getNoteInfo(
api: Gitlab,
mrIid: number | string,
commentType: LooseString<'note'>,
random?: boolean,
): Promise<{ noteId: number } | null | undefined>
async function getNoteInfo(
api: Gitlab,
mrIid: number | string,
commentType: LooseString<'discussion' | 'note'>,
random?: boolean,
): Promise<
| { discussionId: string; noteId: number }
| { noteId: number }
| null
| undefined
> {
const discussionOrNotes = await (commentType === 'discussion'
? api.MergeRequestDiscussions.all(context.projectId, mrIid)
: api.MergeRequestNotes.all(context.projectId, +mrIid))
const username = await getUsername(api)
for (const discussionOrNote of discussionOrNotes) {
if (isMrNote(discussionOrNote)) {
if (isChangesetBotNote(discussionOrNote, username, random)) {
return {
noteId: discussionOrNote.id,
}
}
continue
}
if (!discussionOrNote.notes) {
continue
}
const changesetBotNote = discussionOrNote.notes.find(note =>
isChangesetBotNote(note, username),
)
if (changesetBotNote) {
return {
discussionId: discussionOrNote.id,
noteId: changesetBotNote.id,
}
}
}
/**
* The `username` used for commenting could be random, if we haven't tested the random `username`, then test it
*
* @see https://docs.gitlab.com/ee/development/internal_users.html
* @see https://github.com/un-ts/changesets-gitlab/issues/145#issuecomment-1860610958
*/
return random ? null : getNoteInfo(api, mrIid, commentType, true)
}
const hasChangesetBeenAdded = async (
changedFilesPromise: Promise<MergeRequestChangesSchema>,
) => {
const changedFiles = await changedFilesPromise
return changedFiles.changes.some(file => {
return (
file.new_file &&
/^\.changeset\/.+\.md$/.test(file.new_path) &&
file.new_path !== '.changeset/README.md'
)
})
}
/**
* @see https://github.com/jdalrymple/gitbeaker/blob/52ef0e622de304d98afb811f4937560edefd8889/packages/rest/src/Requester.ts#L79-L86
*/
export interface GitLabAPIError extends Error {
cause: {
description: string
request: Request
response: Response
}
}
const GITLAB_API_ERROR_CAUSE_KEYS = new Set([
'description',
'request',
'response',
])
// eslint-disable-next-line @typescript-eslint/unbound-method
const { toString } = Object.prototype
const isError = (value: unknown): value is Error =>
toString.call(value) === '[object Error]'
const isGitLabAPIError = (error: unknown): error is GitLabAPIError =>
isError(error) &&
!!error.cause &&
typeof error.cause === 'object' &&
Object.keys(error.cause).every(key => GITLAB_API_ERROR_CAUSE_KEYS.has(key))
// eslint-disable-next-line sonarjs/cognitive-complexity
export const comment = async () => {
const mrBranch = env.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME
if (!mrBranch) {
console.warn('[changesets-gitlab:comment] It should only be used on MR')
return
}
const {
CI_MERGE_REQUEST_IID: mrIid,
CI_MERGE_REQUEST_PROJECT_URL,
CI_MERGE_REQUEST_SOURCE_BRANCH_SHA,
CI_MERGE_REQUEST_TITLE,
GITLAB_COMMENT_TYPE,
GITLAB_COMMENT_DISCUSSION_AUTORESOLVE,
GITLAB_ADD_CHANGESET_MESSAGE,
} = env
if (mrBranch.startsWith('changeset-release')) {
return
}
const api = createApi()
let errFromFetchingChangedFiles = ''
try {
const latestCommitSha = CI_MERGE_REQUEST_SOURCE_BRANCH_SHA
const changedFilesPromise = api.MergeRequests.showChanges(
context.projectId,
mrIid,
)
const [noteInfo, hasChangeset, { changedPackages, releasePlan }] =
await Promise.all([
getNoteInfo(api, mrIid, GITLAB_COMMENT_TYPE),
hasChangesetBeenAdded(changedFilesPromise),
getChangedPackages({
changedFiles: changedFilesPromise.then(x =>
x.changes.map(x => x.new_path),
),
api,
}).catch((err: unknown) => {
if (err instanceof ValidationError) {
errFromFetchingChangedFiles = `<details><summary>💥 An error occurred when fetching the changed packages and changesets in this MR</summary>\n\n\`\`\`\n${err.message}\n\`\`\`\n\n</details>\n`
} else {
console.error(err)
captureException(err)
}
return {
changedPackages: ['@fake-scope/fake-pkg'],
releasePlan: null,
}
}),
] as const)
const addChangesetUrl = `${CI_MERGE_REQUEST_PROJECT_URL}/-/new/${mrBranch}?file_name=.changeset/${humanId(
{
separator: '-',
capitalize: false,
},
)}.md&file=${getNewChangesetTemplate(
changedPackages,
CI_MERGE_REQUEST_TITLE,
)}${
GITLAB_ADD_CHANGESET_MESSAGE
? '&commit_message=' + encodeURIComponent(GITLAB_ADD_CHANGESET_MESSAGE)
: ''
}`
const prComment =
(hasChangeset
? getApproveMessage(latestCommitSha, addChangesetUrl, releasePlan)
: getAbsentMessage(latestCommitSha, addChangesetUrl, releasePlan)) +
errFromFetchingChangedFiles
switch (GITLAB_COMMENT_TYPE) {
case 'discussion': {
if (noteInfo) {
if (
GITLAB_COMMENT_DISCUSSION_AUTORESOLVE === 'always' ||
(GITLAB_COMMENT_DISCUSSION_AUTORESOLVE === 'hasChangeset' &&
hasChangeset)
) {
await api.MergeRequestDiscussions.resolve(
context.projectId,
mrIid,
noteInfo.discussionId,
true,
)
}
return api.MergeRequestDiscussions.editNote(
context.projectId,
mrIid,
noteInfo.discussionId,
noteInfo.noteId,
{
body: prComment,
},
)
}
return api.MergeRequestDiscussions.create(
context.projectId,
mrIid,
prComment,
)
}
case 'note': {
if (noteInfo) {
return api.MergeRequestNotes.edit(
context.projectId,
mrIid,
noteInfo.noteId,
{ body: prComment },
)
}
return api.MergeRequestNotes.create(context.projectId, mrIid, prComment)
}
default: {
throw new Error(
`Invalid comment type "${GITLAB_COMMENT_TYPE}", should be "discussion" or "note"`,
)
}
}
} catch (err: unknown) {
if (isGitLabAPIError(err)) {
const {
cause: { description, request, response },
} = err
console.error(description)
try {
console.error('request:', await request.text())
} catch {
console.error("The error's request could not be used as plain text")
}
try {
console.error('response:', await response.text())
} catch {
console.error("The error's response could not be used as plain text")
}
}
throw err
}
}