脱离jenkins之groovy定制化自动化构建打包

脚本无什么多说的,需要注意的是构建后的归档操作请拖拽到groovy执行之后

修改:上个版本文件copy的时候忘记关闭流,导致后续操作部分返回false

现在版本增加了源文件删除,和权限修改为775,以及内部压缩使用tar.gz格式

import groovy.json.JsonSlurper
import org.apache.tools.ant.Project
import org.apache.tools.ant.taskdefs.Zip
import org.apache.tools.ant.types.FileSet
import java.text.SimpleDateFormat
import static java.util.regex.Pattern.matches


//json配置文件读取
static Object readjson(String f) {
    File jsonFile = new File( f )
    def jsonPaser = new JsonSlurper()
    def json = jsonPaser.parse( jsonFile )
    return json
}

//判断执行环境是windos还是linux
Boolean getSystem() {
    def name = System.getProperty( "os.name" )
    if (name.toUpperCase().contains( "win".toUpperCase() )) {
        //windows系统
        return Boolean.FALSE
    } else {
        //linux系统
        return Boolean.TRUE
    }
}

//本地调试
repo = "/home/mvn-builder" //仓库地址
third_repo = "/home/thirdprocess"
res_workspace = System.getProperty( "user.dir" )
manager.listener.logger.println( "res项目工作空间为:" + res_workspace)
workspace = "/home/soft/jenkins/workspace/Ci-item-test1"
manager.listener.logger.println( "项目工作空间为:" + workspace)
test_json = readjson( "$workspace/build.json" )
buildName = test_json["buildName"]
buildPlan = test_json["buildPlan"]  //构建详细计划
installName = test_json["installName"]//安装基础包
installVersion = test_json["installVersion"]//安装基础包版本
topDirName = buildName + "-" + new SimpleDateFormat( "yyyyMMdd_HHmmss" ).format( new Date() ) //构建名称
topDir = "$workspace/$topDirName"  //构建根目录的绝对路径
busiprocess = "$workspace/$topDirName/busiprocess" //应用根目录
busishell = "/home/busishell" //启动,停止等shell仓库
env = "/home/env" //env仓库

//测试环境
manager.listener.logger.println( "----------------------------------------------------------------------------" )
manager.listener.logger.println( "现在开始创建构建目录" )
manager.listener.logger.println( "仓库地址为:" + repo )
manager.listener.logger.println( "项目工作空间为:" + workspace )
manager.listener.logger.println( "构建名称为:" + buildName )
manager.listener.logger.println( "构建目录为:" + topDir )
manager.listener.logger.println( "----------------------------------------------------------------------------\n" )

//创建构建顶级目录
new File( topDir ).mkdirs()
new File( busiprocess ).mkdirs()

//文件复制方法
/*
    @desPath 目标绝对路径名称
    @srcPath 源绝对路径名称
 */

void runCopy(String desPath, String srcPath) {
    FileInputStream input = new FileInputStream( srcPath )
    File abspath = new File( desPath )
    def output = new FileOutputStream( abspath )
    byte[] buf = new byte[1024]
    def bytesRead
    while ((bytesRead = input.read( buf )) > 0) {
        output.write( buf, 0, bytesRead )
    }
    input.close(  )
    output.close(  )
}
//文件压缩
void ZipFile(String decPathName, String srcPathName) {
    File zipfile = new File( decPathName + '.zip' )
    File srcdir = new File( srcPathName )
    Project prj = new Project()
    Zip zip = new Zip()
    zip.setProject( prj )
    zip.setDestFile( zipfile )
    FileSet fileSet = new FileSet()
    fileSet.setProject( prj )
    fileSet.setDir( srcdir )
    zip.addFileset( fileSet )
    zip.execute()
}

//进行以process相关的文件复制并创建chdzlib文件夹
void processCopy(processName) {
    new File( "$busiprocess/$processName/$processName/thirdlib" ).mkdirs()
    new File( "$busiprocess/$processName/$processName/profiles" ).mkdirs()
    new File( "$busiprocess/$processName/$processName/chdzlib" ).mkdirs()
    new File( "$busiprocess/$processName/$processName/profiles/db.migration" ).mkdirs()
    new File( "$busiprocess/$processName/$processName/profiles/application.properties" ).createNewFile()
    new File( "$busiprocess/$processName/$processName/profiles/logback-spring.xml" ).createNewFile()
    new File( "$busiprocess/$processName/processInfo.properties" ).createNewFile()
}

//文件复制规则

/**
 * @name 组件名称
 * @version 组件版本
 * @thirdLibSet 第三方已拷贝jar包集合
 * @chdzSet 长虹电子已拷贝jar包集合
 */

thirdLibSet = new HashSet<String>()
thirdJarSet = new HashSet<String>()
chdzLibSet = new HashSet<String>()
chdzJarSet = new HashSet<String>()

