Jacky
Jacky

Reputation: 8935

Gradle dependency does not work as my expectation

I have two sub projects subproject1 and subproject2. I'd like to add some classes from subproject2 to subproject1 and get the subproject1.jar. Below is my gradle file:

task copyClasses (dependsOn: [  ':subproject1:clean',  ':subproject1:classes']) {
    println "copyClasses "
    doLast {
        Task study = tasks.getByPath(':subproject1:jar')
        study.doFirst {
            copy {
                println "copy ... "
                println sourceSets.main.output.classesDir
                println project(':subproject1').sourceSets.main.output.classesDir
                from sourceSets.main.output.classesDir
                into project(':subproject1').sourceSets.main.output.classesDir
            }
        }
    }
}

task jarUpdated (dependsOn: [ clean, classes, copyClasses, ':subproject1:jar']) {
    doLast {
        println "jarUpdated"
    }
}

But I got the build sequence as below:

$ gradle jarUpdated
copyClasses
:subproject1:compileJava
:subproject1:processResources UP-TO-DATE
:subproject1:classes
:subproject1:jar
:subproject2:compileJava
:subproject2:processResources UP-TO-DATE
:subproject2:classes
:subproject2:clean
:subproject1:clean
:subproject2:copyClasses
Calling Task.doFirst(Closure) after task execution has started has been deprecated and is scheduled to be removed in Gradle 2.0. Check the configuration of task ':subproject1:jar'.
:subproject2:jarUpdated
jarUpdated

BUILD SUCCESSFUL

My expectation is:

$ gradle jarUpdated
:subproject2:clean 
:subproject2:compileJava
:subproject2:processResources UP-TO-DATE
:subproject2:classes
:subproject1:clean 
:subproject1:compileJava
:subproject1:processResources UP-TO-DATE
:subproject2:copyClasses
copyClasses
copy ... 
:subproject1:jar 
:subproject2:jarUpdated
jarUpdated

BUILD SUCCESSFUL

Would you please suggest or point out what I missed? Thanks a lot!

Upvotes: 2

Views: 439

Answers (1)

Perryn Fowler
Perryn Fowler

Reputation: 2232

The "easiest" way to do exactly what you asked for is probably something like this in your subproject1 build file.

jar {
  from  tasks.getByPath(':subproject2:compileJava')
}

However this is a very simplistic approach with a LOT of caveats, for example

  • Subproject 1 can not compile against subproject 2 classes
  • Any dependencies of Subproject 2 will not be included
  • etc

I would actually advise declaring subproject2 as a dependency of subproject1 and using one of the plugins that Peter suggested.

Upvotes: 1

Related Questions