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)
}
}
}