Execute a task only if a particular task is run - gradle

I want the task setupDB to execute if and only if the task fatJar or slimJar is run.
But after adding gradle.taskGraph.whenReady, commandLine './scripts/configureSQLiteDB.sh' is never running for any task.
Here is my code for the setupDB task:
//download bigg.sqlite if not present
task setupDB {
gradle.taskGraph.whenReady { graph ->
if (!project.file("resources/edu/ucsd/sbrg/bigg/bigg.sqlite").exists()
&& (graph.hasTask(slimJar)|| graph.hasTask(fatJar))) {
doFirst {
exec {
println "Setup DB"
commandLine './scripts/configureSQLiteDB.sh'
}
}
}
}
}
You can also view the build.gradle file:
apply plugin: "java"
defaultTasks "clean", "fatJar"
// Java versions for compilation and output
sourceCompatibility = "1.8"
targetCompatibility = "1.8"
archivesBaseName = "ModelPolisher"
version = "1.7"
sourceSets {
main.java.srcDirs = ["src"]
main.resources.srcDirs = ["resources"]
main.resources.excludes = ["**/bigg.zip"]
test.java.srcDirs = ["test"]
}
repositories {
mavenCentral()
maven { url "http://www.ebi.ac.uk/~maven/m2repo" }
maven { url "http://jsbml.sourceforge.net/m2repo/" }
// local dependencies
flatDir {
dirs "lib/de/zbit/SysBio/1390"
}
}
dependencies {
compile "org.sbml.jsbml:jsbml:1.4"
compile "de.zbit:SysBio:1390"
compile "org.xerial:sqlite-jdbc:3.21.0"
compile "org.postgresql:postgresql:42.2.2"
compile "org.biojava:biojava-ontology:5.0.0"
compile "com.diffplug.matsim:matfilerw:3.0.1"
compile "com.fasterxml.jackson.core:jackson-core:2.9.9"
compile "com.fasterxml.jackson.core:jackson-databind:2.9.9"
testCompile "org.junit.jupiter:junit-jupiter-engine:5.1.0"
}
// config for all jar tasks
tasks.withType(Jar) {
dependsOn test
destinationDir = file("$rootDir/target")
manifest {
attributes(
"Version": version,
"Implementation-Title": "ModelPolisher",
"Implementation-Version": version,
"Specification-Vendor": "University of California, San Diego",
"Specification-Title": "ModelPolisher",
"Implementation-Vendor-Id": "edu.ucsd.sbrg",
"Implementation-Vendor": "University of California, San Diego",
"Main-Class": "edu.ucsd.sbrg.bigg.ModelPolisher"
)
}
}
// with dependencies
task fatJar(type: Jar) {
baseName = project.name + "-fat"
from {
configurations.compile.collect {
it.isDirectory() ? it : zipTree(it)
}
}
with jar
}
//with dependencies, without bigg.sqlite
task lightJar(type: Jar) {
exclude("**/bigg.sqlite")
baseName = project.name + "-noDB"
from {
configurations.compile.collect {
it.isDirectory() ? it : zipTree(it)
}
}
with jar
}
// without dependencies and bigg.sqlite
task bareJar(type: Jar) {
exclude("**/bigg.sqlite")
baseName = project.name + "-slim-noDB"
with jar
}
// without dependencies, bigg.sqlite included
// not included in release
task slimJar(type: Jar) {
baseName = project.name + "-slim"
with jar
}
// zip lib folder for release
task zipLibs(type: Zip) {
from "lib"
into "lib"
include "**/**"
archiveName = "lib.zip"
destinationDir = file("target/")
}
// zip script files for release
task zipScripts(type: Zip) {
from "scripts"
into "scripts"
include "**/**"
archiveName = "scripts.zip"
destinationDir = file("target/")
}
// create all three jars for release
task release() {
dependsOn fatJar
dependsOn bareJar
dependsOn lightJar
dependsOn tasks["zipLibs"]
dependsOn tasks["zipScripts"]
// necessary, as order is not defined by dependsOn
bareJar.mustRunAfter classes
// slimJar.mustRunAfter bareJar
lightJar.mustRunAfter slimJar
fatJar.mustRunAfter lightJar
}
// clean up target directory
clean.doFirst {
file(".gradle").deleteDir()
file("target").deleteDir()
}
//download bigg.sqlite if not present
task setupDB {
gradle.taskGraph.whenReady { graph ->
if (!project.file("resources/edu/ucsd/sbrg/bigg/bigg.sqlite").exists()
&& (graph.hasTask(slimJar)|| graph.hasTask(fatJar))) {
doFirst {
exec {
println "Setup DB"
commandLine './scripts/configureSQLiteDB.sh'
}
}
}
}
}
// bump jar version in travis.yml
if (project.file(".travis.yml").exists()) {
task bumpVersionTravis() {
replaceVersion(".travis.yml")
}
processResources.dependsOn bumpVersionTravis
}
// bump jar version in ModelPolisher.sh
if (project.file("./scripts/ModelPolisher.sh").exists()) {
task bumpVersionMP() {
replaceVersion("./scripts/ModelPolisher.sh")
}
processResources.dependsOn bumpVersionMP
}
def replaceVersion(path) {
ArrayList<String> content = new ArrayList<>()
File travisFile = new File(path)
String MPVersion = /ModelPolisher.*\d{1,2}(.\d{1,2}){1,2}.jar/
travisFile.eachLine {
line ->
content.add(line.replaceAll(MPVersion, "ModelPolisher-fat-" +
"${version}.jar"))
}
BufferedWriter writer = new BufferedWriter(new FileWriter(travisFile))
content.each {
line -> writer.writeLine(line)
}
writer.close()
}