//thirdlib获取规则
HashSet<String> thirdLibs(String component_name, String component_version) {
    File thirdLibDir = new File( "$repo/$component_name/$component_version/thirdlib" )
    thirdLibDir.eachFile() {
        if (matches( "chdz-.*jar", it.getName() )) {
            null
        } else {
            if (!thirdJarSet.contains( it.name )) {
                thirdJarSet.add( it.name )
                thirdLibSet.add( it )
            }
        }
    }
    return thirdLibSet
}

//chdzlib获取规则
HashSet<String> chdzLibs(String component_name, String component_version) {
    File chdzLibDir = new File( "$repo/$component_name/$component_version" )
    chdzLibDir.eachFile() { f ->
        if (matches( "chdz-.*jar", f.name )) {
            if (!chdzJarSet.contains( f.name )) {
                chdzLibSet.add( f.toString() )
                chdzJarSet.add( f.name )
            }
        }
    }
    chdzLibDir.eachDir { f ->
        f.eachFile() { x ->
            if (matches( "chdz-.*jar", x.name )) {
                if (!chdzJarSet.contains( x.name )) {
                    chdzLibSet.add( x.toString() )
                    chdzJarSet.add( x.name )
                }
            }
        }
        return chdzLibSet
    }
}

//application.properties文件追加规则
void applicationCopy(String component_name, String component_version, File appFile) {
    File app = new File( "$repo/$component_name/$component_version/profiles/application.properties" )
    app.eachLine { line ->
        if (!appFile.readLines().contains( line ) && !line.startsWith( "#" )) {
            manager.listener.logger.println( "\t新增application属性为:" + line )
            appFile.append( line + '\n' )
        }
    }

}

//processInfo.properties文件追加规则
void processInfoCopy(String component_name, String component_version, File appFile) {
    File app = new File( "$repo/$component_name/$component_version/profiles/processInfo.properties" )
    app.eachLine { line ->
        if (!appFile.readLines().contains( line ) && !line.startsWith( "#" )) {
            manager.listener.logger.println( "\t新增processInfo属性为:" + line )
            appFile.append( line + '\n' )
        }
    }

}

//logback-spring.xml文件追加规则
void logbackCopy(String component_name, String component_version, File logbackFile) {
    File logback = new File( "$repo/$component_name/$component_version/profiles/logback-spring.xml" )
    if (matches( ".*process", component_name )) {
        logback.eachLine { line ->
            logbackFile.append( line + "\n" )
        }
    } else {

        FileWriter writer = new FileWriter( logbackFile, true )
        StringBuilder tmpfile = new StringBuilder( "" )
        //删除最后一行内容
        logbackFile.eachLine {
            if (it != "</configuration>") {
                tmpfile.append( it + "\n" )
            }
        }
        logbackFile.write( tmpfile.toString() )
        logback.eachLine {
            writer.write( it.toString() + "\n" )
        }
        writer.write( "</configuration>" )
        writer.close()
    }
}

manager.listener.logger.println( "构建详细计划为:\n" )
File installProfile = new File( "$repo/$installName/$installVersion/profiles" )
File installJar = new File( "$repo/$installName/$installVersion" )
def ant = new AntBuilder()
//复制env
manager.listener.logger.println( "开始复制env" )
ant.copy( todir: "$workspace/$topDirName/env", overwrite: true ) {
    fileset( dir: "$env" ) {
    }
}
manager.listener.logger.println( "结束复制env" )
//复制install下的文件到顶级目录
manager.listener.logger.println( "开始install的profile下的文件复制" )
ant.copy( todir: "$workspace/$topDirName", overwrite: true ) {
    fileset( dir: installProfile ) {
    }
}
manager.listener.logger.println( "install的profile下的文件复制结束!" )
manager.listener.logger.println( "开始install-jar包复制" )
ant.copy( todir: "$workspace/$topDirName", overwrite: true ) {
    fileset( dir: installJar ) {
        include( name: "*.jar" )
    }
}
manager.listener.logger.println( "install-jar包复制结束!" )

