在执行Gradle任务时如何通过命令行传递Kotlin freeCompilerArgs ?



上下文:这个问题涉及到一个Android应用程序的项目,该项目使用Jetpack Compose作为UI,主要侧重于通过命令行生成Compose编译器指标。


我的根项目的gradle配置如下:

subprojects {
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
kotlinOptions {
// Trigger this with:
// ./gradlew assembleRelease -PenableComposeReports=true
if (project.findProperty("enableComposeReports") == "true") {
freeCompilerArgs += ["-P", "plugin:androidx.compose.compiler.plugins.kotlin:reportsDestination=" + rootProject.buildDir.absolutePath + "/compose_metrics/"]
freeCompilerArgs += ["-P", "plugin:androidx.compose.compiler.plugins.kotlin:metricsDestination=" + rootProject.buildDir.absolutePath + "/compose_metrics/"]
}
}
}
}

当我使用以下命令执行assembleReleasegradle任务时:

适当设置./gradlew assembleRelease -PenableComposeReports=true,freeCompilerArgs以生成Compose编译器指标。


现在,我想知道是否有可能在执行gradle任务本身时通过CLI传递这些freeCompilerArgs,而没有任何特定的gradle配置来生成Compose Compiler Metrics。

我正在尝试构建一个CLI工具,生成撰写编译器指标作为其功能的一部分,我希望能够在任何任意Jetpack撰写项目上运行它,无论gradle是否配置为生成撰写编译器指标(如上所述)。


是否可以通过CLI传递这些freeCompilerArgs ?,例如:

./gradlew assembleRelease -Pkotlin.compiler.arguments="plugin:androidx.compose.compiler.plugins.kotlin:reportsDestination=<path>”

如果没有,是否有其他方法可以通过CLI为任意项目(可能或可能没有Gradle配置生成相同的)生成编译器度量?

这个问题可以使用Gradle Init脚本来解决。

初始化脚本(又名init脚本)与其他脚本类似Gradle中的脚本。但是,这些脚本在构建之前运行开始。

因此,我们可以执行gradletaskgradleinit script,这可以配置gradle以启用生成Compose编译器指标。


// init.gradle
initscript {
repositories {
mavenCentral()
google()
}
dependencies {
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.0")
classpath("com.android.tools.build:gradle:7.4.2")
}
}
allprojects {
afterEvaluate {
tasks.configureEach {
if (it.class.name.contains("org.jetbrains.kotlin.gradle.tasks.KotlinCompile")) {
kotlinOptions {
freeCompilerArgs += ["-P", "plugin:androidx.compose.compiler.plugins.kotlin:reportsDestination=" + rootProject.buildDir.absolutePath + "/reports/"]
freeCompilerArgs += ["-P", "plugin:androidx.compose.compiler.plugins.kotlin:metricsDestination=" + rootProject.buildDir.absolutePath + "/metrics/"]
}
}
}
}
}

并像执行./gradlew assembleRelease -I init.gradle一样执行gradle task以生成Compose编译器指标。


在多个不同的线程中询问这个问题后,这是迄今为止我对这个特定问题的唯一解决方案。

非常感谢Nikita Skvortsov在另一个帖子中回答了这个问题,所有的功劳都归功于他们提出了这个解决方案。另外,感谢Björn Kautler帮助我正确设置init.gradle脚本。