You seem to have the wrong idea about gradle configuration. You shouldn't be changing task behavior based on inputs. You should be configuring dependencies between tasks and also configuring task inputs/outputs to control the "up-to-date" behaviour.
Eg:
task slimJar(type:Jar) {
dependsOn 'setupDB'
...
}
task fatJar(type:Jar) {
dependsOn 'setupDB'
...
}
task setupDB {
outputs.upToDateWhen { file("resources/edu/ucsd/sbrg/bigg/bigg.sqlite").exists() }
doFirst {
println "Setup DB"
exec {
commandLine './scripts/configureSQLiteDB.sh'
}
}
}
The following is also bad practice
if (project.file(".travis.yml").exists()) {
task bumpVersionTravis() {
replaceVersion(".travis.yml")
}
processResources.dependsOn bumpVersionTravis
}
The available tasks should NOT change based on files in your file system. They should always be there, regardless of your file system. You should instead set the "enabled" flag (or use task outputs) to control if the task executes or is skipped
Eg:
task bumpVersionTravis {
enabled = project.file(".travis.yml").exists()
doLast {
replaceVersion(".travis.yml")
}
}
processResources.dependsOn bumpVersionTravis

Related

Transitive dependencies are not found when using composite builds with custom publish metadata

Given the following three projects (foo, bar, and app), where app depends on bar depends on foo, I'd like to be able to simply install bar in project app and have library foo automatically installed as well. This does work correctly with the following scripts:
Project 'foo' build.gradle
plugins {
id "maven-publish"
}
repositories {
mavenLocal()
}
group = "com.test2.foo"
version = "0.0.1"
def distZip = file("${buildDir}/dist.zip")
def distFile = file("${buildDir}/Foo.txt")
tasks.register("createDistFile") {
outputs.file(distFile)
doLast {
distFile.delete()
distFile.parentFile.mkdirs()
distFile.text = "foo output 1"
}
}
tasks.register("assembleZip", Zip) {
dependsOn "createDistFile"
from distFile
archiveName = distZip.name
destinationDir distZip.parentFile
}
publishing {
publications {
main(MavenPublication) {
artifact(distZip) {
builtBy tasks.named("assembleZip")
}
}
}
repositories {
mavenLocal()
}
}
Project 'bar' build.gradle
plugins {
id "maven-publish"
id "base"
}
repositories {
mavenLocal()
}
group = "com.test2.bar"
version = "0.0.1"
def distZip = file("${buildDir}/dist.zip")
def distFile = file("${buildDir}/Bar.txt")
tasks.register("createDistFile") {
outputs.file(distFile)
doLast {
distFile.delete()
distFile.parentFile.mkdirs()
distFile.text = "bar output 2"
}
}
tasks.register("assembleZip", Zip) {
dependsOn "createDistFile"
from distFile
archiveName = distZip.name
destinationDir distZip.parentFile
}
artifacts {
"default" distZip, {
builtBy tasks.named("assembleZip")
}
}
publishing {
publications {
main(MavenPublication) {
artifact(distZip) {
builtBy tasks.named("assembleZip")
pom.withXml {
def dependenciesNode = asNode().appendNode('dependencies')
def dependencyNode = dependenciesNode.appendNode('dependency')
dependencyNode.appendNode('groupId', "com.test2.foo")
dependencyNode.appendNode('artifactId', "foo")
dependencyNode.appendNode('version', "0.0.1")
}
}
}
}
repositories {
mavenLocal()
}
}
Project 'app' build.gradle
repositories {
mavenLocal()
}
configurations {
api
}
dependencies {
api "com.test2.bar:bar:0.0.1"
// This should be automatically installed when bar is installed
// api "com.test2.foo:foo:0.0.1"
}
tasks.register("installLibs", Copy) {
dependsOn configurations.api
destinationDir = file("${buildDir}/libs")
configurations.api.each { config ->
from zipTree(config)
}
doFirst {
destinationDir.deleteDir()
}
}
The Problem
When using the above scripts, this can be verified by running installLibs in project app and verifying that both Bar.txt and Foo.txt are installed into the build/libs directory.
However, if I change the settings.gradle file in project 'app' to be this:
rootProject.name = 'app'
includeBuild '[PATH TO BAR PROJECT]'
Then if I run ./gradle installLibs again for the app project, I find that Foo.txt is no longer installed. Is there a way to manually specify this build metadata for project bar, so then when it is used with includeBuild that its transtive dependencies get included?

