When to use plugins.withType(somePlugin).whenPluginAdded - gradle

A gradle build has several submodules. Some of them have the java plugin applied, some don't. I'm trying to configure the plugin only when it's applied. To do this, I add the following in my top-level build.gradle file:
allprojects {
plugins.withType(JavaPlugin) {
//some configuration on the JavaPlugin
}
}
However, I also noticed the following style:
allprojects {
plugins.withType(JavaPlugin).whenPluginAdded {
//some configuration on the JavaPlugin
}
}
What's the difference between the 2. When do I use the withType(){}-style configuration and when do I use the withType().whenPluginAdded{}-style?

When you use whenPluginAdded() it invokes whenObjectAdded() on the current collection. And when you call withType() and pass a Closure, it invokes all() on the current collection, which in its turn calls whenObjectAdded() on a copied collection.
So both these methods do the same thing but the former makes a defensive copy of a plugin collection.

Related

Can not add gradle DuplicatesStrategy INHERIT

In my project with gradle 7.5.1 there was a error for the following task
processResources {
with copySpec {
from "src/main/resources/"
}
}
Here is the error message. I have application.properties, application-dev.properties, application-test.properties files in my resources folder.
Entry application-dev.properties is a duplicate but no duplicate handling strategy has been set.
So I was trying to add DuplicatesStrategy like bellow
allprojects {
tasks.withType(Copy).all {
duplicatesStrategy = DuplicatesStrategy.INCLUDE
}
}
After adding this the project runs but now I need another strategy INHERIT. If I replace DuplicatesStrategy.INCLUDE with DuplicatesStrategy.INHERIT I am getting the same error again
Entry application-dev.properties is a duplicate but no duplicate handling strategy has been set
I checked(see implementation) the DuplicatesStrategy enum and INHERIT is a valid value.
package org.gradle.api.file;
public enum DuplicatesStrategy {
INCLUDE,
EXCLUDE,
WARN,
FAIL,
INHERIT;
private DuplicatesStrategy() {
}
}
How do I add duplicate strategy properly?
As I could not find the problem I decided to go with the strategy INCLUDE which is same. Duplicate Strategy has the following documentation
EXCLUDE Do not allow duplicates by ignoring subsequent items to be created at the same path.
FAIL Throw a DuplicateFileCopyingException when subsequent items are to be created at the same path.
INCLUDE Do not attempt to prevent duplicates.
INHERIT The default strategy, which is to inherit the strategy from the parent copy spec, if any, or INCLUDE if the copy spec has no parent.
WARN Do not attempt to prevent duplicates, but log a warning message when multiple items are to be created at the same path.
As my copySpec does not have any parent, I expected INCLUDE will be automatically used. But as it is not happening I decided to go for the INCLUDE instead of INHERIT.

How to add dependencies (and repositories) dynamically in a custom Gradle plugin task using Kotlin dsl

The title basically says it all.
I am trying to create a plugin that can be configured and depending on the configuration, the task provided by the plugin adds compileOnly or implementation deppendencies to the project.
The resources on writing custom Gradle plugins are abhorrent (especially in Kotlin instead of Groovy) and I can't figure out how to do this myself.
This is where I'm at with my custom plugin code:
class SpigotVersioner: Plugin<Project> {
override fun apply(project: Project) {
println("Latest spigot version: ${WebScraper.getLatestVersion()}")
val extension = project.extensions.create("spigot", SpigotExtension::class.java)
extension.apiVersion.set("latest")
extension.bukkitVersion.set("latest")
project.task("compileSpigotAPI") {
it.group = "spigot"
it.description = "Adds the spigot api implementation to the project."
it.doLast {
val apiVersion = extension.apiVersion.get()
val dependency = deriveDependencyStr(apiVersion)
//DOESN'T WORK!
project.dependencies {
compileOnly(dependency)
}
//WHAT ARE THESE PARAMETERS SUPPOSED TO BE?
project.dependencies.add(configurationName: String, dependencyNotation: Any)
}
}
}
}
This is supposed to mimic something like
dependencies {
compileOnly 'my.derived.dependency.str:apiVersion:xy'
}
only the dependency being added is supposed to be configurable via an extension.
If possible, I'd like to extend this to also add the appropriate repository as well but the dependency issue is more important.
Bit of an old question now, but I too struggled with this so hopefully this answer is of use to someone.
//WHAT ARE THESE PARAMETERS SUPPOSED TO BE?
project.dependencies.add(configurationName: String, dependencyNotation: Any)
The configurationName is the configuration that you wish to add the dependency to e.g. implementation, testImplementation or api etc.
The dependencyNotation can be any of the following:
String Notation: Simply a String written using Gradle dependency notation e.g. com.mycompany:my-awesome-dependency:1.2.3. There are ways to also specify things like strictness when using these 'simple' declarations, this is somewhat documented here.
Map Notation: This is where you pass a Map<String, String> containing key-value pairs representing the dependency. The documentation on this is either non existent or elusive, but for example: "group": "com.mycompany", "name": "my-awesome-dependency", "version": "1.2.3".
Dependency Interface: This is where you pass in an object that implements one of the Dependency interfaces that the Gradle API provides. The most basic being org.gradle.api.artifacts.Dependency. The main issue with this method is again that the documentation is either elusive or non-existent. I cannot see a way to have Gradle create one of these objects (or see any pre implemented classes in the public API). You could always just implement the interface but there are some methods on there like contentEquals and copy() which seem overkill to implement.
My recommendation if it suits your use case would be to use the first option above.

