首页 > 其他分享 >groovy 脚本实例 从git上创建feature分支

groovy 脚本实例 从git上创建feature分支

时间:2022-09-26 21:01:31浏览次数:48  
标签:groovy userName git feature branch branchFrom def

目录

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

标签:groovy,userName,git,feature,branch,branchFrom,def
From: https://www.cnblogs.com/liwenchao1995/p/16732449.html

相关文章

  • groovy 调整k8s的副本数定时任务
    目录groovy调整k8s的副本数定时任务groovy调整k8s的副本数定时任务packageplatformnode('ecs_wuhan_docker'){println"${BUILD_URL}console"defwxKey......
  • Gitee多分支提交被拒
    方法一首先gitlog查看commit记录,找到远端本地冲突之前的commitgitreset--soft[commitID]1、gitpulloriginmaster(根据你的分支变换)--allow-unrelated-his......
  • git常用命令
    切换远程分支需要先将远程分支与本地分支关联。gitcheckout-b本地分支名origin/远程分支名该命令可以将远程仓库里指定的分支拉取到本地,并在本地创建一个分支与指定......
  • 关于使用shutil.rmtree删除git文件夹时出现拒绝访问的问题
    简介在实际项目中发现,当使用shutil.rmtree删除整个git目录时会出现.git文件无法删除的情况,报错是拒绝访问,原因是默认情况下.git文件是只读的,无法直接对其进行操作。解决......
  • Git常用命令
    感觉VS2019自带的偶尔出现提交,拉取失败,还是命令解决1、回退到上次提交不清除本地提交的代码gitreset--softHEAD~12、回退到上次提交并清除本地提交的代码git rese......
  • gitlab 迁移
    场景:机房搬迁,gitlab迁移至腾讯云解决:1.在原服务器上使用命令生成备份包gitlab-rakegitlab:backup:create 备份命令,会在目录/data/gitlab/backups下生成1579054425_20......
  • GitEE常用命令集合
     以下代码运行前提:在gitee官网有自己的仓库(或者公司的代码仓库) 一、本地仓库初始化(即把当前文件夹(也称本地仓库)与远程仓库连接)gitinit二、设置全局用户名和邮......
  • Git 异常处理:SSH 端口 22 连接超时
    ssh:connecttohostgithub.comport22:Connectiontimedout鼠标右键>>GitBashHere进入.ssh文件夹cd~/.ssh创建一个config文件不会使用vim的可以直接......
  • Git:Github-SSH 配置(加密方式 Ecdsa)
    鼠标右键菜单>>GitBashHere配置用户名gitconfig–globaluser.name"用户名"配置电子邮箱gitconfig–globaluser.email"电子邮箱"以Ecdsa的方式生成SSH......
  • EF Core – 7.0 New Features
    前言这篇不会细谈功能,只是一个总链接. 参考Docs–What'sNewinEFCore7.0 BreakingChange我follow EFCore–搭建单侧环境 做了一遍,在运行 dotne......