Gradle does not copy jars to Maven .m2 folder

What could be missing in this build.gradle file that prevents the publishToMavenLocal not to copy files to the .m2 folder?
The script does have the 'maven-publish' plugin.
buildscript {
ext.kotlinVersion = '1.3.10'
ext.dokkaVersion = '0.9.17'
repositories { mavenLocal() }
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
classpath "org.jetbrains.dokka:dokka-gradle-plugin:$dokkaVersion"
}
}
plugins {
id 'com.github.hierynomus.license' version '0.15.0'
id 'io.codearte.nexus-staging' version '0.11.0'
id 'maven-publish'
}
group = 'org.jetbrains.xodus'
version = hasProperty('xodusVersion') ? project.xodusVersion : ''
def isSnapshot = version.endsWith('SNAPSHOT')
def isDailyBuild = hasProperty('dailyBuild') ? project.dailyBuild : false
def mavenPublishUrl = hasProperty('mavenPublishUrl') ? project.mavenPublishUrl : ''
def mavenPublishUsername = hasProperty('mavenPublishUsername') ? project.mavenPublishUsername : ''
def mavenPublishPassword = hasProperty('mavenPublishPassword') ? project.mavenPublishPassword : ''
def signingKeyId = hasProperty('signingKeyId') ? project.signingKeyId : ''
def signingPassword = hasProperty('signingPassword') ? project.signingPassword : ''
def signingSecretKeyRingFile = hasProperty('signingSecretKeyRingFile') ? project.signingSecretKeyRingFile : '../key.gpg'
static def shouldDeploy(project) {
return project.version.length() > 0 && !(project.name in ['benchmarks', 'samples'])
}
task wrapper(type: Wrapper) {
gradleVersion = '3.5.1'
}
defaultTasks 'assemble'
// Use nexus-staging-plugin to workaround https://issues.sonatype.org/browse/OSSRH-5454
nexusStaging {
username = mavenPublishUsername
password = mavenPublishPassword
delayBetweenRetriesInMillis = 30000
stagingProfileId = "89ee7caa6631c4"
}
subprojects {
apply plugin: 'license'
apply plugin: 'java'
apply plugin: 'kotlin'
apply plugin: 'maven'
apply plugin: 'signing'
apply plugin: 'org.jetbrains.dokka'
sourceCompatibility = 1.7
compileJava.options.encoding = 'UTF-8'
group = rootProject.group
version = rootProject.version
archivesBaseName = rootProject.name + '-' + project.name
license {
header rootProject.file('license/copyright.ftl')
strictCheck true
ext.inceptionYear = 2010
ext.year = Calendar.getInstance().get(Calendar.YEAR)
ext.owner = 'JetBrains s.r.o.'
include "**/*.kt"
include "**/*.java"
mapping {
kt = 'JAVADOC_STYLE'
}
}
repositories {
mavenCentral()
mavenLocal()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
testCompile group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.25'
}
// tests for most of sub-projects run with database encryption turned on
if (!(project.name in ['benchmarks', 'compress', 'crypto', 'openAPI', 'samples', 'utils'])) {
test {
systemProperty 'exodus.cipherId', 'jetbrains.exodus.crypto.streamciphers.ChaChaStreamCipherProvider'
systemProperty 'exodus.cipherKey', '000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f'
systemProperty 'exodus.cipherBasicIV', '314159262718281828'
// uncomment the following line to run tests in-memory
//systemProperty 'exodus.log.readerWriterProvider', 'jetbrains.exodus.io.inMemory.MemoryDataReaderWriterProvider'
}
dependencies {
testCompile project(':crypto')
}
}
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
jar {
manifest {
attributes 'Implementation-Title': archivesBaseName, 'Implementation-Version': version
}
}
test {
minHeapSize = '1g'
maxHeapSize = '1g'
//jvmArgs = ['-ea', '-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=2808']
//testLogging.showStandardStreams = true
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
duplicatesStrategy 'exclude'
includeEmptyDirs false
from javadoc.destinationDir
}
javadoc.failOnError = false
// work around for Java 8 javadoc which is too strict
if (JavaVersion.current().isJava8Compatible()) {
tasks.withType(Javadoc) {
options.addStringOption('Xdoclint:none', '-quiet')
}
}
task sourceJar(type: Jar) {
classifier = 'sources'
duplicatesStrategy 'exclude'
includeEmptyDirs false
from project.sourceSets.main.java
from project.sourceSets.main.kotlin
}
// configuring projects with Kotlin sources
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion"
compile 'io.github.microutils:kotlin-logging:1.5.4'
}
compileKotlin {
kotlinOptions {
languageVersion = '1.2'
apiVersion = '1.2'
}
}
compileTestKotlin {
kotlinOptions {
languageVersion = '1.2'
apiVersion = '1.2'
}
}
dokka {
jdkVersion = 7
packageOptions {
reportUndocumented = false
}
}
task dokkaJavadoc(type: org.jetbrains.dokka.gradle.DokkaTask) {
outputFormat = 'javadoc'
outputDirectory = "$buildDir/javadoc"
}
javadocJar {
dependsOn dokkaJavadoc
from dokkaJavadoc.outputDirectory
}
artifacts {
archives jar, javadocJar, sourceJar
}
if (!isSnapshot && signingKeyId.length() > 0) {
ext.'signing.keyId' = signingKeyId
ext.'signing.password' = signingPassword
ext.'signing.secretKeyRingFile' = signingSecretKeyRingFile
}
afterEvaluate { project ->
if (shouldDeploy(project)) {
uploadArchives {
repositories {
mavenDeployer {
beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
if (isDailyBuild) {
repository(url: "https://api.bintray.com/maven/jetbrains/xodus/" + archivesBaseName + "/;publish=1") {
authentication(userName: mavenPublishUsername, password: mavenPublishPassword)
}
} else {
repository(url: mavenPublishUrl) {
authentication(userName: mavenPublishUsername, password: mavenPublishPassword)
}
}
pom.project {
name 'Xodus'
description 'Xodus is pure Java transactional schema-less embedded database'
packaging 'jar'
url 'https://github.com/JetBrains/xodus'
scm {
url 'https://github.com/JetBrains/xodus'
connection 'scm:git:https://github.com/JetBrains/xodus.git'
developerConnection 'scm:git:https://github.com/JetBrains/xodus.git'
}
licenses {
license {
name 'The Apache Software License, Version 2.0'
url 'http://www.apache.org/license/LICENSE-2.0.txt'
distribution 'repo'
}
}
developers {
developer {
id 'JetBrains'
name 'JetBrains Team'
organization 'JetBrains s.r.o'
organizationUrl 'http://www.jetbrains.com'
}
}
}
}
}
}
signing {
required { !isSnapshot && signingKeyId.length() > 0 && gradle.taskGraph.hasTask('uploadArchives') }
sign configurations.archives
}
}
}
}
Your build does not configure any publications, hence the publishToMavenLocal task is a noop:
$ ./gradlew --console=verbose publishToMavenLocal
> Task :publishToMavenLocal UP-TO-DATE
BUILD SUCCESSFUL in 0s
When you configure a publication as in this example …
task buildMyArtifact(type: Zip) {
// TODO using the build script as a sample file here; use whatever makes
// sense for your project
from 'build.gradle'
archiveBaseName = 'whateverNameInBuildDir'
destinationDirectory = buildDir
}
publishing {
publications {
myPublication(MavenPublication) {
artifact buildMyArtifact
groupId 'com.example'
artifactId 'my-module'
version '1.0.0'
}
}
}
… then the publishToMavenLocal task installs the publication into the local Maven repository:
$ ./gradlew --console=verbose publishToMavenLocal
> Task :buildMyArtifact
> Task :generatePomFileForMyPublicationPublication
> Task :publishMyPublicationPublicationToMavenLocal
> Task :publishToMavenLocal
BUILD SUCCESSFUL in 1s
3 actionable tasks: 3 executed
$ tree ~/.m2/repository/com/example/my-module/
/home/chriki/.m2/repository/com/example/my-module/
├── 1.0.0
│   ├── my-module-1.0.0.pom
│   └── my-module-1.0.0.zip
└── maven-metadata-local.xml
1 directory, 3 files

gradle tasks.withType does not find tasks defined in other file

I have two gradle files, setup.gradle and tests.gradle; each having two gradle tasks of custom type 'EMTest';
test.gradle applies the 'setup.gradle' as apply from: 'setup.gradle'
I want to configure all tasks of type EMTest; For that I added below code at end of tests.gradle
tasks.withType(EMTest) {
println it.name
}
But this only prints the name of tasks in the tests.gradle;
When I run
tasks.all {
println it.name + " " + it.class
}
It however lists the tasks name defined in setup.gradle and the type as EMTest_Decorated (for all 4 types)
NOTE: I use gradle 1.11 (no control over upgrade); What is the issue here ?
UPDATE On 09/Jun
Here is the main file :
apply plugin: 'java';
apply plugin: 'maven'
apply from: 'emcpsrvs_3n_setup.gradle'
buildscript {
repositories {
maven {
url = "${artifactory_contextUrl}/repo" }
}
dependencies {
classpath group:"com.mycompany.myprod.mymodule", name: "TestInfraPlugin", version: "${testinfraVersion}", transitive: true
classpath group: 'org.codehaus.jackson', name: 'jackson-mapper-asl', version:'1.9.13'
classpath group: 'com.mycompany.myprod', name: 'common',version:'0.1'
classpath group: 'org.codehaus.jackson', name: 'jackson-core-asl', version:'1.9.13'
classpath group: 'com.oracle.weblogic',name: 'jettison-1.1', version: '12.1.2-0-0'
}
}
repositories {
/* To check if the jar is available in local maven repository */
mavenLocal()
maven {
url = "${artifactory_contextUrl}/repo"
}
}
apply plugin: 'TestInfraPlugin'
import com.mycompany.myprod.gradle.testinfra.tasks.EMTest;
repositories {
maven {
url = "${artifactory_contextUrl}/repo"
}
}
dependencies {
testConfig group:'com.mycompany.myprod',name:'ui-integ-tests', version: '1.+'
testConfig group: 'com.mycompany.myprod', name: 'emaas-platform-tenant-sdk', version: '0.1+'
}
task unitTests(type: EMTest){
}
// Three tests are disabled due to JIRA-900
task tenantMgmtUITests(type: EMTest,dependsOn: [cleanSmall_deploy_3n_block,small_deploy_3n_block]) {
useWebdriver = true
small_deploy_3n_block.mustRunAfter ([cleanSmall_deploy_3n_block])
options.suiteXmlBuilder().suite('parallel': 'none','name': 'TenantManagementUI') {
test('name': 'TenantManagementUI') {
classes([:]) {
'class'('name': 'com.mycompany.package.MyTest')
}
}
}
}
small_deploy_3n_cleanup.mustRunAfter ([tenantMgmtUITests])
task emcpsrvs_tenant_mgmt_ui_3n(dependsOn: [tenantMgmtUITests,small_deploy_3n_cleanup])
Here is the 'emcpsrvs_3n_setup.gradle' which is being applied above
buildscript {
repositories {
maven {
url = "${artifactory_contextUrl}/repo"
}
}
dependencies {
classpath group: 'com.mycompany.myprod.emdi', name: 'TestInfraPlugin', version: "${testinfraVersion}", transitive: true
}
}
apply plugin: 'TestInfraPlugin'
repositories {
maven {
url = "${artifactory_contextUrl}/repo"
}
}
import com.mycompany.myprod.gradle.testinfra.tasks.EMTest;
ext.integDeployVersion='1.1+'
dependencies {
testConfig group: 'com.mycompany.myprod.test', name: 'smalldeployment', version: "${integDeployVersion}"
}
/* Setup EMaaS Small Deployment */
task small_deploy_3n_block(type: EMTest) {
outputs.upToDateWhen { false }
onlyIf {!System.env.SMALLDEPLOY_IGNORESETUP}
options.suiteXmlBuilder().suite('name': 'setup_3n_env') {
test('name': 'emaas_setup_small_deploy') {
classes([:]) {
'class'('name': 'mycompany.sysman.test.emaas.integ.EmaasSmallDeploy3n') {
methods([:]) {
'include' ('name': 'setupEmaasSmallDeploy')
}
}
}
}
}
useWebdriver = true
useRestAssured = true
}
/* Cleanup EMaaS Small Deployment */
task small_deploy_3n_cleanup(type: EMTest) {
onlyIf {!System.env.SMALLDEPLOY_IGNORESETUP}
options.suiteXmlBuilder().suite('name': 'setup_3n_env') {
test('name': 'emaas_setup_small_deploy') {
classes([:]) {
'class'('name': 'mycompany.sysman.test.emaas.integ.EmaasSmallDeploy3n') {
methods([:]) {
'include' ('name': 'logCollectionAndPostCleanup')
}
}
}
}
}
mustRunAfter ([small_deploy_3n_block])
}
And finally here is the snippet from TestInfraPlugin.groovy (The gradle plugin):
logger.debug "Configuring the EMTest task with default values."
project.afterEvaluate {
project.ext.testClassesDir = new File(project.properties['emdi.T_WORK'] + '/testClasses')
def testTasks = project.tasks.withType(EMTest)
if (testTasks != null && testTasks.size() == 0) {
logger.info "There are no tasks of type EMTest."
return
}
def extractTask = project.tasks.findByPath('extractTestClasses') ?:
project.task('extractTestClasses', type: ExtractConfiguration) {
configuration = project.configurations.testConfig
to = project.testClassesDir
}
/*
* 1. Adding the 'extractTask' to all EMTest, to ensure that 'extractTask' is run before any 'EMTest'.
* 2. For lazy evaluation of lrgConfig, we are NOT running the task here, but just adding as dependent task.
*/
testTasks.each { task ->
logger.debug "Adding dependsOn extractTask for task: ${task.name}"
task.dependsOn extractTask
}
} // end afterEvaluate
}
What is afterEvaluate{} block doing:
It checks if there are any tasks of type EMTest and if there are creates a task to extract a configuration (named testConfig). This extract task is added as dependency on all the tasks of type EMTest such that the extract task run as first task before running any other task.
What is happening
The extractTestClasses task is added as dependency to ONLY the two tasks unitTests and tenantMgmtUITests and thus the small_deploy_3n_block is getting executed before extractTestClasses resulting setup to fail, which in turn results test to fail.
When you reference tasks with no object it is implicitly using project.tasks.
tasks.withType(EMTest) {
println it.name
}
That is why you'll only get tasks from your current project.
To include all projects you can use:
allprojects {
tasks.withType(EMTest) { println it.name }
}
In this closure you are referencing it.tasks, where it loops over every individual project.
This will not work as expected since Gradle will probably not have loaded all of your sub-projects at this point, and not have reached every task define found during the full configuration phase. Therefore you must define the closure to run after all the projects are fully evaluated:
allprojects {
afterEvaluate {
tasks.withType(EMTest) { println it.name }
}
}

