Edits history of script submission #23979 for ' Create merge request (gitlab)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Create merge request
     * Open a merge request from source_branch into target_branch (the project's default branch when empty), with an optional description, labels, assignees and reviewers.
     */
    export async function main(
      auth: RT.Gitlab,
      project: string,
      source_branch: string,
      title: string,
      target_branch: string | undefined,
      description: string | undefined,
      labels: string[] | undefined,
      assignee_ids: number[] | undefined,
      reviewer_ids: number[] | undefined,
      remove_source_branch: boolean = false,
      squash: boolean = false
    ) {
      const api = `${(auth.baseUrl || "https://gitlab.com").replace(/\/+$/, "")}/api/v4/projects/${encodeURIComponent(project)}`
      const headers = {
        Authorization: `Bearer ${auth.token}`,
        Accept: "application/json",
      }
    
      let target = target_branch
      if (!target) {
        const response = await fetch(api, { headers })
        if (!response.ok) {
          throw new Error(`${response.status} ${await response.text()}`)
        }
        target = (await response.json()).default_branch as string
        if (!target) {
          throw new Error(
            `${project} has no default branch (empty repository): set target_branch`
          )
        }
      }
    
      const response = await fetch(`${api}/merge_requests`, {
        method: "POST",
        headers: { ...headers, "Content-Type": "application/json" },
        body: JSON.stringify({
          source_branch,
          target_branch: target,
          title,
          description: description || undefined,
          labels: labels?.length ? labels.join(",") : undefined,
          assignee_ids: assignee_ids?.length ? assignee_ids : undefined,
          reviewer_ids: reviewer_ids?.length ? reviewer_ids : undefined,
          // Only when ticked: false would override the project's own defaults.
          remove_source_branch: remove_source_branch || undefined,
          squash: squash || undefined,
        }),
      })
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      return await response.json()
    }
    

    Submitted by hugo989 8 hours ago