如何在 Gradle 插件中表达项目依赖?

How to express a project dependency in a Gradle plugin?

我正在写一个Gradle插件,我想添加一些对其他项目的依赖。我如何在插件代码中表达它?

对于普通的依赖,它是project.dependencies.add("implementation", "my.dependency.name")

在 Gradle Kotlin DSL 中,我会这样做

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

如何在我的插件中表达这两个?

Gradle Build Language Reference文档中我们可以看到:

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. [...]

这告诉我们,当您在构建脚本中使用 project(":myproject") 时,您实际上是在调用 Project#project(String)。考虑到这一点,您应该能够在插件实现中简单地使用相同的方法:

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

kotlin("stdlib-jdk8")稍微复杂一点,但不多。当您使用该“语法”时,您实际上是在调用 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()
}

总而言之,您的插件代码可能类似于:

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"))
        }
    }
}