buildPlan.each { it ->
    def processName = it["processName"]
    manager.listener.logger.println( "processName:" + it["processName"] )
    manager.listener.logger.println( "runMode:" + it["runMode"] )
    manager.listener.logger.println( "processVersion:" + it["processVersion"] )
    //busishell拷贝
    ant.copy( todir: "$busiprocess/$processName/$processName", overwrite: true ) {
        fileset( dir: "$busishell" ) {
            include( name: "*.sh" )
        }
    }
    thirdLibSet.clear()
    thirdJarSet.clear()
    chdzLibSet.clear()
    chdzJarSet.clear()
    //首先拷贝process下的文件
    processCopy( it["processName"] )
    thirdLibs( it["runMode"].toString(), it["processVersion"].toString() )
    chdzLibs( it["runMode"].toString(), it["processVersion"].toString() )
    File appFile = new File( "$busiprocess/$processName/$processName/profiles/application.properties" )
    manager.listener.logger.println( "\t现在进行application.properties文件合并:" )
    applicationCopy( it["runMode"].toString(), it["processVersion"].toString(), appFile )
    manager.listener.logger.println( "\t现在进行logback-spring.xml文件合并:" )
    File logbackFile = new File( "$busiprocess/$processName/$processName/profiles/logback-spring.xml" )
    logbackCopy( it["runMode"].toString(), it["processVersion"].toString(), logbackFile )
    File processInfoFile = new File( "$busiprocess/$processName/processInfo.properties" )
    manager.listener.logger.println( "\t现在进行processInfo.properties文件合并:" )
    processInfoCopy( it["runMode"].toString(), it["processVersion"].toString(), processInfoFile )

    manager.listener.logger.println( "business:[" )
    it["business"].each {
        manager.listener.logger.println( "\t{" )
        manager.listener.logger.println( "\t组件名称:" + it["name"] )
        thirdLibs( it["name"].toString(), it["version"].toString() )
        chdzLibs( it["name"].toString(), it["version"].toString() )
       try{
        applicationCopy( it["name"].toString(), it["version"].toString(), appFile )
        }
       catch (Exception e) {
            manager.listener.logger.println( "$it['name']-$it['version']" + "没有application.properties文件" )
        }
        logbackCopy( it["name"].toString(), it["version"].toString(), logbackFile )
        try {
            processInfoCopy( it["name"].toString(), it["version"].toString(), processInfoFile )
        }
        catch (Exception e) {
            manager.listener.logger.println( "$it['name']-$it['version']" + "没有processInfo.properties文件" )
        }
        manager.listener.logger.println( it['name'] )
        manager.listener.logger.println( "开始复制db.migration" )
        try {
            File db = new File( "$repo" + '/' + it['name'] + '/' + it['version'] + '/profiles/db.migration' )
            db.eachFile { p ->
                manager.listener.logger.println( p )
                manager.listener.logger.println( "正在复制:" + p.name )
                runCopy( "$busiprocess/$processName/$processName/profiles/db.migration/$p.name", "$p" )
            }
        }
        catch (Exception e) {
            manager.listener.logger.println( " db.migration文件夹下没有sql文件可以复制!" )
        }
        manager.listener.logger.println( "\t组件版本:" + it["version"] )
        manager.listener.logger.println( "\t}" )
    }
    manager.listener.logger.println( '\n' )
    manager.listener.logger.println( "现在进行第三方jar包的拷贝工作:" )

    thirdLibSet.each {
        manager.listener.logger.println( "正在拷贝的第三方jar包:" + it.toString().split( "/" )[-1] )
        runCopy( busiprocess + "/" + processName + "/" + processName + "/" + "thirdlib" + "/" + it.toString().split( "/" )[-1], it.toString() )
    }

    manager.listener.logger.println( '\n' )
    manager.listener.logger.println( "现在进行chdz-jar包的拷贝工作:" )

    chdzLibSet.each {
        //首先我们需要创建文件目录,保证拷贝路径存在
        //测试环境
        manager.listener.logger.println( "正在拷贝的chdz-jar包:" + it.toString().split( "/" )[-1] )
        if (matches( ".*process.*", it.toString().split( "/" )[-1] )) {
            runCopy( busiprocess + "/" + processName + "/" + processName + "/" + it.toString().split( "/" )[-1], it.toString() )
        } else {
            runCopy( busiprocess + "/" + processName + "/" + processName + "/" + "chdzlib" + "/" + it.toString().split( "/" )[-1], it.toString() )
        }

    }
    manager.listener.logger.println( '\n' )
}

//进行
def application = new File( "$busiprocess" )
application.eachDir() { d ->
    if (getSystem()) {
        ant.tar( basedir: d.toString(), destfile: "$d/${d.toString().split( '/' )[-1]}.tar" )
        ant.gzip( zipfile: "$d/${d.toString().split( '/' )[-1]}.tar.gz", src: "$d/${d.toString().split( '/' )[-1]}.tar" )
        manager.listener.logger.print("压缩为tar.gz格式完成,删除源文件:")
        manager.listener.logger.println( "$d/${d.toString().split( '/' )[-1]}" )
        ant.delete( dir: "$d/${d.toString().split( '/' )[-1]}", includeemptydirs: "true" )
        ant.delete {
            fileset( dir: d.toString(), includes: "**/*.tar" )
        }
    } else {
        ant.tar( basedir: d.toString(), destfile: "$d/${d.toString().split( '\\\\' )[-1]}.tar" )
        ant.gzip( zipfile: "$d/${d.toString().split( '\\\\' )[-1]}.tar.gz", src: "$d/${d.toString().split( '\\\\' )[-1]}.tar" )
        manager.listener.logger.print("压缩为tar.gz格式完成,删除源文件:")
        manager.listener.logger.println( "$d/${d.toString().split( '\\\\' )[-1]}" )
        ant.delete {
            fileset( dir: d.toString(), includes: "**/*.tar" )
        }
    }
}

