Pood1331
Pood1331

Reputation: 235

How to apply a Gradle plugin from another plugin?

I'm trying to encapsulate android plugin in my own plugin, but when I'm trying to apply my plugin build fails with an exception:

A problem occurred evaluating root project 'myproj'.
> Failed to apply plugin [id 'com.mycomp.build']
  > Failed to apply plugin [id 'android-library']
    > Plugin with id 'android-library' not found.

Here is how I'm applying android plugin inside my own plugin's implementation:

// build.gradle
apply plugin: 'groovy'

version = '1.0'
group = 'com.mycomp'

dependencies {
    compile gradleApi()
    compile localGroovy()
}

// Build.groovy
package com.mycomp

import org.gradle.api.Plugin
import org.gradle.api.Project

class Build implements Plugin<Project> {
    void apply(Project project) {
        println 'Hello from com.mycomp.Build'
        project.beforeEvaluate {
            buildscript.configurations.classpath += 
                'com.android.tools.build:gradle:1.0.0-rc1'
        }

        project.configure(project) {
            buildscript.repositories.mavenCentral()
            apply plugin: 'android-library'
        }
    }
}

For some reason a classpath is not being properly loaded, what am I doing wrong?

Upvotes: 16

Views: 14080

Answers (2)

Opal
Opal

Reputation: 84854

I guess that at the time you'd like to add the plugin dependencies for the build script have been already resolved, thus it won't work that way. You need to specify the plugin You'd like to apply as a script dependency itself.

It will work that way:

buildscript {
   repositories {
      mavenCentral()
   }

   dependencies {
      classpath 'com.android.tools.build:gradle:1.0.0-rc1'
   }
}


apply plugin: 'groovy'
apply plugin: Build

version = '1.0'
group = 'com.mycomp'

dependencies {
    compile gradleApi()
    compile localGroovy()
}

import org.gradle.api.Plugin
import org.gradle.api.Project

class Build implements Plugin<Project> {
    void apply(Project project) {
        project.configure(project) {
            apply plugin: 'android-library'
        }
    }
}

Now, android-plugin is found but it fails because of the fact that groovy plugin had been applied earlier and there's a conflict.

Upvotes: 11

Emil Lundberg
Emil Lundberg

Reputation: 7380

Use the project's PluginManager. For example, the war plugin pulls in the java plugin like this:

public class WarPlugin implements Plugin<Project> {
    // ...
    public void apply(final Project project) {
        project.getPluginManager().apply(org.gradle.api.plugins.JavaPlugin.class);
        // ...
    }
    // ...
}

Upvotes: 9

Related Questions