How to use if else condition in Gradle

为君一笑 提交于 2019-12-10 13:52:10

问题


Can someone tell me how could I write the if else condition in the gradle script I mean i have two different types of zip files one is LiceseGenerator-4.0.0.58 and other one is CLI-4.0.0.60.My deployment script is working fine but I am using the shell script to do this and I want everything in gradle instead of doing it in the shell script.I want when I am deploying the LicenseGenerator it should deploy in differnet way and if it is CLI then it should deploy in other way.Currently deployall task is doing everyting.If I put if else condition how could I call the task.Please let me know if need any other information

Below is my script

// ------ Tell the script to get dependencies from artifactory ------
buildscript {
    repositories {
      maven {
        url "http://ct.ts.th.com:8/artifactory/libs-snapshot"
         }
    }

    // ------ Tell the script to get dependencies from artifactory ------
    dependencies {
    classpath ([ "com.trn.cm:cmplugin:1.1.118" ])
  }
}

apply plugin: 'com.trn.cm.cmgplugin'

/**
 * The folloing -D parameters are required to run this task
 *  - deployLayer = one of acceptance, latest, production, test
 */
//------------------------------------------------------------------------------------------
// Read the properties file and take the value as per the enviornment.
// 
//------------------------------------------------------------------------------------------
if(!System.properties.deployLayer) throw new Exception ("deployLayer must be set")
def thePropFile = file("config/${System.properties.deployLayer}.properties")
if(!thePropFile.exists()) throw new Exception("Cannot load the specified environment properties from ${thePropFile}")
println "Deploying ${System.properties.jobName}.${System.properties.buildNumber} to ${System.properties.deployLayer}"

// load the deploy properties from the file
def deployProperties = new Properties()
thePropFile.withInputStream { 
    stream -> deployProperties.load(stream) 
} 
// set them in the build environment
project.ext {
  deployProps = deployProperties
  deployRoot = deployProperties["${System.properties.jobName}.deployroot"]
  deployFolder = deployProperties["${System.properties.jobName}.foldername"]
  deployPostInstallSteps = deployProperties["${System.properties.jobName}.postInstallSteps"]
}

task deleteGraphicsAssets(type: Delete, dependsOn: deploy) {
    def dirName = "${deployRoot}"
    delete dirName

    doLast {
        file(dirName).mkdirs()
    }
}


task myCustomTask(dependsOn: deleteGraphicsAssets) << {
    copy {
        from 'deploymentfiles'
        into "${deployRoot}"
    }
}

task cleanTempDir(type: Delete, dependsOn: myCustomTask) {
      delete fileTree(dir: "build/artifacts", exclude: "*.zip")
  }

task unzipArtifact(dependsOn: cleanTempDir) << {
  file("${buildDir}/artifacts").eachFile() { 
    println "Deploying ${it}"
   // ant.mkdir(dir: "${deployRoot}/${deployFolder}")
    ant.unzip(src: it, dest: "${deployRoot}")
  }
}

task setPerms( type: Exec, dependsOn: unzipArtifact) {
  workingDir "${deployRoot}"
  executable "bash"
  args "-c", "dos2unix analyticsEngine.sh"
  args "-c", "chmod u+x analyticsEngine.sh && ./analyticsEngine.sh"
 }

 task deployAll(dependsOn: setPerms){}

回答1:


I used in below way it is working fine

  // ------ Tell the script to get dependencies from artifactory ------
    buildscript {
        repositories {
          maven {
            url "http://c.t.th.com:8/artifactory/libs-snapshot"
             }
        }

        // ------ Tell the script to get dependencies from artifactory ------
        dependencies {
        classpath ([ "c.t.c:cmgin:1.1.118" ])
      }
    }

    apply plugin: 'com.t.c.cmlugin'

    /**
     * The folloing -D parameters are required to run this task
     *  - deployLayer = one of acceptance, latest, production, test
     */
    //------------------------------------------------------------------------------------------
    // Read the properties file and take the value as per the enviornment.
    // 
    //------------------------------------------------------------------------------------------
    if(!System.properties.deployLayer) throw new Exception ("deployLayer must be set")
    def thePropFile = file("config/${System.properties.deployLayer}.properties")
    if(!thePropFile.exists()) throw new Exception("Cannot load the specified environment properties from ${thePropFile}")
    println "Deploying ${System.properties.jobName}.${System.properties.buildNumber} to ${System.properties.deployLayer}"

    // load the deploy properties from the file
    def deployProperties = new Properties()
    thePropFile.withInputStream { 
        stream -> deployProperties.load(stream) 
    } 
    // set them in the build environment
    project.ext {
      deployProps = deployProperties
      deployRoot = deployProperties["${System.properties.jobName}.deployroot"]
      deploydir = deployProperties["${System.properties.jobName}.deploydir"]
      deployFolder = deployProperties["${System.properties.jobName}.foldername"]
      deployPostInstallSteps = deployProperties["${System.properties.jobName}.postInstallSteps"]
    }

    task deleteGraphicsAssets(type: Delete, dependsOn: deploy) {
        def dirName = "${deployRoot}"
        delete dirName

        doLast {
            file(dirName).mkdirs()
        }
    }

    task copyartifactZip << {
        copy {
            from "${deployRoot}"
            into "${deploydir}/"
        }
    }

    task copyLicenseZip << {
        copy {
            from "${deployRoot}"
            into "${deploydir}/${deployFolder}"
        }
    }

    task myCustomTask(dependsOn: deleteGraphicsAssets) << {
        copy {
            from 'deploymentfiles'
            into "${deployRoot}"
        }
    }
    task unzipArtifact(dependsOn: myCustomTask) << {
      def theZip = file("${buildDir}/artifacts").listFiles().find { it.name.endsWith('.zip') }
      println "Unzipping ${theZip} the artifact to: ${deployRoot}"
      ant.unzip(src: theZip, dest: "${deployRoot}", overwrite: true)
    }

    task setPerms(type:Exec, dependsOn: unzipArtifact) {
      workingDir "${deployRoot}"
      executable "bash"
      args "-c", "chmod -fR 755 *"

      }
    def dirName = "${deploydir}/${deployFolder}"
    task zipDeployment(type: GradleBuild, dependsOn: setPerms) { GradleBuild gBuild ->
        def env = System.getenv()
        def jobName=env['jobName']
    if (jobName.equals("LicenseGenerator")) {
        delete dirName
        file(dirName).mkdirs()
        gBuild.tasks = ['copyLicenseZip']
        } else {
       gBuild.tasks = ['copyartifactZip']
    }
    }

    task deployAll(dependsOn: zipDeployment){}



回答2:


It's usually a bad practice to have if/else logic in the build script because it adds complexity and sometimes causes surprising and unexpected results. Since you have very different artifacts, it's advisable to have two different tasks for that, instead of one-for-all deployAll. And you should call corresponding task when you are in different environments.



来源:https://stackoverflow.com/questions/30331762/how-to-use-if-else-condition-in-gradle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!