How to use if else condition in Gradle - groovy

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

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

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.

Related

NodeJs Jenkins plug-in is not working with dockerfile agent

I'm trying to use NodeJs plug-in on Jenkins. I follow NodeJs document and it work fine with its example code which is using agent any
pipeline {
agent any
stages {
stage('Build') {
steps {
nodejs(nodeJSInstallationName: 'NodeJs test') {
sh 'npm config ls'
}
}
}
}
}
But if I use dockerfile agent like the code below
pipeline {
options {
timeout(time:1,unit:'HOURS')
}
environment {
docker_image_name = "myapp-test"
HTTP_PROXY = "${params.HTTP_PROXY}"
JENKINS_USER_ID = "${params.JENKINS_USER_ID}"
JENKINS_GROUP_ID = "${params.JENKINS_GROUP_ID}"
}
agent {
dockerfile {
additionalBuildArgs '--tag myapp-test --build-arg "JENKINS_USER_ID=${JENKINS_USER_ID}" --build-arg "JENKINS_GROUP_ID=${JENKINS_GROUP_ID}" --build-arg "http_proxy=${HTTP_PROXY}" --build-arg "https_proxy=${HTTP_PROXY}"'
filename 'Dockerfile'
dir '.'
label env.docker_image_name
}
}
stages {
stage('Build') {
steps {
nodejs(nodeJSInstallationName: 'NodeJs test') {
sh 'npm config ls'
}
}
}
}
}
It will return npm: command not found error.
My guess is, It couldn't find the path of nodejs... I want to try to export PATH=$PATH:?? too but I also don't know the nodejs path.
How can I make the NodeJS plug-in work with dockerfile?
NodeJS plugin won't inject itself into a docker. However you could make an ARG build argument in your dockerfile that takes the version of nodeJS to install. You will then need to get read of the nodejs step
Thank you fredericrous for the answer. Unfortunately in my system, the dockerfile can't be modified. But from your information that
NodeJS plugin won't inject itself into a docker.
I decide to run the NodeJS plugin in another agent instead of dockerfile(running multiple agents)
With the code below I manage to run it successfully.
pipeline {
options {
timeout(time:1,unit:'HOURS')
}
environment {
docker_image_name = "myapp-test"
HTTP_PROXY = "${params.HTTP_PROXY}"
JENKINS_USER_ID = "${params.JENKINS_USER_ID}"
JENKINS_GROUP_ID = "${params.JENKINS_GROUP_ID}"
}
agent {
dockerfile {
additionalBuildArgs '--tag myapp-test --build-arg "JENKINS_USER_ID=${JENKINS_USER_ID}" --build-arg "JENKINS_GROUP_ID=${JENKINS_GROUP_ID}" --build-arg "http_proxy=${HTTP_PROXY}" --build-arg "https_proxy=${HTTP_PROXY}"'
filename 'Dockerfile'
dir '.'
label env.docker_image_name
}
}
stages {
stage('Build') {
steps {
sh 'ls'
}
}
}
}
stage('Test'){
node('master'){
checkout scm
try{
nodejs(nodeJSInstallationName: 'NodeJs test') {
sh 'npm config ls'
}
}
finally {
sh 'echo done'
}
}
}

Could not resolve org.nodejs : Local build error

I have a Angular-App forked from another repository where they manage all their builds in a pipeline.
I wanted to build that in my local system (laptop) and push the built-app in to the hosting server.
This is their build.gradle
node {
version = "9.4.0"
npmVersion = "5.6.0"
download = true
}
task cleanProd(type: Delete) {
delete "dist"
}
task testProd(type: NodeTask, dependsOn: npmInstall) {
script = file("${projectDir}/node_modules/#angular/cli/bin/ng")
args = ["test", "--browsers", "PhantomJS", "--watch=false", "--singleRun=true"]
}
task assembleProd(type: NodeTask, dependsOn: ['npmInstall', 'testProd']) {
script = file("${projectDir}/node_modules/#angular/cli/bin/ng")
args = ["build", "--prod", "--vendor-chunk=true"]
}
task copyDist(type: Copy) {
from "dist/"
into "dist/fancy-ui-${project.version}"
}
task buildProd(dependsOn: [assembleProd])
I executed the command gradlew cleanProd buildProd copyDist and I am stuck with the below exception
Build Version = build-713-ge359ca9
:cleanProd UP-TO-DATE
:nodeSetup FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':nodeSetup'.
> Could not resolve all dependencies for configuration 'detachedConfiguration1'.
> Could not resolve org.nodejs:node:9.4.0.
Required by:
:portal-ui:build-713-ge359ca9
> Could not resolve org.nodejs:node:9.4.0.
> Could not get resource 'https://nodejs.org/dist/v9.4.0/ivy.xml'.
> Could not GET 'https://nodejs.org/dist/v9.4.0/ivy.xml'.
> nodejs.org
I have all the necessary HTTP-Proxies and there is no issue with connectivity as such .. Just that this resource https://nodejs.org/dist/v9.4.0/ivy.xml is not getting loaded .. but the same code and configuration built fine in the Jenkins server
I had the same problem with node 10.14.1.
There is a workaround that solves the problem:
repositories.whenObjectAdded {
if (it instanceof IvyArtifactRepository) {
metadataSources {
artifact()
}
}
}
Extracted from https://github.com/srs/gradle-node-plugin/issues/301

