Appearance
独立插件项目
独立插件项目是可以发布到 Gradle Plugin Portal 或私有仓库的完整 Gradle 插件。
项目结构
my-gradle-plugin/
├── settings.gradle.kts
├── build.gradle.kts
└── src/
├── main/kotlin/
│ └── com/example/gradle/
│ ├── MyPlugin.kt
│ ├── MyExtension.kt
│ └── MyTask.kt
└── test/kotlin/
└── com/example/gradle/
└── MyPluginTest.ktbuild.gradle.kts
kotlin
plugins {
`kotlin-dsl`
`java-gradle-plugin`
`maven-publish`
id("com.gradle.plugin-publish") version "1.2.1"
}
group = "com.example.gradle"
version = "1.0.0"
repositories {
mavenCentral()
gradlePluginPortal()
}
dependencies {
testImplementation("org.junit.jupiter:junit-jupiter:5.10.1")
testImplementation(gradleTestKit())
}
gradlePlugin {
website.set("https://github.com/example/my-gradle-plugin")
vcsUrl.set("https://github.com/example/my-gradle-plugin")
plugins {
create("myPlugin") {
id = "com.example.my-plugin"
implementationClass = "com.example.gradle.MyPlugin"
displayName = "My Gradle Plugin"
description = "A plugin that does amazing things"
tags.set(listOf("java", "utility"))
}
}
}
tasks.named<Test>("test") {
useJUnitPlatform()
}插件实现
kotlin
// src/main/kotlin/com/example/gradle/MyPlugin.kt
package com.example.gradle
import org.gradle.api.Plugin
import org.gradle.api.Project
class MyPlugin : Plugin<Project> {
override fun apply(project: Project) {
val extension = project.extensions.create("myConfig", MyExtension::class.java)
project.tasks.register("myTask", MyTask::class.java) { task ->
task.inputProperty.set(extension.configValue)
}
}
}TestKit 测试插件
kotlin
// src/test/kotlin/com/example/gradle/MyPluginTest.kt
import org.gradle.testkit.runner.GradleRunner
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.io.File
class MyPluginTest {
@TempDir
lateinit var testProjectDir: File
@Test
fun `plugin applies correctly`() {
// 创建测试项目
File(testProjectDir, "settings.gradle.kts").writeText(
"rootProject.name = \"test-project\""
)
File(testProjectDir, "build.gradle.kts").writeText("""
plugins {
id("com.example.my-plugin")
}
""".trimIndent())
// 运行构建
val result = GradleRunner.create()
.withProjectDir(testProjectDir)
.withPluginClasspath()
.withArguments("myTask", "--stacktrace")
.build()
assert(result.output.contains("Expected output"))
}
}发布到 Gradle Plugin Portal
bash
# 需要在 gradle.properties 中配置 Portal 凭据
# gradle.publish.key=your-api-key
# gradle.publish.secret=your-api-secret
./gradlew publishPlugins