//第三方依赖拷贝

manager.listener.logger.println( "现在进行第三方中间件拷贝!" )
envSystem = test_json['envSystem']
thirdprocess = test_json['thirdprocess']
thirdSystemPath = "$third_repo/$envSystem"
thirdprocess.eachWithIndex { p, index ->
    def name = p['name']
    def version = p['version']
    (++index)
    new File( "$workspace/$topDirName/thirdprocess/step$index-$name" ).mkdirs()
    def ToolDir = new File( "$thirdSystemPath/$name/$name-$version/" )
    manager.listener.logger.println( "现在拷贝的是" + "$name-$version" )
    ToolDir.eachFile { f ->
        def fName = f.name
        runCopy( "$workspace/$topDirName/thirdprocess/step$index-$name/$fName", f.toString() )
    }
}

//修改文件权限
manager.listener.logger.print( "现在进行文件权限批量修改:" )
manager.listener.logger.println( "$workspace/$topDirName" )
def command = """chmod 775 -R $workspace/$topDirName"""
def proc = command.execute()               
proc.waitFor()
manager.listener.logger.println( "文件权限批量修改完成!" )

manager.listener.logger.println( "第三方中间件拷贝完毕!" )
manager.listener.logger.println( "现在开始进行压缩打包工作!" )
ZipFile( "$workspace/$topDirName", "$workspace/$topDirName" )
manager.listener.logger.println( "打包完成,请进入工作区进行相关下载!" )
manager.addShortText(topDirName)

相关config.xml文件如下,供大家参考

<?xml version='1.1' encoding='UTF-8'?>
<project>
  <actions/>
  <description></description>
  <keepDependencies>false</keepDependencies>
  <properties>
    <hudson.plugins.jira.JiraProjectProperty plugin="jira@3.0.10"/>
    <jenkins.model.BuildDiscarderProperty>
      <strategy class="hudson.tasks.LogRotator">
        <daysToKeep>-1</daysToKeep>
        <numToKeep>50</numToKeep>
        <artifactDaysToKeep>-1</artifactDaysToKeep>
        <artifactNumToKeep>-1</artifactNumToKeep>
      </strategy>
    </jenkins.model.BuildDiscarderProperty>
    <com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty plugin="gitlab-plugin@1.5.12">
      <gitLabConnection></gitLabConnection>
    </com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty>
    <hudson.model.ParametersDefinitionProperty>
      <parameterDefinitions>
        <hudson.model.FileParameterDefinition>
          <name>build.json</name>
          <description>构建计划文件</description>
        </hudson.model.FileParameterDefinition>
      </parameterDefinitions>
    </hudson.model.ParametersDefinitionProperty>
  </properties>
  <scm class="hudson.scm.NullSCM"/>
  <canRoam>true</canRoam>
  <disabled>false</disabled>
  <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
  <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
  <triggers/>
  <concurrentBuild>false</concurrentBuild>
  <builders>
    <hudson.tasks.Shell>
      <command>chmod -R 755 /home/busishell /home/mvn-builder /home/thirdprocess /home/env</command>
    </hudson.tasks.Shell>
  </builders>
  <publishers>
    <org.jvnet.hudson.plugins.groovypostbuild.GroovyPostbuildRecorder plugin="groovy-postbuild@2.5">
      <script plugin="script-security@1.61">
        <script>import groovy.json.JsonSlurper
import org.apache.tools.ant.Project
import org.apache.tools.ant.taskdefs.Zip
import org.apache.tools.ant.types.FileSet
import java.text.SimpleDateFormat
import static java.util.regex.Pattern.matches


//json配置文件读取
static Object readjson(String f) {
    File jsonFile = new File( f )
    def jsonPaser = new JsonSlurper()
    def json = jsonPaser.parse( jsonFile )
    return json
}

//判断执行环境是windos还是linux
Boolean getSystem() {
    def name = System.getProperty( &quot;os.name&quot; )
    if (name.toUpperCase().contains( &quot;win&quot;.toUpperCase() )) {
        //windows系统
        return Boolean.FALSE
    } else {
        //linux系统
        return Boolean.TRUE
    }
}