Defining custom ‘build’ task is deprecated when using standard lifecycle plugin has been deprecated and is scheduled to be removed in Gradle 3.0

I am facing an issue in my build.gradle script My script is bascially generatiing the POM file and then copy the artifact to other location as well under build/lib with different name.The issue which I am facing How to call the below build task beacuse it is generating the error.I am using gradle 2.3
Error:"Defining custom ‘build’ task is deprecated when using standard lifecycle plugin has been deprecated and is scheduled to be removed in Gradle 3.0"
My task build will build the artifact and then generate the POM and move the artifact to different location but I am getting below error.
My full script is
apply plugin: 'cpp'
apply plugin: 'java'
//-- set the group for publishing
group = 'com.tr.anal'
/**
* Initializing GAVC settings
*/
def buildProperties = new Properties()
file("version.properties").withInputStream {
stream -> buildProperties.load(stream)
}
//add the jenkins build version to the version
def env = System.getenv()
if (env["BUILD_NUMBER"]) buildProperties.analBuildVersion += "_${env["BUILD_NUMBER"]}"
version = buildProperties.analBuildVersion
println "${version}"
//name is set in the settings.gradle file
group = "com.t.anal"
version = buildProperties.analBuildVersion
println "Building ${project.group}:${project.name}:${project.version}"
repositories {
maven {
url "http://cm.thon.com:900000/artifactory/libs-snapshot-local"
}
maven {
url "http://cm.thon.com:9000000/artifactory/libs-release"
}
}
dependencies {
compile ([
"com.tr.anal:analytics-engine-common:4.+"
])
}
model {
repositories {
libs(PrebuiltLibraries) {
jdk {
headers.srcDirs "${System.properties['java.home']}/../include",
"${System.properties['java.home']}/../include/win32",
"${System.properties['java.home']}/../include/darwin",
"${System.properties['java.home']}/../include/linux"
}
}
}
}
model {
platforms {
x64 { architecture "x86_64" }
x86 { architecture "x86" }
}
}
model {
components {
main(NativeLibrarySpec) {
sources {
cpp {
source {
lib library: 'main', linkage: 'static'
lib library: 'jdk', linkage: 'api'
srcDir "src/main/c++/native"
include "**/JniSupport.cpp"
include "**/DiseaseStagingJni.cpp"
}
}
}
}
}
}
def nativeHeadersDir = file("$buildDir/nativeHeaders")
//def compilePath = configurations.compile.resolve().collect {it.absolutePath}.join(";")
binaries.all {
// Define toolchain-specific compiler and linker options
if (toolChain in Gcc) {
cppCompiler.args "-I${nativeHeadersDir}"
cppCompiler.args "-g"
linker.args '-Xlinker', '-shared -LNativeJNI/src/main/resources/DSresources/DSLib -lds64 -Wl'
}
}
//def nativeHeadersDir = file("$buildDir/nativeHeaders")
task nativeHeaders {
// def nativeHeadersDir = file("$buildDir/nativeHeaders")
def outputFile = file("$nativeHeadersDir/DiseaseStagingJniWrapper.h")
def classes = [
'com.truvenhealth.analyticsengine.common.diseasestaging.DiseaseStagingJniWrapper'
]
inputs.files sourceSets.main.output
inputs.property('classes', classes)
outputs.file outputFile
doLast {
outputFile.parentFile.mkdirs()
def compilePath = configurations.compile.resolve().collect {it.absolutePath}.join(":")
println "Using Compile Path: ${compilePath}"
exec {
executable org.gradle.internal.jvm.Jvm.current().getExecutable('javah')
args '-o', outputFile
args '-classpath', compilePath
args classes
}
}
}
tasks.withType(CppCompile) { task ->
task.dependsOn nativeHeaders
}
/*****************************
* Packaging
*****************************/
apply plugin: "maven"
// Workaround for Jenkins-Artifactory plugin not picking up the POM file
def pomFile = file("${buildDir}/libs/${archivesBaseName.toLowerCase()}-${version}.pom")
task newPom << {
pom {
project {
groupId project.group
artifactId project.name
version project.version
description = "Configuration Management Gradle Plugin"
}
}.writeTo(pomFile)
}
//disabling the install task since we're not using maven for real
install.enabled = false
//for publishing to artifactory via jenkins
if(project.hasProperty('artifactoryPublish')) {
artifactoryPublish {
mavenDescriptor pomFile
}
}
def filechange = file("build/libs/NativeJNI-${project.version}.so")
task copyfile(type: Copy) {
from 'build/binaries/mainSharedLibrary'
into 'build/libs'
include('libmain.so')
rename ('libmain.so', "$filechange")
}
//build.dependsOn copyfile
task build (dependsOn: ["newPom","copyfile"]) << {
println "build in progress"
}
def someFile = file("build/libs/NativeJNI-${project.version}.so")
artifacts {
archives someFile
}
Looks like this was a bug in 3.0,
https://github.com/GradleFx/GradleFx/issues/235