Gradle build not including source/src groovy

I am trying to create a jar from a basic program.
I have a basic groovy project i.e. src/org...../*.groovy In the root
I have the following build.gradle
apply plugin: 'groovy'
version = '1.0'
repositories {
mavenCentral();
}
dependencies
{
compile files (fileTree(dir: 'lib', include: ['*.jar']),
fileTree(dir: 'lib/DocxDep', include: ['*.jar']))
}
task buildLabServicesJar(type: Jar) {
from files(sourceSets.main.output.classesDir)
from {
configurations.compile.collect {
it.isDirectory() ? it : zipTree(it)
}
configurations.runtime.collect {
it.isDirectory() ? it : zipTree(it)
}
}
manifest {
attributes 'Implementation-Title': 'Lab Services',
'Implementation-Version': version,
'Main-Class': 'org.xxx.clarity.ClarityServices'
}
}
Problem is when I run and/or inspec the jar file my sclasses from src/** are not included! (all the dependencies are perfect)
What is the problem here?
UPDATE
When I add:
from files(fileTree(dir: 'src'))
to the task it includes the .groovy files :(
When I add
from sourceSets.main.output.classesDir
to the task and:
sourceSets {
main {
groovy {
srcDir 'src'
}
}
}
They do not get included :( Can't find any other ways....
By default, Gradle looks for source in src/main/groovy when the 'groovy' plugin in applied. You'll need to either restructure your project or configure your source sets to appropriately reflect your project structure.
Final working build.gradle. (thanks all).
apply plugin: 'application'
apply plugin: 'groovy'
version = '1.0'
repositories {
mavenCentral();
}
dependencies
{
compile files (fileTree(dir: 'lib', include: ['*.jar']),
fileTree(dir: 'lib/DocxDep', include: ['*.jar']))
compile 'org.codehaus.groovy:groovy-all:2.3.6' //Was missing
}
task buildLabServicesJar(type: Jar) {
from files(sourceSets.main.output) //Was missing/wrong
from {
configurations.compile.collect {
it.isDirectory() ? it : zipTree(it)
}
configurations.runtime.collect {
it.isDirectory() ? it : zipTree(it)
}
}
with jar
sourceSets.main.groovy {
srcDirs = [ 'src' ] //Was missing/wrong
}
manifest {
attributes 'Implementation-Title': 'Lab Services',
'Implementation-Version': version,
'Main-Class': 'org.petermac.clarity.ClarityServices'
}
}
referencing sourceSets.main.output.classesDir in your jar task means that it will just copy everything from that directory in your jar. The problem is that when you run gradle buildLabServicesJar nothing tells gradle that the classes should be compiled first. That's why the directory keeps to be empty and your jar doesn't contain the compiled classes. If you modify your task declaration from
task buildLabServicesJar(type: Jar) {
from files(sourceSets.main.output.classesDir)
...
}
to
task buildLabServicesJar(type: Jar) {
from files(sourceSets.main.output)
...
}
task autowiring kicks in. task autowiring means that if you declare an output of one task as input to another task (your buildLabServicesJar) gradle knows that it must generate the output first (run the compile task for example).
hope that helps!
You must excuse me but I have recently crossed over from a long life of Microsoft and am still learning. I am surprised by the lack of blogs and example code of basic stuff, what I am doing is so standard....(I will be posting one once/if I figure this out)
Note: Intellij -> Build -> Build Artifacts works perfectly but I would like to move this to Bamboo.
anyway taking into account everyone's ideas, here is my file (and error)
apply plugin: 'groovy'
version = '1.0'
repositories {
mavenCentral();
}
dependencies
{
compile files (fileTree(dir: 'lib', include: ['*.jar']),
fileTree(dir: 'lib/DocxDep', include: ['*.jar']))
}
//println "Classes dir: " + sourceSets.main.groovy
task buildLabServicesJar(type: Jar) {
from files(sourceSets.main.output)
//from sourceSets.main.groovy.output
//from files(fileTree(dir: 'src'))
from {
configurations.compile.collect {
it.isDirectory() ? it : zipTree(it)
}
configurations.runtime.collect {
it.isDirectory() ? it : zipTree(it)
}
}
manifest {
attributes 'Implementation-Title': 'Lab Services',
'Implementation-Version': version,
'Main-Class': 'org.petermac.clarity.ClarityServices'
}
}
sourceSets {
main {
groovy.srcDirs = [ 'src' ]
}
}
ERROR:Cannot infer Groovy class path because no Groovy Jar was found on class path: configuration ':compile'
And if I change src line to:
srcDirs = [ 'src/**' ]
It builds but leaves out all my source again.

How to build Groovy JAR w/ Gradle and publish it to in-house repo

I have a Groovy project and am trying to build it with Gradle. First I want a package task that creates a JAR by compiling it against its dependencies. Then I need to generate a Maven POM for that JAR and publish the JAR/POM to an in-house Artifactory repo. The build.gradle:
apply plugin: "groovy"
apply plugin: "maven-publish"
repositories {
maven {
name "artifactory01"
url "http://myartifactory/artifactory/libs-release"
}
}
dependencies {
compile "long list starts here"
}
// Should compile up myapp-<version>.jar
jar {
}
// Should publish myapp-<version>.jar and its (generated) POM to our in-house Maven/Artifactory repo.
publishing {
publications {
myPublication(MavenPublication) {
from components.java
artifact sourceJar {
classifier "source"
}
pom.withXml {
// ???
}
}
}
}
task wrapper(type: Wrapper) {
gradleVersion = '1.11'
}
However I do not believe I have set up versioning correctly with my jar task (for instance, how could I get it creating myapp-1.2.1 vs. myapp-1.2.2? I also don't think I have my publications configuration set up correctly: what should go in pom.withXml?
You're more than welcome to use artifactory plugin for that.
The documentation can be found in our user guide and below you can find a full working example of gradle build.
Run gradle build artifactoryPublish to build and publish the project.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath(group: 'org.jfrog.buildinfo', name: 'build-info-extractor-gradle', version: '3.0.1')
}
}
apply plugin: 'java'
apply plugin: 'maven-publish'
apply plugin: 'com.jfrog.artifactory'
group = 'com.jfrog.example'
version = '1.2-SNAPSHOT'
status = 'SNAPSHOT'
dependencies {
compile 'org.slf4j:slf4j-api:1.7.5'
testCompile 'junit:junit:4.11'
}
task sourcesJar(type: Jar, dependsOn: classes) {
classifier = 'sources'
from sourceSets.main.allSource
}
publishing {
publications {
main(MavenPublication) {
from components.java
artifact sourcesJar
}
}
artifactory {
contextUrl = 'http://myartifactory/artifactory'
resolve {
repository {
repoKey = 'libs-release'
}
}
publish {
repository {
repoKey = 'libs-snapshot-local'
username = 'whatever'
password = 'whatever123'
}
defaults {
publications 'main'
}
}
}
package is a keyword in Java/Groovy, and you'd have to use a different syntax to declare a task with that name.
Anyway, the task declaration for package should be removed, as the jar task already serves that purpose. The jar task configuration (jar { from ... }) should be at the outermost level (not nested inside another task), but from configurations.compile is unlikely what you want, as that will include Jars of compile dependencies into the Jar (which regular Java class loaders can't deal with), rather than merging them into the Jar. (Are you even sure you need a fat Jar?)
Likewise, the publish task declaration should be removed, and replaced with publishing { publications { ... } }.
Also, the buildscript block should probably be removed, and repositories { ... } and dependencies { ... } moved to the outermost level. ( buildscript { dependencies { ... } } declares dependencies of the build script itself (e.g. Gradle plugins), not the dependencies of the code to be compiled/run.)
I suggest to check out the many self-contained example builds in the samples directory of the full Gradle distribution (gradle-all).

gradle merge configurations.testRuntime with configurations.testCompile in copy

I'd like to copy some of my dependencies (retrieved from maven) to specific location in my build.gradle file.
If I iterate only testRuntime it works OK. My code is:
dependencies {
testRuntime 'p6spy:p6spy:2.+'
testRuntime 'com.h2database:h2:1+'
}
task foo {
copy {
from configurations.testRuntime.findAll { it.getAbsolutePath().contains("/p6spy/") || it.getAbsolutePath().contains("/h2/") }
into "outputdir"
}
}
however I'd like to go for testCompile rather than testRuntime in case of h2 dependency. So I tried:
dependencies {
testRuntime 'p6spy:p6spy:2.+'
testCompile 'com.h2database:h2:1+'
}
task foo {
copy {
from [ configurations.testRuntime, configurations.testCompile ].flatten().findAll { it.getAbsolutePath().contains("/p6spy/") || it.getAbsolutePath().contains("/h2/") }
into "outputdir"
}
}
However here I get error:
No such property: from for class: org.gradle.api.internal.file.copy.CopySpecWrapper_Decorated
I guess trouble is in my merging of the 2 lists here. Still can't figure out the right way.
Your solution will copy the files on every build invocation, even if the foo task isn't invoked. Here is a correct solution:
task foo(type: Copy) {
from configurations.testRuntime // includes configurations.testCompile
into "outputdir"
include "**/p6spy/**"
include "**/h2/**"
}
well, found solution myself, documenting it:
dependencies {
testRuntime 'p6spy:p6spy:2.+'
testCompile 'com.h2database:h2:1+'
}
task foo {
copy {
from configurations.testRuntime.plus(configurations.testCompile).findAll { it.getAbsolutePath().contains("/p6spy/") || it.getAbsolutePath().contains("/h2/") }
into "outputdir"
}
}

Resources