//本地调试
repo = &quot;/home/mvn-builder&quot; //仓库地址
third_repo = &quot;/home/thirdprocess&quot;
res_workspace = System.getProperty( &quot;user.dir&quot; )
manager.listener.logger.println( &quot;res项目工作空间为:&quot; + res_workspace)
workspace = &quot;/home/soft/jenkins/workspace/Ci-item-test1&quot;
manager.listener.logger.println( &quot;项目工作空间为:&quot; + workspace)
test_json = readjson( &quot;$workspace/build.json&quot; )
buildName = test_json[&quot;buildName&quot;]
buildPlan = test_json[&quot;buildPlan&quot;]  //构建详细计划
installName = test_json[&quot;installName&quot;]//安装基础包
installVersion = test_json[&quot;installVersion&quot;]//安装基础包版本
topDirName = buildName + &quot;-&quot; + new SimpleDateFormat( &quot;yyyyMMdd_HHmmss&quot; ).format( new Date() ) //构建名称
topDir = &quot;$workspace/$topDirName&quot;  //构建根目录的绝对路径
busiprocess = &quot;$workspace/$topDirName/busiprocess&quot; //应用根目录
busishell = &quot;/home/busishell&quot; //启动,停止等shell仓库
env = &quot;/home/env&quot; //env仓库

//测试环境
manager.listener.logger.println( &quot;----------------------------------------------------------------------------&quot; )
manager.listener.logger.println( &quot;现在开始创建构建目录&quot; )
manager.listener.logger.println( &quot;仓库地址为:&quot; + repo )
manager.listener.logger.println( &quot;项目工作空间为:&quot; + workspace )
manager.listener.logger.println( &quot;构建名称为:&quot; + buildName )
manager.listener.logger.println( &quot;构建目录为:&quot; + topDir )
manager.listener.logger.println( &quot;----------------------------------------------------------------------------\n&quot; )

//创建构建顶级目录
new File( topDir ).mkdirs()
new File( busiprocess ).mkdirs()

//文件复制方法
/*
    @desPath 目标绝对路径名称
    @srcPath 源绝对路径名称
 */

void runCopy(String desPath, String srcPath) {
    FileInputStream input = new FileInputStream( srcPath )
    File abspath = new File( desPath )
    def output = new FileOutputStream( abspath )
    byte[] buf = new byte[1024]
    def bytesRead
    while ((bytesRead = input.read( buf )) &gt; 0) {
        output.write( buf, 0, bytesRead )
    }
    input.close(  )
    output.close(  )
}
//文件压缩
void ZipFile(String decPathName, String srcPathName) {
    File zipfile = new File( decPathName + &apos;.zip&apos; )
    File srcdir = new File( srcPathName )
    Project prj = new Project()
    Zip zip = new Zip()
    zip.setProject( prj )
    zip.setDestFile( zipfile )
    FileSet fileSet = new FileSet()
    fileSet.setProject( prj )
    fileSet.setDir( srcdir )
    zip.addFileset( fileSet )
    zip.execute()
}

//进行以process相关的文件复制并创建chdzlib文件夹
void processCopy(processName) {
    new File( &quot;$busiprocess/$processName/$processName/thirdlib&quot; ).mkdirs()
    new File( &quot;$busiprocess/$processName/$processName/profiles&quot; ).mkdirs()
    new File( &quot;$busiprocess/$processName/$processName/chdzlib&quot; ).mkdirs()
    new File( &quot;$busiprocess/$processName/$processName/profiles/db.migration&quot; ).mkdirs()
    new File( &quot;$busiprocess/$processName/$processName/profiles/application.properties&quot; ).createNewFile()
    new File( &quot;$busiprocess/$processName/$processName/profiles/logback-spring.xml&quot; ).createNewFile()
    new File( &quot;$busiprocess/$processName/processInfo.properties&quot; ).createNewFile()
}

//文件复制规则

/**
 * @name 组件名称
 * @version 组件版本
 * @thirdLibSet 第三方已拷贝jar包集合
 * @chdzSet 长虹电子已拷贝jar包集合
 */

thirdLibSet = new HashSet&lt;String&gt;()
thirdJarSet = new HashSet&lt;String&gt;()
chdzLibSet = new HashSet&lt;String&gt;()
chdzJarSet = new HashSet&lt;String&gt;()

//thirdlib获取规则
HashSet&lt;String&gt; thirdLibs(String component_name, String component_version) {
    File thirdLibDir = new File( &quot;$repo/$component_name/$component_version/thirdlib&quot; )
    thirdLibDir.eachFile() {
        if (matches( &quot;chdz-.*jar&quot;, it.getName() )) {
            null
        } else {
            if (!thirdJarSet.contains( it.name )) {
                thirdJarSet.add( it.name )
                thirdLibSet.add( it )
            }
        }
    }
    return thirdLibSet
}

//chdzlib获取规则
HashSet&lt;String&gt; chdzLibs(String component_name, String component_version) {
    File chdzLibDir = new File( &quot;$repo/$component_name/$component_version&quot; )
    chdzLibDir.eachFile() { f -&gt;
        if (matches( &quot;chdz-.*jar&quot;, f.name )) {
            if (!chdzJarSet.contains( f.name )) {
                chdzLibSet.add( f.toString() )
                chdzJarSet.add( f.name )
            }
        }
    }
    chdzLibDir.eachDir { f -&gt;
        f.eachFile() { x -&gt;
            if (matches( &quot;chdz-.*jar&quot;, x.name )) {
                if (!chdzJarSet.contains( x.name )) {
                    chdzLibSet.add( x.toString() )
                    chdzJarSet.add( x.name )
                }
            }
        }
        return chdzLibSet
    }
}

