Skip to content

Built for people who want to own their automations. Join the waitlist for an invite.

Package listing

@kody/gitlab

src/pipelines/create.ts

58 lines · 1.5 KB · TypeScript
import { isConfirmed, isDryRun, normalizeProjectLocator, pickAuthInput, request } from '../core.ts'
import { asRecord, readOptionalString, slimPipeline } from '../shape.ts'

/**
 * Create a GitLab pipeline.
 *
 * Pass `dryRun: true` to preview the request. Live creates require `confirm: true`.
 *
 * @example
 * import createGitlabPipeline from 'kody:@kody/gitlab/pipelines/create'
 * const preview = await createGitlabPipeline({
 *   project: 'example-group/example-project',
 *   ref: 'main',
 *   dryRun: true,
 * })
 */
export default async function createGitlabPipeline(params: Record<string, unknown> = {}) {
	const auth = pickAuthInput(params)
	const { projectId, projectPath } = normalizeProjectLocator(params)
	const ref = readOptionalString(params.ref)
	if (!ref) {
		throw new Error('ref is required (branch, tag, or commit SHA)')
	}

	const body: Record<string, unknown> = { ref }
	if (params.variables !== undefined) body.variables = params.variables

	if (isDryRun(params)) {
		return {
			dryRun: true,
			wouldCreate: true,
			projectPath,
			body,
			auth,
		}
	}

	if (!isConfirmed(params)) {
		throw new Error(
			`Creating a pipeline in ${projectPath} requires dryRun: true (preview) or confirm: true (live write).`,
		)
	}

	const response = await request<Record<string, unknown>>({
		...auth,
		method: 'POST',
		path: `/projects/${projectId}/pipeline`,
		body,
		throwOnError: true,
		confirm: true,
	})

	return {
		...slimPipeline(asRecord(response.data)),
		projectPath,
		auth: response.auth,
	}
}