Bitbucket Create/Delete branch based on Jira workflow
Asked by Ramya Yarru:

Hello Team,

Can we Create/Delete branch in bitbucket based on Jira workflow?

Please advise.


Answers:
author: Max Lim _Adaptavist_
body: Yes, you certainly can. You would need ScriptRunner in your Jira instance.

There are two ways to do it. Basically you make a POST call using the following [Rest API](https://docs.atlassian.com/bitbucket-server/rest/7.18.1/bitbucket-branch-rest.html#idp1) to create a branch in a workflow post function **from Jira to BitBucket**:

### /rest/branch-utils/1.0/projects/{projectKey}/repos/{repositorySlug}/branches {#toc-hId-1288481720}

### With App links, without need to pass username and password {#toc-hId--518972743}

1. Setup the app links as mentioned in this [documentation](https://docs.adaptavist.com/sr4js/latest/integrations/atlassian-products/via-app-links).

2. Following snippet works as I have tested:

```
import com.atlassian.applinks.api.ApplicationLinkResponseHandler
import com.atlassian.applinks.api.ApplicationLinkResponseHandler
import com.atlassian.applinks.api.ApplicationLinkService
import com.atlassian.applinks.api.application.bitbucket.BitbucketApplicationType
import com.atlassian.sal.api.component.ComponentLocator
import groovy.json.JsonSlurper
import com.atlassian.sal.api.net.Request
import com.atlassian.sal.api.net.Response
import com.atlassian.sal.api.net.ResponseException
import com.atlassian.sal.api.net.ResponseHandler

import groovy.json.JsonBuilder

def appLinkService = ComponentLocator.getComponent(ApplicationLinkService)
def appLink = appLinkService.getPrimaryApplicationLink(BitbucketApplicationType)
def applicationLinkRequestFactory = appLink.createAuthenticatedRequestFactory()

Map body = [
  name: "test-branch",
  startPoint: "refs/heads/master",
]

def request = applicationLinkRequestFactory
  .createRequest(Request.MethodType.POST, "/rest/branch-utils/1.0/projects/JP/repos/just-repository/branches")
  .addHeader("Content-Type", "application/json")
  .setRequestBody(new JsonBuilder(body).toString())
  .execute(new ApplicationLinkResponseHandler<Map>() {
    @Override
    Map credentialsRequired(Response response) throws ResponseException {
      return null
    }
    @Override
    Map handle(Response response) throws ResponseException {
      new JsonSlurper().parseText(response.getResponseBodyAsString()) as Map
    }
  })
```

### With username and password {#toc-hId-1968540090}

You can use this [sample script](https://library.adaptavist.com/entity/using-external-apis-in-sr) from our library as reference to make the same POST call:

```
import groovy.json.JsonOutput
import groovy.json.JsonBuilder
import groovyx.net.http.ContentType
import groovyx.net.http.HttpResponseDecorator
import groovyx.net.http.RESTClient

final externalUrl = "http://<BitBucket_Base_URL>/"

def body = [
  name: "test-branch",
  startPoint: "refs/heads/master",
]

def postResponse = post(externalUrl, "/rest/branch-utils/1.0/projects/JP/repos/just-repository/branches", new JsonBuilder(body).toString())

def post(def hostUrl, def endpointAndQuery, def bodyJson) {
  def client = new RESTClient(hostUrl)
  client.setHeaders([
    'Accept' : ContentType.JSON,
    'Authorization': "Basic ${'xxxx:xxxxxxxx'.bytes.encodeBase64()}"
  ])
  client.handler.success = { HttpResponseDecorator response, json ->
    json
  }
  client.handler.failure = { HttpResponseDecorator response ->
    // Failure can be handled here
    log.error response.entity.content.text
    [:]
  }
  client.post(
    path: endpointAndQuery,
    contentType: ContentType.JSON,
    body: bodyJson
  )
}
```

Please note that this will hardcode a username and password in your script.

Deleting a branch is just similar using a DELETE call on the same [REST API](https://docs.atlassian.com/bitbucket-server/rest/7.18.1/bitbucket-branch-rest.html#idp2).

I hope this helps!

comments: author: Ramya Yarru
body: Thank you so much [@Max Lim _Adaptavist_](/t5/user/viewprofilepage/user-id/4065455)


author: Max Lim -Adaptavist-
body: (deleted duplicated answer.)


author: Robert Giddings [Adaptavist]
body: [@Ramya Yarru](/t5/user/viewprofilepage/user-id/3797301) ,

Thank you for your question.

Please can I confirm if you have ScriptRunner for Jira or ScriptRunner for Bitbucket?

Kind regards,

Robert Giddings,

Product Manager, ScriptRunner for Bitbucket

comments: author: Ramya Yarru
body: Hello [@Robert Giddings \[Adaptavist\]](/t5/user/viewprofilepage/user-id/1196283)

yes, i do have have scriptrunner for bitbucket and jira.

Thanks and Regards

Ramya


Tags: bitbucket-server

scriptrunner

server