//application.properties文件追加规则
void applicationCopy(String component_name, String component_version, File appFile) {
    File app = new File( &quot;$repo/$component_name/$component_version/profiles/application.properties&quot; )
    app.eachLine { line -&gt;
        if (!appFile.readLines().contains( line ) &amp;&amp; !line.startsWith( &quot;#&quot; )) {
            manager.listener.logger.println( &quot;\t新增application属性为:&quot; + line )
            appFile.append( line + &apos;\n&apos; )
        }
    }

}

//processInfo.properties文件追加规则
void processInfoCopy(String component_name, String component_version, File appFile) {
    File app = new File( &quot;$repo/$component_name/$component_version/profiles/processInfo.properties&quot; )
    app.eachLine { line -&gt;
        if (!appFile.readLines().contains( line ) &amp;&amp; !line.startsWith( &quot;#&quot; )) {
            manager.listener.logger.println( &quot;\t新增processInfo属性为:&quot; + line )
            appFile.append( line + &apos;\n&apos; )
        }
    }

}

//logback-spring.xml文件追加规则
void logbackCopy(String component_name, String component_version, File logbackFile) {
    File logback = new File( &quot;$repo/$component_name/$component_version/profiles/logback-spring.xml&quot; )
    if (matches( &quot;.*process&quot;, component_name )) {
        logback.eachLine { line -&gt;
            logbackFile.append( line + &quot;\n&quot; )
        }
    } else {

        FileWriter writer = new FileWriter( logbackFile, true )
        StringBuilder tmpfile = new StringBuilder( &quot;&quot; )
        //删除最后一行内容
        logbackFile.eachLine {
            if (it != &quot;&lt;/configuration&gt;&quot;) {
                tmpfile.append( it + &quot;\n&quot; )
            }
        }
        logbackFile.write( tmpfile.toString() )
        logback.eachLine {
            writer.write( it.toString() + &quot;\n&quot; )
        }
        writer.write( &quot;&lt;/configuration&gt;&quot; )
        writer.close()
    }
}

manager.listener.logger.println( &quot;构建详细计划为:\n&quot; )
File installProfile = new File( &quot;$repo/$installName/$installVersion/profiles&quot; )
File installJar = new File( &quot;$repo/$installName/$installVersion&quot; )
def ant = new AntBuilder()
//复制env
manager.listener.logger.println( &quot;开始复制env&quot; )
ant.copy( todir: &quot;$workspace/$topDirName/env&quot;, overwrite: true ) {
    fileset( dir: &quot;$env&quot; ) {
    }
}
manager.listener.logger.println( &quot;结束复制env&quot; )
//复制install下的文件到顶级目录
manager.listener.logger.println( &quot;开始install的profile下的文件复制&quot; )
ant.copy( todir: &quot;$workspace/$topDirName&quot;, overwrite: true ) {
    fileset( dir: installProfile ) {
    }
}
manager.listener.logger.println( &quot;install的profile下的文件复制结束!&quot; )
manager.listener.logger.println( &quot;开始install-jar包复制&quot; )
ant.copy( todir: &quot;$workspace/$topDirName&quot;, overwrite: true ) {
    fileset( dir: installJar ) {
        include( name: &quot;*.jar&quot; )
    }
}
manager.listener.logger.println( &quot;install-jar包复制结束!&quot; )

buildPlan.each { it -&gt;
    def processName = it[&quot;processName&quot;]
    manager.listener.logger.println( &quot;processName:&quot; + it[&quot;processName&quot;] )
    manager.listener.logger.println( &quot;runMode:&quot; + it[&quot;runMode&quot;] )
    manager.listener.logger.println( &quot;processVersion:&quot; + it[&quot;processVersion&quot;] )
    //busishell拷贝
    ant.copy( todir: &quot;$busiprocess/$processName/$processName&quot;, overwrite: true ) {
        fileset( dir: &quot;$busishell&quot; ) {
            include( name: &quot;*.sh&quot; )
        }
    }
    thirdLibSet.clear()
    thirdJarSet.clear()
    chdzLibSet.clear()
    chdzJarSet.clear()
    //首先拷贝process下的文件
    processCopy( it[&quot;processName&quot;] )
    thirdLibs( it[&quot;runMode&quot;].toString(), it[&quot;processVersion&quot;].toString() )
    chdzLibs( it[&quot;runMode&quot;].toString(), it[&quot;processVersion&quot;].toString() )
    File appFile = new File( &quot;$busiprocess/$processName/$processName/profiles/application.properties&quot; )
    manager.listener.logger.println( &quot;\t现在进行application.properties文件合并:&quot; )
    applicationCopy( it[&quot;runMode&quot;].toString(), it[&quot;processVersion&quot;].toString(), appFile )
    manager.listener.logger.println( &quot;\t现在进行logback-spring.xml文件合并:&quot; )
    File logbackFile = new File( &quot;$busiprocess/$processName/$processName/profiles/logback-spring.xml&quot; )
    logbackCopy( it[&quot;runMode&quot;].toString(), it[&quot;processVersion&quot;].toString(), logbackFile )
    File processInfoFile = new File( &quot;$busiprocess/$processName/processInfo.properties&quot; )
    manager.listener.logger.println( &quot;\t现在进行processInfo.properties文件合并:&quot; )
    processInfoCopy( it[&quot;runMode&quot;].toString(), it[&quot;processVersion&quot;].toString(), processInfoFile )

    manager.listener.logger.println( &quot;business:[&quot; )
    it[&quot;business&quot;].each {
        manager.listener.logger.println( &quot;\t{&quot; )
        manager.listener.logger.println( &quot;\t组件名称:&quot; + it[&quot;name&quot;] )
        thirdLibs( it[&quot;name&quot;].toString(), it[&quot;version&quot;].toString() )
        chdzLibs( it[&quot;name&quot;].toString(), it[&quot;version&quot;].toString() )
       try{
        applicationCopy( it[&quot;name&quot;].toString(), it[&quot;version&quot;].toString(), appFile )
        }
       catch (Exception e) {
            manager.listener.logger.println( &quot;$it[&apos;name&apos;]-$it[&apos;version&apos;]&quot; + &quot;没有application.properties文件&quot; )
        }
        logbackCopy( it[&quot;name&quot;].toString(), it[&quot;version&quot;].toString(), logbackFile )
        try {
            processInfoCopy( it[&quot;name&quot;].toString(), it[&quot;version&quot;].toString(), processInfoFile )
        }
        catch (Exception e) {
            manager.listener.logger.println( &quot;$it[&apos;name&apos;]-$it[&apos;version&apos;]&quot; + &quot;没有processInfo.properties文件&quot; )
        }
        manager.listener.logger.println( it[&apos;name&apos;] )
        manager.listener.logger.println( &quot;开始复制db.migration&quot; )
        try {
            File db = new File( &quot;$repo&quot; + &apos;/&apos; + it[&apos;name&apos;] + &apos;/&apos; + it[&apos;version&apos;] + &apos;/profiles/db.migration&apos; )
            db.eachFile { p -&gt;
                manager.listener.logger.println( p )
                manager.listener.logger.println( &quot;正在复制:&quot; + p.name )
                runCopy( &quot;$busiprocess/$processName/$processName/profiles/db.migration/$p.name&quot;, &quot;$p&quot; )
            }
        }
        catch (Exception e) {
            manager.listener.logger.println( &quot; db.migration文件夹下没有sql文件可以复制!&quot; )
        }
        manager.listener.logger.println( &quot;\t组件版本:&quot; + it[&quot;version&quot;] )
        manager.listener.logger.println( &quot;\t}&quot; )
    }
    manager.listener.logger.println( &apos;\n&apos; )
    manager.listener.logger.println( &quot;现在进行第三方jar包的拷贝工作:&quot; )

    thirdLibSet.each {
        manager.listener.logger.println( &quot;正在拷贝的第三方jar包:&quot; + it.toString().split( &quot;/&quot; )[-1] )
        runCopy( busiprocess + &quot;/&quot; + processName + &quot;/&quot; + processName + &quot;/&quot; + &quot;thirdlib&quot; + &quot;/&quot; + it.toString().split( &quot;/&quot; )[-1], it.toString() )
    }

    manager.listener.logger.println( &apos;\n&apos; )
    manager.listener.logger.println( &quot;现在进行chdz-jar包的拷贝工作:&quot; )

    chdzLibSet.each {
        //首先我们需要创建文件目录,保证拷贝路径存在
        //测试环境
        manager.listener.logger.println( &quot;正在拷贝的chdz-jar包:&quot; + it.toString().split( &quot;/&quot; )[-1] )
        if (matches( &quot;.*process.*&quot;, it.toString().split( &quot;/&quot; )[-1] )) {
            runCopy( busiprocess + &quot;/&quot; + processName + &quot;/&quot; + processName + &quot;/&quot; + it.toString().split( &quot;/&quot; )[-1], it.toString() )
        } else {
            runCopy( busiprocess + &quot;/&quot; + processName + &quot;/&quot; + processName + &quot;/&quot; + &quot;chdzlib&quot; + &quot;/&quot; + it.toString().split( &quot;/&quot; )[-1], it.toString() )
        }

    }
    manager.listener.logger.println( &apos;\n&apos; )
}

//进行
def application = new File( &quot;$busiprocess&quot; )
application.eachDir() { d -&gt;
    if (getSystem()) {
        ant.tar( basedir: d.toString(), destfile: &quot;$d/${d.toString().split( &apos;/&apos; )[-1]}.tar&quot; )
        ant.gzip( zipfile: &quot;$d/${d.toString().split( &apos;/&apos; )[-1]}.tar.gz&quot;, src: &quot;$d/${d.toString().split( &apos;/&apos; )[-1]}.tar&quot; )
        manager.listener.logger.print(&quot;压缩为tar.gz格式完成,删除源文件:&quot;)
        manager.listener.logger.println( &quot;$d/${d.toString().split( &apos;/&apos; )[-1]}&quot; )
        ant.delete( dir: &quot;$d/${d.toString().split( &apos;/&apos; )[-1]}&quot;, includeemptydirs: &quot;true&quot; )
        ant.delete {
            fileset( dir: d.toString(), includes: &quot;**/*.tar&quot; )
        }
    } else {
        ant.tar( basedir: d.toString(), destfile: &quot;$d/${d.toString().split( &apos;\\\\&apos; )[-1]}.tar&quot; )
        ant.gzip( zipfile: &quot;$d/${d.toString().split( &apos;\\\\&apos; )[-1]}.tar.gz&quot;, src: &quot;$d/${d.toString().split( &apos;\\\\&apos; )[-1]}.tar&quot; )
        manager.listener.logger.print(&quot;压缩为tar.gz格式完成,删除源文件:&quot;)
        manager.listener.logger.println( &quot;$d/${d.toString().split( &apos;\\\\&apos; )[-1]}&quot; )
        ant.delete {
            fileset( dir: d.toString(), includes: &quot;**/*.tar&quot; )
        }
    }
}

//第三方依赖拷贝

manager.listener.logger.println( &quot;现在进行第三方中间件拷贝!&quot; )
envSystem = test_json[&apos;envSystem&apos;]
thirdprocess = test_json[&apos;thirdprocess&apos;]
thirdSystemPath = &quot;$third_repo/$envSystem&quot;
thirdprocess.eachWithIndex { p, index -&gt;
    def name = p[&apos;name&apos;]
    def version = p[&apos;version&apos;]
    (++index)
    new File( &quot;$workspace/$topDirName/thirdprocess/step$index-$name&quot; ).mkdirs()
    def ToolDir = new File( &quot;$thirdSystemPath/$name/$name-$version/&quot; )
    manager.listener.logger.println( &quot;现在拷贝的是&quot; + &quot;$name-$version&quot; )
    ToolDir.eachFile { f -&gt;
        def fName = f.name
        runCopy( &quot;$workspace/$topDirName/thirdprocess/step$index-$name/$fName&quot;, f.toString() )
    }
}

//修改文件权限
manager.listener.logger.print( &quot;现在进行文件权限批量修改:&quot; )
manager.listener.logger.println( &quot;$workspace/$topDirName&quot; )
def command = &quot;&quot;&quot;chmod 775 -R $workspace/$topDirName&quot;&quot;&quot;
def proc = command.execute()               
proc.waitFor()
manager.listener.logger.println( &quot;文件权限批量修改完成!&quot; )

manager.listener.logger.println( &quot;第三方中间件拷贝完毕!&quot; )
manager.listener.logger.println( &quot;现在开始进行压缩打包工作!&quot; )
ZipFile( &quot;$workspace/$topDirName&quot;, &quot;$workspace/$topDirName&quot; )
manager.listener.logger.println( &quot;打包完成,请进入工作区进行相关下载!&quot; )
manager.addShortText(topDirName)</script>
        <sandbox>false</sandbox>
      </script>
      <behavior>2</behavior>
      <runForMatrixParent>false</runForMatrixParent>
    </org.jvnet.hudson.plugins.groovypostbuild.GroovyPostbuildRecorder>
    <hudson.tasks.ArtifactArchiver>
      <artifacts>*.zip</artifacts>
      <allowEmptyArchive>false</allowEmptyArchive>
      <onlyIfSuccessful>true</onlyIfSuccessful>
      <fingerprint>true</fingerprint>
      <defaultExcludes>true</defaultExcludes>
      <caseSensitive>true</caseSensitive>
    </hudson.tasks.ArtifactArchiver>
  </publishers>
  <buildWrappers>
    <hudson.plugins.ws__cleanup.PreBuildCleanup plugin="ws-cleanup@0.37">
      <deleteDirs>false</deleteDirs>
      <cleanupParameter></cleanupParameter>
      <externalDelete></externalDelete>
      <disableDeferredWipeout>false</disableDeferredWipeout>
    </hudson.plugins.ws__cleanup.PreBuildCleanup>
    <hudson.plugins.timestamper.TimestamperBuildWrapper plugin="timestamper@1.10"/>
  </buildWrappers>
</project>

 

标签