脫離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="[email protected]"/>
    <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="[email protected]">
      <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="[email protected]">
      <script plugin="[email protected]">
        <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="[email protected]">
      <deleteDirs>false</deleteDirs>
      <cleanupParameter></cleanupParameter>
      <externalDelete></externalDelete>
      <disableDeferredWipeout>false</disableDeferredWipeout>
    </hudson.plugins.ws__cleanup.PreBuildCleanup>
    <hudson.plugins.timestamper.TimestamperBuildWrapper plugin="[email protected]"/>
  </buildWrappers>
</project>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章