How can I conditionally run code if a Gradle plugin is applied?
Asked Answered
P

3

12

I have a script plugin that I would like to:

  • Check if the ivy-publish applied (via apply plugin: ivy-publish):
  • If it is applied, declare publishing { repositories { ivy { } } }
  • If it's not applied, run some other code

However, I'm unsure of how to actually run code if the ivy-publish plugin is applied, and I couldn't find anything about that in the documentation. Is there any way to do this?

Principium answered 13/9, 2017 at 18:36 Comment(0)
C
19

You can use the PluginManager.withPlugin(String id, Action<? super AppliedPlugin> action) method. From the Javadoc:

If a plugin with the specified ID has already been applied, the supplied action will be executed immediately. Otherwise, the action will executed immediately after a plugin with the specified ID is applied.

In your build script you could do something like:

pluginManager.withPlugin('ivy-publish') {
  // Do configuration
}
Chrissa answered 14/9, 2017 at 0:38 Comment(2)
While both answers are helpful, this one actually wound up being more useful for what we were doing, so I've chosen to accept this.Principium
actually I don't see that this works when writing your own plugins but is evaluated too early, i.e. no project is found and nothing is appliedChucho
C
5

You can always use findPlugin:

println project.plugins.findPlugin('ivy-publish')
Consensus answered 14/9, 2017 at 7:7 Comment(3)
There's a problem with findPlugin - if a plugin is applied later in the script findPlugin will fail to find it.Des
@Des check it in afterEvaluate then.Consensus
If there are at least two plugins doing this there's really no difference.Des
B
1

Or use:

if (project.getPluginManager().hasPlugin("ivy-publish")) {
    ..
}
Buckboard answered 16/4, 2021 at 9:20 Comment(1)
The same problem as in @Opal's answer - this is an eager API.Des

© 2022 - 2024 — McMap. All rights reserved.