What is the difference between simple and source set dependencies when working with the Kotlin MPP plugin?

I'm using the Kotlin MPP plugin (with .kts support) and while I've been reading some code I came upon build.gradle.kts files like this:
kotlin {
sourceSets {
commonMain {
dependencies {
api(kotlinxCollectionsImmutable)
}
}
}
dependencies {
with(Libs) {
commonMainApi(kotlinStdLibCommon)
commonMainApi(kotlinxCoroutinesCommon)
}
}
}
What is the difference between declaring an api dependency within a sourceSet compared to declaring a commonMainApi dependency? Is there any?
No difference. The commonMainApi is just an alternative way of doing the same, and doesn't look to be recommended any more. Link - https://kotlinlang.ru/docs/reference/building-mpp-with-gradle.html
Альтернативным способом указания зависимостей является использование
встроенного DSL Gradle на верхнем уровне с именами конфигурации,
следующими за шаблоном : [translation:
Alternatively, dependencies can be declared by specifying
configuration names at the top level using the built-in Gradle DSL]
dependencies {
commonMainApi 'com.example:foo-common:1.0'
jvm6MainApi 'com.example:foo-jvm6:1.0'
}
Interestingly, this document is described as a translation of https://kotlinlang.org/docs/reference/building-mpp-with-gradle.html where this paragraph (about the alternative syntax) is completely missing, so one can only deduce that the English version has been updated and the alternative syntax removed as either not recommended or obsolete at this point.

Call `javaexec` from custom task (`buildSrc`), use transitive dependencies

I’ve written a custom task in Kotlin and located it inside buildSrc as recommended. The custom task calls javaexec. Something like this:
private fun custom() {
project.javaexec {
main = "com.thirdParty.something.Main"
classpath = ???
args("...")
}
}
Two questions:
Is project.javaexec the best way to call a main method from within a custom task?
How can I configure classpath such that com.thirdParty.something.Main remains a dependency of the custom task (i.e. buildSrc/build.kotlin.kts), and not the main project?

How can I decompose a Gradle build into multiple files?

I'm writing a Gradle plugin which contains a collection of multiple chunks of independent configuration which will be applied to any project applying the plugin.
I want to keep the fragments very separate to discourage other people from adding unrelated logic to an existing place, and to improve visibility of what the plugin is actually configuring.
So I thought I could do this:
class CommonChecksPlugin implements Plugin<Project> {
#Override
void apply(Project project) {
project.apply plugin: 'base'
def resolveFile = { filename ->
new URL(buildscript.sourceURI.toURL(), filename)
}
project.apply from: resolveFile('configuration1.gradle')
project.apply from: resolveFile('configuration2.gradle')
}
}
Example configurationN.gradle:
task 'checkSomething', type: CheckSomething
Problem is, this Java class CheckSomething cannot be resolved.
Is there a sensible way to do this other than just giving up and moving all the sub-scripts in as full Groovy classes? I'm reluctant to move them to classes, because I want to apply the same checks to the plugin project itself, and it seems difficult to apply them if they require compilation.
The applied script has a different classloader to the plugin, it doesn't inherit the buildscript classloader so therefore the task isn't on the classpath. You can do the following:
project.ext.CheckSomething = CheckSomething
project.apply from: resolveFile('configuration1.gradle')
See https://discuss.gradle.org/t/buildscript-configurations-classpath-not-available-in-apply-from-scripts/1391

Resources