Andrew Charneski
Andrew Charneski

Reputation: 488

How to copy a jar produced by one Gradle sub-project into another in a single build

A multi-project Gradle build (minimal reproduction below) seems to be unable to pick up a jar file from one project and import it as a jar file in another when using a copy task.

Build file:

buildscript {
    repositories {
        maven {
            url "https://plugins.gradle.org/m2/"
        }
    }
    dependencies {
        classpath "gradle.plugin.com.dorongold.plugins:task-tree:1.5"
    }
}

subprojects { subproject ->
    subproject.apply plugin: com.dorongold.gradle.tasktree.TaskTreePlugin
}

project(":jarBuild") {
    apply plugin: "java"
}

project(":assemblyBuild") {
    apply plugin: "maven"
    configurations {
        compile
    }
    dependencies {
        compile(project(path: ":jarBuild"))
    }
    task copyFiles {
        copy {
            from configurations.compile
            into buildDir
        }
    }
    copyFiles.dependsOn(project(':jarBuild').tasks.assemble)
    build.dependsOn(copyFiles)
}

task clean
clean.dependsOn(subprojects.collect { it.tasks.matching { it.name == "clean" } })

This command demonstrates the issue:

gradle clean && gradle build && find . -name '*.jar' && gradle build && find . -name '*.jar'

Command Output:

BUILD SUCCESSFUL in 594ms
2 actionable tasks: 2 executed

BUILD SUCCESSFUL in 617ms
1 actionable task: 1 executed
./jarBuild/build/libs/jarBuild.jar

BUILD SUCCESSFUL in 590ms
1 actionable task: 1 up-to-date
./assemblyBuild/build/jarBuild.jar
./jarBuild/build/libs/jarBuild.jar

After the first build, there is no jar packaged in the build directory of assemblyBuild. On the second run of build the jar IS copied.

Proper task dependency has been verified:

gradle :assemblyBuild:build taskTree

> Task :assemblyBuild:taskTree

------------------------------------------------------------
Project :assemblyBuild
------------------------------------------------------------

:assemblyBuild:build
+--- :assemblyBuild:assemble
+--- :assemblyBuild:check
\--- :assemblyBuild:copyFiles
     \--- :jarBuild:assemble
          \--- :jarBuild:jar
               \--- :jarBuild:classes
                    +--- :jarBuild:compileJava
                    \--- :jarBuild:processResources

I have tried many different variations on this approach, including copying the jar file by referencing the direct path, to no avail.

Upvotes: 0

Views: 1532

Answers (1)

Andrew Charneski
Andrew Charneski

Reputation: 488

I figured it out. The copy command was being executed during task configuration, not execution. Replacing that task definition with this worked:

    task copyFiles {
        doLast {
            copy {
                from configurations.compile
                into buildDir
            }
        }
    }

Upvotes: 2

Related Questions