メインコンテンツまでスキップ

Gradle plugin variantsのサポート

Gradle 7.0では、Gradleプラグインの作成者向けの新機能であるplugins with variantsが導入されました。 この機能により、古いGradleバージョンとの互換性を維持しながら、最新のGradle機能のサポートを簡単に追加できます。 詳しくは、variant selection in Gradleをご覧ください。

Gradle plugin variantsを使用すると、Kotlinチームは、異なるGradleバージョンに対して異なるKotlin Gradle plugin (KGP) variantsを提供できます。 その目標は、Gradleのサポート対象の最も古いバージョンに対応するmain variantで、ベースとなるKotlinコンパイルをサポートすることです。各variantには、対応するリリースからのGradle機能の実装が含まれます。最新のvariantは、最新のGradle機能セットをサポートします。このアプローチにより、機能が制限された古いGradleバージョンのサポートを拡張することが可能です。

現在、Kotlin Gradle pluginには以下のvariantsがあります。

Variant's nameCorresponding Gradle versions
main7.6.0–7.6.3
gradle808.0–8.0.2
gradle818.1.1
gradle828.2.1–8.4
gradle858.5 and higher

将来のKotlinリリースでは、さらにvariantsが追加される予定です。

ビルドで使用するvariantを確認するには、--info log levelを有効にして、出力内のUsing Kotlin Gradle pluginで始まる文字列(例:Using Kotlin Gradle plugin main variant)を見つけてください。

Troubleshooting

Gradleがカスタム構成でKGP variantを選択できない

これは、Gradleがカスタム構成でKGP variantを選択できない場合に想定される状況です。 カスタムGradle構成を使用する場合:

configurations.register("customConfiguration") {
// ...
}

たとえば、Kotlin Gradle pluginへの依存関係を追加したい場合は、以下のようにします。

dependencies {
customConfiguration("org.jetbrains.kotlin:kotlin-gradle-plugin:2.1.20")
}

customConfigurationに次の属性を追加する必要があります。

configurations {
customConfiguration {
attributes {
attribute(
Usage.USAGE_ATTRIBUTE,
project.objects.named(Usage.class, Usage.JAVA_RUNTIME)
)
attribute(
Category.CATEGORY_ATTRIBUTE,
project.objects.named(Category.class, Category.LIBRARY)
)
// If you want to depend on a specific KGP variant:
attribute(
GradlePluginApiVersion.GRADLE_PLUGIN_API_VERSION_ATTRIBUTE,
project.objects.named("7.0")
)
}
}
}

そうしないと、次のようなエラーが発生します。

 > Could not resolve all files for configuration ':customConfiguration'.
> Could not resolve org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.0.
Required by:
project :
> Cannot choose between the following variants of org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.0:
- gradle70RuntimeElements
- runtimeElements
All of them match the consumer attributes:
- Variant 'gradle70RuntimeElements' capability org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.0:
- Unmatched attributes:

What's next?

Learn more about Gradle basics and specifics.