Share configuration dependencies using extendsFrom with control over order - gradle

Received this warning in my gradle build this morning, and trying to figure out how to solve it
Adding a Configuration as a dependency is a confusing behavior
which isn't recommended. This behaviour has been deprecated
and is scheduled to be removed in Gradle 8.0. If you're
interested in inheriting the dependencies from the
Configuration you are adding, you should use extendsFrom
Following up on this answer... I was using the configuration as a dependency approach so I could control ordering.
For example:
configurations {
A
B {
extendsFrom A
}
}
dependencies {
A 'jar1'
B 'jar2'
}
Seems to result in the order of B's path being jar1;jar2
But if I want B to be like A, but override some classes from A, then I need B's dependencies first.
So I was using this approach:
configurations {
A
B
}
dependencies {
A 'jar1'
B 'jar2'
B A
}
Which results in B's path being jar2;jar1
I couldn't figure out a way to get this to work using extendsFrom.
Mainly I tried to use B.extendsFrom(A) with various syntax in the dependencies section but couldn't get that to compile.
Is there a way to get the override/ordering use-case to work using extendsFrom?

I believe it's not possible with extendsFrom.
I am not an expert on the dependencies area, but what could work for you or give you some ideas is something like:
def a = project.configurations.findByName("A")
def b = project.configurations.findByName("A")
b.getIncoming().beforeResolve {
// If you want to get also dependencies from
// configurations that "A" extends use getAlLDependencies
a.getDependencies().forEach{
b.dependencies.add(it)
}
}
Note: getDependencies() and getAllDependencies() don't return resolved dependencies, but just the dependencies that were added to a configuration in build script (e.g. A 'jar1'). If you want resolved dependencies you have to resolve A.
Note2: I don't recommend class shadowing as I think you want to achieve. It can bring a lot of unexpected troubles, e.g. app could compile but might not work at runtime. Maybe you should rather do a dependency substitution or resolve conflicts with capabilities (https://docs.gradle.org/7.2/userguide/dependency_capability_conflict.html#sub:declaring-component-capabilities).

Related

How do I include a project dependency with a classifier

I have a sub-project with a classifier, test-fixtures, that I want to include into an adjacent sub-project:
dependencies {
implementation(project(":producer"))
}
I assumed that would be a trivial task, but I can't seem to find out how. Is that possible?
I found that this was not a classifier in the maven sense. The variant (what gradle calls them) was created by the java-test-fixtures-plugin. See user guide on testing.
It is used by importing the dependency like this:
dependencies {
testFixtures(project(":producer"))
}
I had a little problem on this since this inhibits my freedom to select the configuration I needed in order to include this jar in an ear-file. I found a way around this by adding it manually as the earlib(...)-method actually does:
dependencies {
add("earlib", testFixtures(project(":producer")))
}

Is it possible to make a doubly-inherited custom task in Gradle?

I'm working on a Gradle (Groovy, not Kotlin) library using a bunch of external libraries, and we have a case where we want to implement double-inheritance in our code off of a custom Task provided by an external library. (For reference, that library is specifically the MarkLogic DataHub, and we're extending RunFlowTask, but I've generalized a bit for this example. There are a few restrictions that introduces, but I'm fairly certain all of them can be worked around.)
What I want is the following:
ClassA.gradle
class ClassA extends com.external.plugin.TaskA {}
ClassB.gradle
import com.fasterxml.jackson.databind.ObjectMapper
class ClassB extends ClassA {}
...with no restrictions on where things need to be, just that it works. Worth noting that we have a bunch of examples like ClassA that work on their own, I just need to extend ClassA again.
I've detailed a few attempts I made to get this to work below; any feedback on what I did wrong with any of them is more than welcome, or if there's any advice on an entirely new way to build things, that's totally appreciated as well.
First attempt:
apply from: './ClassA'
apply from: './ClassB'
=>
'unable to resolve class ClassA' in ClassB.gradle, which makes enough sense given what I know about how Gradle compilation works. I tried replacing class ClassB... with println ClassB just to see, and that printed without an issue. Made me think that ClassA needed to be compiled in advance, so I'm pretty sure there's nothing I'm doing wrong here, it just won't work.
Second attempt:
buildSrc/src/main/groovy/ClassA.gradle exists and is the same as above.
buildSrc/build.gradle
import com.fasterxml.jackson.databind.ObjectMapper
buildscript {
repositories { }
dependencies {
classpath fileTree(dir: '/path/to/dependencies', include: '*.jar') // includes jackson
}
}
println ObjectMapper
The println worked, but I get:
/path/to/src/main/groovy/ClassA.groovy: 1: unable to resolve class com.fasterxml.jackson.databind.ObjectMapper
# line 1, column 1.
import com.fasterxml.jackson.databind.ObjectMapper
...and the same thing if I duplicate the buildscript block into the ClassA submodule, or if I remove the import from the ClassA submodule. My question for this is is there anything I'm doing wrong with the imports? Seems like this should work and the imports should just work, but they're not.
Third attempt:
Sparing a few code examples here: I got everything very close to working with copying buildSrc into an includeBuild folder, and ClassA is accessible as a TaskReference in the top-level project, but I don't know how to to actually extend ClassA from there.
gradle.includedBuild('subbuild').task(':ClassA') => org.gradle.composite.internal.IncludedBuildTaskReference
gradle.includedBuild('subbuild').task(':UPMCRunFlowTask').resolveTask() => Task with path ':ClassA' not found in project ':subbuild'.
My question for this is is there a way to dig back to the class reference so it's actually extendable? I tried digging into setting up an include './subbuild' subproject and ran into similar issues.
Any help/advice is welcome - thanks!
Answer was on the second attempt. In build.gradle, it needed to be:
repositories {}
dependencies {
implementation fileTree(dir: '/path/to/deps', include: ['*.jar'])
}
...and nothing needed to be in the sub-files.

