Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/close-discussion-with-changeset.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"changesets-gitlab": patch
---

**Fixed** Close the merge request discussion on the same run that finds a changeset, including the run that creates the discussion, and reopen it when the changeset is removed.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ GITLAB_TOKEN_TYPE # optional, type of the provided token in
GITLAB_CI_USER_NAME # optional, username with accessibility to push, used in pairs of the above token (if it was personal access token). If not set read it from the Gitlab API
GITLAB_CI_USER_EMAIL # optional, default `gitlab[bot]@users.noreply.gitlab.com`
GITLAB_COMMENT_TYPE # optional, type of the comment. defaults to `discussion`. can be set to `note` to not create a discussion instead of a thread
GITLAB_COMMENT_DISCUSSION_AUTO_RESOLVE # optional, automatically resolve added discussion when changeset is present, if you want to always resolve the discussion, you should actually use `GITLAB_COMMENT_TYPE=note` instead, default `true`
GITLAB_COMMENT_DISCUSSION_AUTO_RESOLVE # optional, resolve the discussion when a changeset is present (including the run that creates it) and reopen it when the changeset is removed. To avoid a resolvable thread, use `GITLAB_COMMENT_TYPE=note` instead. Default `true`
GITLAB_COMMENT_CUSTOM_LINKS # optional, override the links content referenced in the cli bot comment, use {{ addChangesetUrl }} placeholder for the dynamic URL to add a changeset
GITLAB_ADD_CHANGESET_MESSAGE # optional, default commit message for adding changesets on GitLab Web UI
DEBUG_GITLAB_CREDENTIAL # optional, set to `1`/`true` to echo the remote URL when debugging git authentication; WARNING: the remote URL may contain credentials
Expand Down
36 changes: 28 additions & 8 deletions src/comment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,11 @@ async function getNoteInfo(
mrIid: number,
commentType: LooseString<'discussion'>,
random?: boolean,
): Promise<{ discussionId: string; noteId: number } | null | undefined>
): Promise<
| { discussionId: string; individualNote: boolean; noteId: number }
| null
| undefined
>
async function getNoteInfo(
api: Gitlab,
mrIid: number,
Expand All @@ -175,7 +179,7 @@ async function getNoteInfo(
commentType: LooseString<'discussion' | 'note'>,
random?: boolean,
): Promise<
| { discussionId: string; noteId: number }
| { discussionId: string; individualNote: boolean; noteId: number }
| { noteId: number }
| null
| undefined
Expand Down Expand Up @@ -207,6 +211,7 @@ async function getNoteInfo(
if (changesetBotNote) {
return {
discussionId: discussionOrNote.id,
individualNote: discussionOrNote.individual_note,
noteId: changesetBotNote.id,
}
}
Expand Down Expand Up @@ -348,6 +353,7 @@ ${newChangesetTemplate}
return { body: prComment, hasChangeset }
}

// eslint-disable-next-line sonarjs/cognitive-complexity
export const comment = async () => {
const mrBranch = env.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME
if (!mrBranch) {
Expand Down Expand Up @@ -377,16 +383,19 @@ export const comment = async () => {

switch (commentType) {
case 'discussion': {
const autoResolve = TRUTHY_VALUES.has(
env.GITLAB_COMMENT_DISCUSSION_AUTO_RESOLVE || '1',
)

if (noteInfo) {
if (
hasChangeset &&
TRUTHY_VALUES.has(env.GITLAB_COMMENT_DISCUSSION_AUTO_RESOLVE || '1')
) {
// Individual notes are never resolvable: GitLab rejects both
// resolving and reopening them, and the comment update never runs.
if (autoResolve && !noteInfo.individualNote) {
await api.MergeRequestDiscussions.resolve(
context.projectId,
mrIid,
noteInfo.discussionId,
true,
hasChangeset,
)
}

Expand All @@ -401,11 +410,22 @@ export const comment = async () => {
)
}

return api.MergeRequestDiscussions.create(
const discussion = await api.MergeRequestDiscussions.create(
context.projectId,
mrIid,
prComment,
)

if (hasChangeset && autoResolve) {
await api.MergeRequestDiscussions.resolve(
context.projectId,
mrIid,
discussion.id,
true,
)
}

return discussion
}
case 'note': {
if (noteInfo) {
Expand Down
236 changes: 236 additions & 0 deletions test/comment.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@
const { MR_IID, PROJECT_ID, mockApi } = vi.hoisted(() => {
const PROJECT_ID = '42'
const MR_IID = 12
// `src/env.ts` and `src/context.ts` capture CI variables at module load.
process.env.CI_PROJECT_ID = PROJECT_ID
process.env.CI_MERGE_REQUEST_IID = String(MR_IID)
process.env.CI_MERGE_REQUEST_PROJECT_URL =
'https://gitlab.example/group/project'
process.env.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME = 'feature'
process.env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA = 'abc123'
process.env.CI_MERGE_REQUEST_TITLE = 'Add feature'
process.env.GITLAB_CI_USER_NAME = 'ci-bot'
process.env.GITLAB_TOKEN = 'glpat-token'
process.env.GITLAB_COMMENT_TYPE = 'discussion'
process.env.GITLAB_COMMENT_DISCUSSION_AUTO_RESOLVE = '1'
return {
MR_IID,
PROJECT_ID,
mockApi: {
MergeRequests: {
allDiffs: vi.fn(),
},
MergeRequestDiscussions: {
all: vi.fn(),
create: vi.fn(),
editNote: vi.fn(),
resolve: vi.fn(),
},
MergeRequestNotes: {
all: vi.fn(),
create: vi.fn(),
edit: vi.fn(),
},
},
}
})

vi.mock('../src/api.ts', () => ({
createApi: () => mockApi,
}))

vi.mock('../src/get-changed-packages.js', () => ({
getChangedPackages: () =>
Promise.resolve({
changedPackages: ['pkg'],
releasePlan: {
changesets: [],
releases: [],
},
}),
}))

const { comment } = await import('../src/comment.js')

const DISCUSSION_ID = 'disc-new'
const EXISTING_DISCUSSION_ID = 'disc-existing'

const changesetDiff = {
new_file: true,
new_path: '.changeset/brave-lions-sing.md',
}

const existingDiscussion = {
id: EXISTING_DISCUSSION_ID,
individual_note: false,
notes: [
{
id: 11,
author: { username: 'ci-bot' },
body: 'previous\n__Generated By Changesets GitLab Bot__',
},
],
}

const originalEnv = { ...process.env }

beforeEach(() => {
vi.clearAllMocks()
vi.unstubAllEnvs()

mockApi.MergeRequests.allDiffs.mockResolvedValue([])
mockApi.MergeRequestDiscussions.all.mockResolvedValue([])
mockApi.MergeRequestDiscussions.create.mockResolvedValue({
id: DISCUSSION_ID,
})
mockApi.MergeRequestDiscussions.editNote.mockResolvedValue({
id: existingDiscussion.notes[0].id,
})
mockApi.MergeRequestDiscussions.resolve.mockResolvedValue({
id: DISCUSSION_ID,
})
mockApi.MergeRequestNotes.all.mockResolvedValue([])
mockApi.MergeRequestNotes.create.mockResolvedValue({ id: 99 })
mockApi.MergeRequestNotes.edit.mockResolvedValue({ id: 99 })
})

afterAll(() => {
process.env = { ...originalEnv }
})

describe('comment', () => {
test('creates the discussion and resolves it when a changeset is already present', async () => {
mockApi.MergeRequests.allDiffs.mockResolvedValue([changesetDiff])

await comment()

expect(mockApi.MergeRequestDiscussions.create).toHaveBeenCalledOnce()
expect(mockApi.MergeRequestDiscussions.create).toHaveBeenCalledWith(
PROJECT_ID,
MR_IID,
expect.stringContaining('Changeset detected'),
)
expect(mockApi.MergeRequestDiscussions.resolve).toHaveBeenCalledWith(
PROJECT_ID,
MR_IID,
DISCUSSION_ID,
true,
)
expect(mockApi.MergeRequestDiscussions.create).toHaveBeenCalledBefore(
mockApi.MergeRequestDiscussions.resolve,
)
})

test('creates an open discussion when the merge request has no changeset', async () => {
await comment()

expect(mockApi.MergeRequestDiscussions.create).toHaveBeenCalledWith(
PROJECT_ID,
MR_IID,
expect.stringContaining('No Changeset found'),
)
expect(mockApi.MergeRequestDiscussions.resolve).not.toHaveBeenCalled()
})

test('resolves an existing discussion when a changeset is present', async () => {
mockApi.MergeRequests.allDiffs.mockResolvedValue([changesetDiff])
mockApi.MergeRequestDiscussions.all.mockResolvedValue([existingDiscussion])

await comment()

expect(mockApi.MergeRequestDiscussions.create).not.toHaveBeenCalled()
expect(mockApi.MergeRequestDiscussions.resolve).toHaveBeenCalledWith(
PROJECT_ID,
MR_IID,
EXISTING_DISCUSSION_ID,
true,
)
expect(mockApi.MergeRequestDiscussions.resolve).toHaveBeenCalledBefore(
mockApi.MergeRequestDiscussions.editNote,
)
})

test('reopens an existing discussion when the changeset is removed', async () => {
mockApi.MergeRequestDiscussions.all.mockResolvedValue([existingDiscussion])

await comment()

expect(mockApi.MergeRequestDiscussions.resolve).toHaveBeenCalledWith(
PROJECT_ID,
MR_IID,
EXISTING_DISCUSSION_ID,
false,
)
const editCall = mockApi.MergeRequestDiscussions.editNote.mock.calls[0]
expect(editCall[0]).toBe(PROJECT_ID)
expect(editCall[1]).toBe(MR_IID)
expect(editCall[2]).toBe(EXISTING_DISCUSSION_ID)
expect(editCall[3]).toBe(existingDiscussion.notes[0].id)
expect(JSON.stringify(editCall[4])).toContain('No Changeset found')
})

test('updates an individual note without reopening it when no changeset exists', async () => {
mockApi.MergeRequestDiscussions.all.mockResolvedValue([
{ ...existingDiscussion, individual_note: true },
])

await comment()

expect(mockApi.MergeRequestDiscussions.resolve).not.toHaveBeenCalled()
expect(mockApi.MergeRequestDiscussions.editNote).toHaveBeenCalledOnce()
})

test('updates an individual note without resolving it when a changeset is present', async () => {
mockApi.MergeRequests.allDiffs.mockResolvedValue([changesetDiff])
mockApi.MergeRequestDiscussions.all.mockResolvedValue([
{ ...existingDiscussion, individual_note: true },
])

await comment()

expect(mockApi.MergeRequestDiscussions.resolve).not.toHaveBeenCalled()
expect(mockApi.MergeRequestDiscussions.editNote).toHaveBeenCalledOnce()
expect(
JSON.stringify(mockApi.MergeRequestDiscussions.editNote.mock.calls[0]),
).toContain('Changeset detected')
})

test('does not resolve a new discussion when auto-resolve is disabled', async () => {
vi.stubEnv('GITLAB_COMMENT_DISCUSSION_AUTO_RESOLVE', 'false')
vi.resetModules()
const { comment: commentWithoutAutoResolve } =
await import('../src/comment.js')
mockApi.MergeRequests.allDiffs.mockResolvedValue([changesetDiff])

await commentWithoutAutoResolve()

expect(mockApi.MergeRequestDiscussions.create).toHaveBeenCalledOnce()
expect(mockApi.MergeRequestDiscussions.resolve).not.toHaveBeenCalled()
})

test('does not reopen an existing discussion when auto-resolve is disabled', async () => {
vi.stubEnv('GITLAB_COMMENT_DISCUSSION_AUTO_RESOLVE', 'false')
vi.resetModules()
const { comment: commentWithoutAutoResolve } =
await import('../src/comment.js')
mockApi.MergeRequestDiscussions.all.mockResolvedValue([existingDiscussion])

await commentWithoutAutoResolve()

expect(mockApi.MergeRequestDiscussions.editNote).toHaveBeenCalledOnce()
expect(mockApi.MergeRequestDiscussions.resolve).not.toHaveBeenCalled()
})

test('posts a note instead of a discussion when the comment type is note', async () => {
vi.stubEnv('GITLAB_COMMENT_TYPE', 'note')
vi.resetModules()
const { comment: commentAsNote } = await import('../src/comment.js')
mockApi.MergeRequests.allDiffs.mockResolvedValue([changesetDiff])

await commentAsNote()

expect(mockApi.MergeRequestNotes.create).toHaveBeenCalledOnce()
expect(mockApi.MergeRequestDiscussions.create).not.toHaveBeenCalled()
expect(mockApi.MergeRequestDiscussions.resolve).not.toHaveBeenCalled()
})
})
Loading