jira-tirgger-gitlab

 jira 状态发生改变时触发GItlab进行创建分支、创建TAG


import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.issue.comments.CommentManager
import com.atlassian.jira.issue.CustomFieldManager;
import com.atlassian.jira.issue.fields.CustomField;
import com.atlassian.jira.issue.IssueInputParameters;
import com.atlassian.jira.issue.link.IssueLinkManager;


import com.atlassian.jira.event.issue.IssueEvent;
import com.atlassian.jira.user.ApplicationUser

import com.atlassian.jira.bc.issue.IssueService;
import com.atlassian.jira.bc.issue.IssueService.CreateValidationResult
import com.atlassian.jira.bc.issue.IssueService.UpdateValidationResult
import com.atlassian.jira.bc.issue.IssueService.IssueResult
import com.atlassian.jira.exception.CreateException;

import org.gitlab.api.GitlabAPI;
import org.gitlab.api.TokenType;
import org.gitlab.api.GitlabAPIException;
import org.gitlab.api.models.GitlabBranch;
import org.gitlab.api.models.GitlabProject;
import org.gitlab.api.models.GitlabTag;
import org.gitlab.api.models.GitlabCommit;

import java.util.Map;
import java.util.Set;
import java.net.URI;
import java.util.HashMap;
import java.text.SimpleDateFormat;
import java.util.Date;


IssueEvent issueEvent = event;
Issue issue = issueEvent.getIssue();
List<HashMap<String, Object>> fieldsModified = (List<HashMap<String, Object>>)event.getChangeLog()?.getRelated('ChildChangeItem');
CommentManager commentManager = ComponentAccessor.commentManager;
CustomFieldManager customFieldManager = ComponentAccessor.getCustomFieldManager();


// GitModule
CustomField GitModuleField = customFieldManager.getCustomFieldObject('customfield_10305');
String gitModule = GitModuleField.getValue(issue);

// ModuleType
CustomField ModuleTypeField = customFieldManager.getCustomFieldObject('customfield_10700');
String moduleType = ModuleTypeField.getValue(issue);



GitlabAPI getGitlabAPI(){
  String host = "http://git.localhost.com";
  String token = "58QBsXhNos9Fz_ciQpBd";
  GitlabAPI gitlabapi = GitlabAPI.connect(host, token,  TokenType.PRIVATE_TOKEN);
  return gitlabapi;
}

List<String> getNameSpace(String module){
  List<String> space = new ArrayList<String>();
  String projectName = '';
  String namespace = module;
  int split = module.lastIndexOf('/');
  if( split > -1){
    namespace = module.substring(0, split);
    projectName = module.substring(split+1);
  }
  space.add(namespace);
  space.add(projectName);
  return space;
}

def createBranch(String gitModule, String branchName, CommentManager commentManager){
  List<String> space = getNameSpace(gitModule);
  String namespace = space.get(0);
  String projectName = space.get(1);
  try{
    GitlabAPI gitlabAPI =  getGitlabAPI();
    GitlabProject gitlabProject = gitlabAPI.getProject(namespace, projectName);
    try{
      gitlabAPI.createBranch(gitlabProject, branchName, "master");
      try{
        GitlabBranch gitlabBranch = gitlabAPI.getBranch(gitlabProject, branchName);
        commentManager.create(event.issue, event.getUser(), "分支创建成功: [${gitlabBranch.getName()}|http://git.localhost.com/${gitModule}/tree/${gitlabBranch.getName()}]", true)
      }catch (FileNotFoundException e){
        commentManager.create(event.issue, event.getUser(), "分支创建失败: ${e.getMessage()}", true)
      }
    }catch (GitlabAPIException e){
      commentManager.create(event.issue, event.getUser(), "分支已经存在: ${e.getMessage()}", true)
    }
  } catch (IOException e){
    commentManager.create(event.issue, event.getUser(), "GIT初始化失败: ${e.getMessage()}", true)
  }
}

String createTag(String gitModule, String tagName, String branch, String message, String description, CommentManager commentManager){
  List<String> space = getNameSpace(gitModule);
  String namespace = space.get(0);
  String projectName = space.get(1);
  try{
    GitlabAPI gitlabAPI =  getGitlabAPI();
    GitlabProject gitlabProject = gitlabAPI.getProject(namespace, projectName);
    try{
      GitlabTag gitlabTag = gitlabAPI.addTag(gitlabProject, tagName, branch, message, description);
      GitlabCommit gitlabCommit = gitlabTag.getCommit();
      String commitId = gitlabCommit.getId();
      return commitId;
    }catch (GitlabAPIException e){
      commentManager.create(event.issue, event.getUser(), "TAG已经存在: ${e.getMessage()}", true)
    }
  } catch (IOException e){
    commentManager.create(event.issue, event.getUser(), "GIT初始化失败: ${e.getMessage()}", true)
  }
  return null;
}

