Referencing the outputs of a task in another project in Gradle

The accepted answer has been to only and recommended way to solve this problem. However building up this kind of project dependencies and reaching from one project into another is discouraged by the Gradle team now. Instead of this, projects should only interact with each others using publication variants. So the idiomatic (but sadly at the moment more verbose) way would be:

On the producing side (projectB) define a configuration that is not resolvable but consumable by other projects and creates a new variant (called taskB-variant)

configurations.create("taskElements") {
    isCanBeResolved = false
    isCanBeConsumed = true
    attributes {
        attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage::class, "taskB-variant"))
    }
    outgoing.artifact(taskB.outputs)
}

On the consuming side (projectA) define a configuration that is resolvable but not consumable for the same variant and define a dependency to projectB

val taskOutputs by configurations.creating {
    isCanBeResolved = true
    isCanBeConsumed = false
    attributes {
        attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage::class, "taskB-variant"))
    }
}

dependencies {
    taskOutputs(project(":projectB"))
}

tasks.register<Copy>("taskA") {
    from taskOutputs
    into 'someFolder'
}

This way you decouple how the outputs are produced and the publication variant (called "taskB-variant") becomes the interface between projectA and projectB. So whenever you change the way the output is created you only need to refactor projectB but not projectA as long as you make sure the outputs end up in the taskElements configuration.

At the moment this is still pretty verbose but hopefully Gradle will get more powerful APIs to describe this kind of project relationships in the future.


projectA build.gradle should be:

evaluationDependsOn(':projectB')

task taskA(type:Copy, dependsOn:':projectB:taskB'){
    from tasks.getByPath(':projectB:taskB').outputs
    into 'someFolder'
}

Tags:

Gradle