import { isConfirmed, isDryRun, normalizeMergeRequestLocator, pickAuthInput, request } from '../core.ts'
import { asRecord, readOptionalString, slimMergeRequest } from '../shape.ts'
/**
* Update a GitLab merge request.
*
* Pass `dryRun: true` to preview the request. Live updates require `confirm: true`.
*
* @example
* import updateGitlabMergeRequest from 'kody:@kody/gitlab/merge-requests/update'
* const preview = await updateGitlabMergeRequest({
* project: 'example-group/example-project',
* mergeRequestIid: 4,
* state_event: 'close',
* dryRun: true,
* })
*/
export default async function updateGitlabMergeRequest(params: Record<string, unknown> = {}) {
const auth = pickAuthInput(params)
const { projectId, projectPath, mergeRequestIid } = normalizeMergeRequestLocator(params)
const body: Record<string, unknown> = {}
const title = readOptionalString(params.title)
if (title) body.title = title
if (params.description !== undefined) {
body.description = readOptionalString(params.description) ?? ''
}
const labels = readOptionalString(params.labels)
if (labels) body.labels = labels
const stateEvent = readOptionalString(params.state_event ?? params.stateEvent)
if (stateEvent) body.state_event = stateEvent
const targetBranch = readOptionalString(params.target_branch ?? params.targetBranch)
if (targetBranch) body.target_branch = targetBranch
if (Object.keys(body).length === 0) {
throw new Error(
'Provide at least one field to update (title, description, labels, state_event, target_branch).',
)
}
if (isDryRun(params)) {
return {
dryRun: true,
wouldUpdate: true,
projectPath,
mergeRequestIid,
body,
auth,
}
}
if (!isConfirmed(params)) {
throw new Error(
`Updating ${projectPath}!${mergeRequestIid} requires dryRun: true (preview) or confirm: true (live write).`,
)
}
const response = await request<Record<string, unknown>>({
...auth,
method: 'PUT',
path: `/projects/${projectId}/merge_requests/${mergeRequestIid}`,
body,
throwOnError: true,
confirm: true,
})
return {
...slimMergeRequest(asRecord(response.data)),
projectPath,
auth: response.auth,
}
}