groovy 脚本实例 从git上创建feature分支
从git上创建feature分支
//从git上创建feature分支
package common
node('ecs_wuhan_docker') {
/** 参数部分:
* 这部分是自己定义的参数,根据生产线不通,需要根据情况进行修改
*/
// 定义当前时间,根据时间创建分支
def dateStr = new Date().format('yyyyMMdd')
// 定义分支名
def featureName = "feature-${dateStr}-${ENVIRONMENT_BRANCH}"
/** 参数部分:
* 这部分是cicd平台参数数传入,一般不需要修改
*/
// 定义微信通知联系人手机号码
def proposerMobile = CURRENT_OPERATOR_MOBILE
// 定义,cicd的地址,cicd模板参数导入
def cicdServerUrl = CICD_SERVER_URL
// 定义branch,ENVIRONMENT_BRANCH是cicd模板参数传入,FeatureID,任意一段英文字符串或数字,如 1224。会生成 feature-${dateStr}-${ENVIRONMENT_BRANCH}这个分支
def branch = ENVIRONMENT_BRANCH
// 定义userName, 创建者的名字CURRENT_OPERATOR是cicd模板参数传入
def proposerName = CURRENT_OPERATOR
// 定义微信群通知的key,WX_KEY是cicd模板参数导入
def wxKey = WX_KEY
// 定义从哪个分支拉取分支,默认是dev
def branchFrom = BRANCH_FROM
// 定义Jobname,cicd模板参数导入
def jobName = JOB_NAME
// 定义buildNumber,BUILD_NUMBER是jenkins默认参数,cicd模板参数导入
def buildNumber = BUILD_NUMBER
try {
stage('check param') {
check_param(proposerName, branch)
deleteDir()
}
stage('create_branch_by_id feature') {
cloneAllProjectAll(branchFrom, proposerName)
createBranch(featureName, 'dev')
}
stage('java deploy') {
build()
}
stage('push feature') {
pushNewBranch(featureName)
deleteDir()
}
stage('wxNotice') {
wxNotice("'${proposerName}'申请构建分支: '${featureName}' 分支构建成功!相关开发可以使用", wxKey, proposerMobile)
}
}
catch (e) {
wxFailNotice(wxKey, proposerName, jobName, buildNumber, cicdServerUrl)
throw e
} finally {
deleteDir()
}
}
def wxFailNotice(wxKey, proposerName, jobName, buildNumber, cicdServerUrl) {
def text = "<font color=info>【${proposerName}申请</font>构建分支<font color=warning>构建失败</font>\\n >[查看控制台](${cicdServerUrl}'/pipeline/job/consolesHTML/'${jobName}'/'${buildNumber})"
sh """curl 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key='${wxKey}'' -H 'Content-Type: application/json' -d '{ "msgtype": "markdown", "markdown": { "content": "${text}", } }'"""
sh """curl 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key='${wxKey}'' -H 'Content-Type: application/json' -d '{ "msgtype": "text", "text": { "mentioned_mobile_list":["18201292571"] } }'"""
}
def wxNotice(msg, wxKey, proposerMobile) {
sh """
curl 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${wxKey}' \
-H 'Content-Type: application/json' \
-d '
{
"msgtype": "text",
"text": {
"content": "${msg}",
"mentioned_mobile_list":["${proposerMobile}"]
}
}'
"""
}
def check_param(userName, branch) {
if (userName == 'userName') {
throw new Exception('YourName 不能为空!')
}
if (branch == 'branch') {
throw new Exception('branch 不能为空!')
}
}
def cloneAllProjectAll(branchFrom, userName) {
parallel(
"java": {
cloneJavaPlatformProject(branchFrom, userName)
},
"web": {
cloneWebPlatformProject(branchFrom, userName)
},
)
}
def cloneJavaPlatformProject(branchFrom, userName) {
stage('clone Java') {
cloneProjectBranch(['ynbase', 'inf', 'ecs2', 'ynmicro'], 'ecs-platform', branchFrom, userName)
}
}
def cloneWebPlatformProject(branchFrom, userName) {
stage('clone Web') {
parallel(
"ecs-web2": {
cloneProjectBranch(['ecs-web2'], 'ecs-platform', branchFrom, userName)
},
"ecs-console": {
cloneProjectBranch(['ecs_console'], 'ecs-platform', branchFrom, userName)
},
"yn_p1_designer": {
cloneProjectBranch(['yn_p1_designer'], 'p1', branchFrom, userName)
},
)
}
}
def isHasFeature(featureName) {
String featureCount = sh(returnStdout: true, script: "git ls-remote --heads |grep ${featureName}\$ | wc -l").trim()
return Integer.parseInt(featureCount) > 0
}
def cloneProjectBranch(projectNames, group, branch, userName) {
withCredentials([usernamePassword(credentialsId: 'ecs_git', usernameVariable: 'USER', passwordVariable: 'PASS')]) {
def encodedPass = URLEncoder.encode(PASS, "UTF-8")
try{
sh 'git config --global http.sslVerify false'
}catch (e) {
}
Map parallelMap = [:]
for (item in projectNames) {
def projectName = item
parallelMap.put(projectName, {
sh "git clone https://${USER}:${encodedPass}@192.168.48.50/${group}/${projectName}.git ${projectName}"
dir(projectName) {
sh "git config user.email ${userName}@yuanian.com"
sh "git config user.name ${userName}"
if (isHasFeature(branch)) {
sh "git checkout ${branch}"
}
}
})
}
parallel(parallelMap)
}
}
def createBranch(branchName, sourceBranch) {
fixJavaPomVersion("ECS2-${branchName}-SNAPSHOT", sourceBranch)
stage('create_branch_by_id Branch') {
Map parallelMap = [:]
for (item in getAllProjects()) {
def projectName = item
parallelMap.put(projectName, {
dir(projectName) {
sh "git checkout -b ${branchName}"
}
})
}
parallel(parallelMap)
}
}
def getJavaProjects() {
return ['ynbase', 'inf', 'ecs2', 'ynmicro']
}
def fixJavaPomVersion(version, sourceBranch) {
stage('fix Pom') {
for (item in getJavaProjects()) {
dir(item) {
if (isHasFeature(sourceBranch)) {
sh "find ./ -name pom.xml -exec sed -i 's/>.*-SNAPSHOT</>${version}</g' {} \\;"
sh "git commit -a -m 修改pom版本号 --allow-empty"
}
}
}
}
}
def build() {
stage('build java') {
def baseBuild = ['ynbase/mbase', 'ynbase/mbase-micro', 'inf/com.yuanian.infrastructure', 'ecs2/ecs']
mavenBuildProject(baseBuild, 'package install deploy')
}
}
def mavenBuildProject(paths = [], mavenCmd) {
if (paths == null || paths.size() == 0) {
return
}
sh 'mkdir -p /tmp/.m2/repository'
withDockerContainer(args: "-v /tmp/.m2/repository:/tmp/.m2/repository:rw,z", image: 'maven:3.6.3-openjdk-8') {
configFileProvider([configFile(fileId: 'maven-setting2', variable: 'MAVEN_SETTINGS')]) {
for (path in paths) {
if (fileExists("${path}/pom.xml")) {
dir(path) {
sh "mvn -s $MAVEN_SETTINGS ${mavenCmd} -Dmaven.test.skip=true"
}
}
}
}
}
}
def getAllProjects() {
return ['ynbase', 'inf', 'ecs2', 'ynmicro', 'ecs-web2', 'yn_p1_designer', 'ecs_console']
}
def pushNewBranch(featureName) {
stage('push New Branch') {
Map parallelMap = [:]
for (item in getAllProjects()) {
def projectName = item
parallelMap.put(projectName, {
dir(projectName) {
sh "git push --progress origin ${featureName}"
}
})
}
parallel(parallelMap)
}
}