forked from un-ts/changesets-gitlab
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomment.ts
261 lines (217 loc) · 7.36 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
import { ValidationError } from '@changesets/errors'
import type {
ComprehensiveRelease,
ReleasePlan,
VersionType,
} from '@changesets/types'
import type { Gitlab, MergeRequests } from '@gitbeaker/core'
import { captureException } from '@sentry/node'
import { humanId } from 'human-id'
import { markdownTable } from 'markdown-table'
import * as context from './context.js'
import { getChangedPackages } from './get-changed-packages.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 getNoteInfo = (api: Gitlab, mrIid: number | string) =>
api.MergeRequestDiscussions.all(context.projectId, mrIid).then(
async discussions => {
for (const discussion of discussions) {
if (!discussion.notes) {
continue
}
const username = await getUsername(api)
const changesetBotNote = discussion.notes.find(
note =>
note.author.username === 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),
)
if (changesetBotNote) {
return {
discussionId: discussion.id,
noteId: changesetBotNote.id,
}
}
}
},
)
const hasChangesetBeenAdded = (
changedFilesPromise: ReturnType<MergeRequests['changes']>,
) =>
changedFilesPromise.then(files =>
files.changes!.some(
file =>
file.new_file &&
/^\.changeset\/.+\.md$/.test(file.new_path) &&
file.new_path !== '.changeset/README.md',
),
)
const getCommentFunctions = (api: Gitlab, commentType: string) => {
if (commentType === 'discussion') {
return {
editComment: api.MergeRequestDiscussions.editNote.bind(
api.MergeRequestDiscussions,
),
createComment: api.MergeRequestDiscussions.create.bind(
api.MergeRequestDiscussions,
),
}
}
if (commentType === 'note') {
return {
editComment: api.MergeRequestNotes.edit.bind(api.MergeRequestNotes),
createComment: api.MergeRequestNotes.create.bind(api.MergeRequestNotes),
}
}
throw new Error(
`Invalid comment type "${commentType}", should be "discussion" or "note"`,
)
}
export const comment = async () => {
const {
CI_MERGE_REQUEST_IID,
CI_MERGE_REQUEST_PROJECT_URL,
CI_MERGE_REQUEST_SOURCE_BRANCH_NAME: mrBranch,
CI_MERGE_REQUEST_SOURCE_BRANCH_SHA,
CI_MERGE_REQUEST_TITLE,
GITLAB_COMMENT_TYPE = 'discussion',
} = process.env
if (!mrBranch) {
console.warn('[changesets-gitlab:comment] It should only be used on MR')
return
}
if (mrBranch.startsWith('changeset-release')) {
return
}
const api = createApi()
let errFromFetchingChangedFiles = ''
const mrIid = +CI_MERGE_REQUEST_IID!
try {
const latestCommitSha = CI_MERGE_REQUEST_SOURCE_BRANCH_SHA!
const changedFilesPromise = api.MergeRequests.changes(
context.projectId,
mrIid,
)
const [noteInfo, hasChangeset, { changedPackages, releasePlan }] =
await Promise.all([
getNoteInfo(api, mrIid),
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!,
)}`
const prComment =
(hasChangeset
? getApproveMessage(latestCommitSha, addChangesetUrl, releasePlan)
: getAbsentMessage(latestCommitSha, addChangesetUrl, releasePlan)) +
errFromFetchingChangedFiles
const { editComment, createComment } = getCommentFunctions(
api,
GITLAB_COMMENT_TYPE,
)
if (noteInfo != null) {
return editComment(
context.projectId,
mrIid,
// @ts-expect-error - https://github.com/jdalrymple/gitbeaker/pull/523#issuecomment-975276068
noteInfo.discussionId,
noteInfo.noteId,
{
body: prComment,
},
)
}
return createComment(context.projectId, mrIid, prComment)
} catch (err: unknown) {
console.error(err)
throw err
}
}