void createIssueLink(IssueResult createResult){
  IssueLinkManager linkMgr = ComponentAccessor.getIssueLinkManager();
  try {
    // createIssueLink(Long sourceIssueId, Long destinationIssueId, Long issueLinkTypeId, Long sequence, ApplicationUser remoteUser)
    // sourceIssueId - The source issue.
    Long newIssueId = createResult.getIssue().getId();
    // destinationIssueId - The destination issue.
    Long destinationIssueId = event.getIssue().getId();
    // issueLinkTypeId - The type of issuelink http://127.0.0.1:8080/jira/rest/api/2/issueLinkType/10000
    Long issueLinkTypeId = 10000L;
    // sequence - In which order the link will appear in the UI
    Long sequence = 0L
    // remoteUser - Needed for creation of change items.
    log.error("createIssueLink :${newIssueId}, ${destinationIssueId}, ${issueLinkTypeId}, ${sequence}")
    linkMgr.createIssueLink(newIssueId, destinationIssueId, issueLinkTypeId, sequence, event.getUser());
  }catch (CreateException e){
    log.error("CreateException :{}", e.getMessage())
  }
}

void createIssue(String summary, String reporterId, String gitModule, String tagName, String commitId, String moduleType, ApplicationUser user){
  IssueService issueService = ComponentAccessor.getIssueService()
  IssueInputParameters issueInputParameters = issueService.newIssueInputParameters();
  
  issueInputParameters
    .setProjectId(10000L)
    .setIssueTypeId("10002") // issue type ID
    .setSummary(summary)
    .setAssigneeId(user.key)
    .setReporterId(user.key)
    .setPriorityId("3") // id of Priority
    // 模块名
    .addCustomFieldValue("customfield_10305", gitModule) // user picker field
    // tag 名
    .addCustomFieldValue("customfield_10306", tagName) // custom field with dropdown ID
    // commit id 
    .addCustomFieldValue("customfield_10307", commitId)
    // module type 
    .addCustomFieldValue("customfield_10700", moduleType)

  CreateValidationResult createValidationResult = issueService.validateCreate(event.getUser(), issueInputParameters);

  if (createValidationResult.isValid())
  {
    IssueResult createResult = issueService.create(user, createValidationResult);
    createIssueLink(createResult);
    log.error("Creation result?: {}", createResult.isValid().toString())
    
    if (!createResult.isValid()) {
      log.error("Something went wrong")
    }
  } else {
    log.error("cause :" + createValidationResult.getErrorCollection().getErrorMessages())
  }
}

for (HashMap<String, Object> field : fieldsModified){
  // 创建分支
  if(field['newvalue'] == '10105' && field['fieldtype'] == 'jira'){ // 创建分支
    SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
    String date = df.format(new Date());
    createBranch(gitModule, "Galaxy-" + issue.getKey() , commentManager)
    IssueService issueService = ComponentAccessor.getIssueService()
    IssueInputParameters issueInputParameters = issueService.newIssueInputParameters();
    issueInputParameters.addCustomFieldValue("customfield_10306", "Galaxy-" + issue.getKey());
    UpdateValidationResult updateValidationResult = issueService.validateUpdate(event.getUser(), issue.getId(), issueInputParameters)
    issueService.update(event.getUser(), updateValidationResult)
    
    commentManager.create(event.issue, event.getUser(), "创建分支: ${field}", true)
  }
  
  // 创建TAG
  if(field['newvalue'] == '10106' && field['fieldtype'] == 'jira'){ 

    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
    String date = df.format(new Date());

    String summary = issue.getSummary();
    String tagName = "v"+ date + '-' +issue.getKey();
    String message = summary;
    String branch = "Galaxy-" + issue.getKey();
    String description = "|  项目字段   | 字段值  | \n|  ----  | ----  |\n | tagName  | v${date}-${issue.getKey()} |\n | 关联ISSUE  | http://127.0.0.1:8080/jira/browse/${issue.getKey()} |\n | 分支  | Galaxy-${issue.getKey()} |\n| TAG概要  | ${issue.getSummary()} |\n| TAG描述  | ${issue.getDescription()} |\n| 时间  | ${date} |"

    String commitId = createTag(gitModule, tagName, branch, message, description , commentManager);

    if(commitId != null){
      commentManager.create(event.issue, event.getUser(), "创建TAG: ${field}", true)

      ApplicationUser user = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser()
      String reporterId = user.getId().toString();
      createIssue(summary, reporterId, gitModule, tagName, commitId, moduleType, user)
    }
  } 
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

从未、淡定

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值