user8681
user8681

Reputation:

How to express a project dependency in a Gradle plugin?

I'm writing a Gradle plugin, and I want to add some dependencies on other projects. How do I express that in the plugin code?

For normal dependencies, it's project.dependencies.add("implementation", "my.dependency.name")

In the Gradle Kotlin DSL, I would do

    implementation(kotlin("stdlib-jdk8"))
    implementation(project(":myproject"))

How do I express those two in my plugin?

Upvotes: 1

Views: 1477

Answers (1)

Slaw
Slaw

Reputation: 45806

From the Gradle Build Language Reference documentation we can see:

Some basics

There are a few basic concepts that you should understand, which will help you write Gradle scripts.

First, Gradle scripts are configuration scripts. As the script executes, it configures an object of a particular type. For example, as a build script executes, it configures an object of type Project [emphasis added]. This object is called the delegate object of the script. [...]

This tells us that when you use project(":myproject") in the build script you are actually invoking Project#project(String). With that in mind, you should be able to simply use the same method in your plugin implementation:

project.dependencies.add("implementation", project.project(":myproject"))

The kotlin("stdlib-jdk8") is a little more complicated, but not by much. When you use that "syntax" you're actually invoking the DependencyHandler.kotlin extension function. You get a DependencyHandler instance when you invoke project.dependencies. However, to make that extension function available to your plugin code you need to add the Kotlin DSL API to your plugin's dependencies. This is made easier with the Kotlin DSL Plugin:

plugins {
    `kotlin-dsl`
}

repositories {
    jcenter()
}

Altogether, your plugin code might look something like:

import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.kotlin

class FooPlugin : Plugin<Project> {

    override fun apply(target: Project) {
        // Apply plugin which adds "implementation" configuration?
        target.dependencies.apply {
            add("implementation", target.project(":myproject"))
            add("implementation", kotlin("stdlib-jdk8"))
        }
    }
}

Upvotes: 3

Related Questions