简体   繁体   中英

Apply a gradle plugin (errorprone) from a custom Gradle Java plugin

I need to apply a gradle plugin, in this case errorprone from a custom Gradle plugin.

My Plugin has a build.gradle that looks like this:

gradlePlugin {
    plugins {
        myErrorprone {
            id = 'my-errorprone'
            implementationClass = 'com.my.MyErrorpronePlugin'
        }
    }
}

And the plugin code is:

public class MyErrorpronePlugin implements Plugin<Project> {
  List<String> compilerArgs =
      Arrays.asList(
          "-XepExcludedPaths:.*/proto/.*|.*/protoGeneratedSrc/.*",
          "-XepDisableWarningsInGeneratedCode");

  @Override
  public void apply(Project project) {
    project.getPluginManager().apply("net.ltgt.errorprone:");
    for (JavaCompile task : project.getTasks().withType(JavaCompile.class)) {
      task.getOptions().setCompilerArgs(compilerArgs);
    }
  }
}

Then, when in another project I apply this plugin (after getting the dependencies in the buildscript) like this:

apply plugin: 'my-errorprone'

A problem occurred evaluating root project 'my-project.

Failed to apply plugin [id 'my-errorprone'] Plugin with id 'net.ltgt.errorprone' not found.

And it only resolved if i add to buildscript classpath

classpath "net.ltgt.gradle:gradle-errorprone-plugin:0.0.16"

How can I make my plugin work in such way that the project that consumes my plugin will not have to add this direct dependency in the classpath in "net.ltgt.gradle:gradle-errorprone-plugin:0.0.16" ?

In order to solve it, one should apply the plugin by class rather than by ID. This will force you to include error prone dependency in your plugin's dependency list as it won't compile until you add the dependency.

import net.ltgt.gradle.errorprone.ErrorPronePlugin.class;

public class MyPlugin implements Plugin<Project> {
   public void apply(Project project) {
       project.getPluginManager().apply(ErrorPronePlugin.class);
       // custom logic here 
   } 
} 

and in the build.gradle file:

repositories {
   maven {
      url "https://plugins.gradle.org/m2/"
   }
} 
dependencies {
   api "net.ltgt.gradle:gradle-errorprone-plugin:1.1.1"
} 

I found the answer in Gradle's forum under this topic: https://discuss.gradle.org/t/apply-a-gradle-plugin-errorprone-from-a-custom-gradle-java-plugin/34645/4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM