Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

  • 스크립트 내용
    33번 줄 'repositoryPush': Scriptrunner rest Endpoint의 주소, {jira_url}/rest/scriptrunner/latest/custom/repositoryPush  
    64번 줄: Jira Issue에 댓글 남길 Id 입력
Code Block
languagegroovy
linenumberstrue
import com.onresolve.scriptrunner.runner.rest.common.CustomEndpointDelegate
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
import groovy.transform.BaseScript

import javax.ws.rs.core.MultivaluedMap
import javax.ws.rs.core.Response

import com.atlassian.jira.issue.Issue
import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.component.ComponentAccessor
import org.apache.log4j.Level
import org.apache.log4j.Logger

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 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 java.util.Date
import java.text.SimpleDateFormat

def log = Logger.getLogger("com.curvc")
log.setLevel(Level.DEBUG)

@BaseScript CustomEndpointDelegate delegate

repositoryPush(httpMethod: "POST") { MultivaluedMap queryParams, String body ->
    JsonSlurper slurper = new JsonSlurper()
    Map map = slurper.parseText(body)
    
    // 브랜치 생성이 아닌 경우 return
    if(map.changes.type.toString().equals("[ADD]")&&map.changes.ref.type.toString().equals("[BRANCH]")){
        log.info("Branch Created")
    } else {
        return
    }
    
    def issueManager = ComponentAccessor.getIssueManager()
    def userManager = ComponentAccessor.getUserManager()
    def commentManager = ComponentAccessor.getCommentManager()
    
    // 기본 정보들
    String projectKey = map.repository.project.key.toString()
    String repostiroySlug = map.repository.slug.toString()
    String repostiroyName = map.repository.name.toString()
    String tempBranchName = map.changes.ref.displayId.toString()
    String branchName = tempBranchName.substring(1, tempBranchName.size() - 1)
    String branchCreator = map.actor.displayName
    
    //날짜포맷
    String tempDate = map.date.toString().split('\\+')[0]
    Date date = Date.parse("yyyy-MM-dd'T'HH:MM:ss", tempDate)
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy년 MM월 dd일 HH시 MM분")
    String strDate = simpleDateFormat.format(date)
    log.info("저장소: " + projectKey + "/" + repostiroySlug + " 저장소명: " + repostiroyName + " Create Branch: " + branchName + " 만든이: " + branchCreator)

    // Jira issue에 댓글 남길 유저명
    String userName = "jk.park"
    def user = userManager.getUserByName(userName)
    //댓글 내용
    def message = """
    저장소명: ${repostiroyName}
    브랜치명: ${branchName}
    만든이: ${branchCreator}
    생성날짜: ${strDate} 
    """
    
    //연동된 bitbucket과 통신하여 해당되는 Jira Issue 가져오기
    def applicationLinkService = ComponentLocator.getComponent(ApplicationLinkService)
    final def bitbucketLink = applicationLinkService.getPrimaryApplicationLink(BitbucketApplicationType)
	ComponentAccessor.getJiraAuthenticationContext().setLoggedInUser(user)
    def authenticatedRequestFactory = bitbucketLink.createImpersonatingAuthenticatedRequestFactory()?: bitbucketLink.createAuthenticatedRequestFactory()
    authenticatedRequestFactory
        .createRequest(Request.MethodType.GET, "/rest/api/1.0/projects/MAV/repos/testtest/branches?filterText=" + branchName + "&details=true")
        .addHeader("Content-Type","application/json")
        .execute(new ResponseHandler<Response>(){
            @Override
            void handle(Response response) throws ResponseException{
                if(response.statusCode != HttpURLConnection.HTTP_OK){
                    throw new Exception(response.responseBodyAsString)
                } else{
                    responseBody = new JsonSlurper().parseText(response.responseBodyAsString)
                }
            }
        })
    
    log.info(responseBody)
    if(responseBody.size == 0){
        log.info("브랜치 조회에 실패했습니다.")
        return 
    }
    if(responseBody.values.metadata["com.atlassian.bitbucket.server.bitbucket-jira:branch-list-jira-issues"][0].key.size == 0){
        log.info("연동된 Jira Issue가 없습니다.")
        return 
    } else if(responseBody.values.metadata["com.atlassian.bitbucket.server.bitbucket-jira:branch-list-jira-issues"][0].key.size > 1){
        log.info("연동된 Jira Issue가 2개 이상입니다.")
        return   
    }
    String issueKey = responseBody.values.metadata["com.atlassian.bitbucket.server.bitbucket-jira:branch-list-jira-issues"][0].key[0]
	log.info("issue: " + issueKey)
    

    

    def issue = issueManager.getIssueByCurrentKey(issueKey)
    
    commentManager.create(issue, user, message, false)
    log.info("comment Add")
    
    return javax.ws.rs.core.Response.ok(new JsonBuilder([success:"comment Add"]).toString()).build();
}

...