confusion on what tasks --all prints out

I have this when I execute "gradle tasks --all"
assemble - Assembles the outputs of this project. [jar]
toneserver:assemble - Assembles the outputs of this project. [toneserver:jar, webserver:jar]
toneserver:copyJars
toneserver:zip
webserver:assemble - Assembles the outputs of this project. [webserver:jar]
webserver:versionFile
webserver:zip
What I really really don't get is I have toneserver:zip depending on toneserver:jar and I have webserver:zip depending on webserver:jar but this tasks --all is not showing those dependencies. Why is this? and how to get it to truly show the dependencies?
My full gradle file is below(and yes I need to move the apply plugin stuff still out of all projects into subprojects section and other
allprojects {
apply plugin: 'java'
apply plugin: 'eclipse'
//override gradle's default output directory(build) on every project as it conflicts with
//our build script called build causing failures.
buildDir = 'output'
repositories {
mavenCentral()
}
if (project.hasProperty('myVersion')) {
project.ext.realVersion = project.myVersion
project.version = project.myVersion
} else {
project.ext.realVersion = 'Developer-Build'
project.version = 'Developer-Build'
}
test {
beforeTest { desc ->
println "Executing test ${desc.name} [${desc.className}]"
}
}
task hello << { task -> println "I'm $task.project.name" }
build << { task -> println "MASTER: I'm building now" } //"building with classpath=$sourceSets.main.compileClasspath.files"
}
project(':webserver') {
//play does not follow maven/gradle standard of src/main/java and src/test/java :( :(
//so we override the directories here...(we should put test in the sourceSets.test.java.srcDirs instead)
sourceSets.main{
java.srcDirs = ['app', 'test']
resources.srcDirs = ['app']
}
dependencies {
compile fileTree(dir: 'lib', include: '*.jar')
compile fileTree(dir: 'play-1.2.4/framework/lib', include: '*.jar')
compile fileTree(dir: 'play-1.2.4/framework', include: 'play-*.jar')
}
//MOVE this into allprojects to be run by both toneserver and webserver to put a file there...
task versionFile() << {
File f = new File('webserver/output/version');
f.mkdirs()
File v = new File(f, 'version'+project.ext.realVersion)
println('output version file='+v.getAbsolutePath())
v.createNewFile()
}
task zip(type: Zip) {
archiveName 'dashboard-'+project.version+'.zip'
from('output/version') {
into('webserver')
}
from('..') {
exclude '**/*.pyc'
exclude '**/*.class'
exclude '**/samples-and-tests/**'
exclude '**/play-1.2.4/documentation/**'
exclude 'webserver/conf/logback.xml'
include 'webserver/run*.sh'
include 'webserver/lib/**'
include 'webserver/app/**'
include 'webserver/conf/**'
include 'webserver/play-1.2.4/**'
include 'webserver/public/**'
}
rename 'prod.(.*)', '$1'
}
zip.dependsOn('versionFile')
zip.dependsOn('jar')
assemble.dependsOn('zip')
//playframework has it's own generation of .classpath and .project fils so do not
//overwrite their versions. NEED to call "play.bat eclipsify" here...
task eclipse(overwrite: true) << {
if (System.properties['os.name'].toLowerCase().contains('windows')) {
println "*** WINDOWS "
def result = exec {
commandLine 'cmd', '/c', 'play-1.2.4\\play.bat eclipsify'
}
} else {
println "*** NOT WINDOWS "
def result = exec {
commandLine './play-1.2.4/play eclipsify'
}
}
}
}
project(':toneserver') {
project.ext.genLibDir = file('output/thirdpartylibs')
configurations {
all*.exclude module: 'log4j'
}
dependencies {
compile 'com.google.inject:guice:3.0'
compile 'com.google.protobuf:protobuf-java:2.4.1'
//weird, why is their maven not working(we drop it in the directory instead)...
//compile 'org.asteriskjava:asterisk-java:1.0.0.M3'
//to be erased as soon as we get the chance...(we should try this NOW and see if it is needed anymore)
compile 'commons-configuration:commons-configuration:1.8'
compile 'org.bouncycastle:bcpg-jdk16:1.46'
compile project(':webserver')
//gradle is not sucking in transitive dependencies when they exist in another project so we suck them
//in ourselves here...
compile fileTree(dir: '../webserver/play-1.2.4/framework/lib', include: '*.jar')
compile fileTree(dir: '../webserver/lib', include: '*.jar')
compile fileTree(dir: '../webserver/play-1.2.4/framework', include: 'play-*.jar')
compile 'org.bouncycastle:bcpg-jdk16:1.46'
testCompile 'junit:junit:4.11'
}
task generateSources {
project.ext.outputDir = file("$buildDir/generated-src")
outputDir.exists() || outputDir.mkdirs()
if (System.properties['os.name'].toLowerCase().contains('windows')) {
println "*** WINDOWS "
def result = exec {
commandLine 'cmd', '/c', '..\\tools\\protoc\\protoc.exe', '--java_out=output\\generated-src', 'src\\schemas\\agentbridge.proto'
}
} else {
throw new RuntimeException("DARN, protoc only works on windows :( :( right now")
}
}
compileJava.dependsOn("generateSources")
sourceSets {
main {
java {
srcDir 'output/generated-src'
}
}
}
tasks.eclipse.dependsOn("generateSources")
task copyJars(type: Copy) {
from(configurations.compile) {}
into genLibDir
}
task initconfig(type:Copy) {
from('src/staging/toneserver') {
include '**/*'
}
into 'output/staging'
}
task zip(type: Zip) {
archiveName 'toneserver-'+project.version+'.zip'
from('src/staging') {
include 'toneserver/**'
}
from('output/thirdpartylibs') {
into('toneserver/lib')
}
from('output/version') {
into('webserver')
}
}
zip.dependsOn('copyJars')
zip.dependsOn('jar')
assemble.dependsOn('zip')
}
//overwrite the eclipse target so that no .classpath ends up in stserver directory
task eclipse(overwrite: true) {
}
gradle tasks --all shows all tasks, but only first-level task dependencies. I agree that it would be useful to have a way to visualize the whole task graph, but it's not something that Gradle currently offers out-of-the-box.

Resources