4

所以我一直在玩 gradle 的 kotlin dsl,我的 buildscript 已经发展到我想引入自定义任务以更好地组织的地步。

这是我的MWEbuild.gradle.kts

open class CustomTask : DefaultTask() {
  var dir = File(".")

  @TaskAction
  fun action() {
    println("CustomTask.dir: ${dir.absolutePath}")
  }
}
tasks.create<CustomTask>("debug") {
  //dir = File(".gradle") // Script compilation fails if I uncomment this line
}

tasks.create("traverseDir") {
  doLast {
    traverseDir(File("gradle/wrapper/gradle-wrapper.jar"))
  }
}
fun traverseDir(file: File) {
  var dir: File? = file.parentFile
  while (dir != null) {
    println(dir)

    dir = dir.parentFile
  }
}

没有任务配置的输出./gradlew debug traverseDir(意思是注释目录分配):

> Task :debug
CustomTask.dir: /home/.../gradle-kotlin_dsl-smart_cast_error/.

> Task :traverseDir
gradle/wrapper
gradle

BUILD SUCCESSFUL in 0s
2 actionable tasks: 2 executed

带有任务配置的输出./gradlew debug traverseDir(意味着未注释的目录分配):

> Configure project :
e: /home/.../gradle-kotlin_dsl-smart_cast_error/build.gradle.kts:32:11: Smart cast to 'File' is impossible, because 'dir' is a local variable that is captured by a changing closure

FAILURE: Build failed with an exception.

* Where:
Build file '/home/.../gradle-kotlin_dsl-smart_cast_error/build.gradle.kts' line: 32

* What went wrong:
Script compilation error:

  Line 32:     dir = dir.parentFile
                     ^ Smart cast to 'File' is impossible, because 'dir' is a local variable that is captured by a changing closure

1 error

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 0s

这两个任务彼此没有联系(除了它们在同一个构建脚本文件中定义),但是当我尝试配置我的自定义任务的实例(即取消注释该dir = ...行)时,构建失败,因为脚本编译错误- 看似无关的 - traverseDir 函数。

进一步的怪异:

  • dir如果我重命名任何一个变量(即为),则不会发生错误dir_- 然后构建成功。
  • 将行更改dir = dir.parentFiledir = dir?.parentFile使构建成功。

为什么会这样?


输出./gradlew --version

------------------------------------------------------------
Gradle 4.10
------------------------------------------------------------

Build time:   2018-08-27 18:35:06 UTC
Revision:     ee3751ed9f2034effc1f0072c2b2ee74b5dce67d

Kotlin DSL:   1.0-rc-3
Kotlin:       1.2.60
Groovy:       2.4.15
Ant:          Apache Ant(TM) version 1.9.11 compiled on March 23 2018
JVM:          1.8.0_181 (Oracle Corporation 25.181-b13)
OS:           Linux 4.15.0-33-generic amd64

更新

这似乎是一个错误,我在以下方面创建了问题:

4

0 回答 0