Get the project instance from kotlin's gradle

I'm trying to migrate a script from Groovy's gradle to Kotlin's gradle.
The function:
def Group(Closure closure) {
closure.delegate = dependencies
return closure
}
ext {
aGroup = Group {
implementation xyz
kapt xpto
...
}
...
}
What I manage to do:
object Group {
operator fun <T> invoke(project: Project, closure: Closure<T>):Closure<T> {
closure.delegate = project.dependencies
return closure
}
}
Notice that I've added the extra arg Project.
Groovy access the project property directly, I would like to know how can I get this directly from kotlin too, so I'll be able to remove that extra arg and keep the previous syntax.
Short answer: You can't
Long answer:
You can't due to the strong/statically typed nature of Kotlin (and Java). Groovy is a dynamic language and lets you get away with many things, to an extent. In addition to the dynamic nature of Groovy, Gradle implements a lot of the metaprogramming that Groovy offers.
So even though you do not explicitly pass in a Project in your Groovy script, behind the scenes it is being looked up dynamically.
You could make Group an extension of Project to have a reference of project.

Child build.gradle not evaluating at afterEvaluate event

I have a project with 21 subprojects. one of those subprojects has its own build.gradle file because its a little obscure.
Now, i have a configuration setting in the build that is needed during the config phase. So, in my plugin i have
project.afterEvaluate {
if (project == project.rootProject) {
project.allprojects.each { proj ->
MetaExtension config = proj.getExtensions().getByType(MetaExtension)
if (config.inventoryHash == null){
throw new ProjectHashNotSetException(proj.name)
}
}
}
}
Now, if i have everything in one build.gradle file, it all works perfectly. but, as soon as i broke the 21st subproject into its own build.gradle file, it now always comes back as null. copy and past back into one build.gradle file, works fine, 2 gradle files, fails.
Why would this be?
afterEvaluate is a method of the project and is evaluated after the project is evaluated, not after all projects are evaluated.
You need to restructure your logic. You could e. g. add an evaluationDependsOnChildren() or evaluationDependsOn '21st-project', then you don't need the afterEvaluate at all.
Actually if the shown code is your actual code, it is a bit strange anyway. You add an afterEvaluate action to all projects, but only execute it if it is the root project. You could as well just add the action to the root project and then leave out the condition. Or maybe even better, just add an afterEvaluate to each project that checks exactly that project like
project.afterEvaluate {
MetaExtension config = extensions.getByType(MetaExtension)
if (!config.inventoryHash) {
throw new ProjectHashNotSetException(name)
}
}
Then the evaluation order is not important, as each is checked individually. This is also better for project decoupling if you e. g. ever want to use configure-on-demand which would not be possible with your approach.

Referencing the outputs of a task in another project in Gradle

Consider the following setup
rootProject
|--projectA
|--projectB
There is a task taskB in projectB and I would like the reference the outputs of that task in a copy task taskA in projectA. For example, taskA might look something like:
task taskA(type: Copy) {
dependsOn ':projectB:taskB'
from ':projectB:taskB.outputs'
into 'someFolder'
}
Of course the above example doesn't actually work. While it's okay to reference the task as :projectB:taskB as a dependency, :projectB:taskB.outputs doesn't seem to mean anything to Gradle. I've tried reading through the Gradle docs but didn't find anything that referenced what I'm trying to do.
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'
}

Resources