projectDir在Gradle脚本中的任务类中是不可见的

时间:2017-07-25 11:04:13

标签: class intellij-idea groovy gradle-task

这是在IntellJ上空新创建的空Gradle / Groovy项目上设置build.gradle的示例。我在两个地方使用projectDir:在任务定义和任务类定义中。 IntelliJ向我显示第一次使用不正确 - 无法解析符号。它认为第二次使用是正确的。

group 'test'
version '1.0-SNAPSHOT'

apply plugin: 'java'
apply plugin: 'groovy'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile 'org.codehaus.groovy:groovy-all:2.3.11'
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

task ProjectDirTest(type: ProjectDirTestClass){
    println " -------------- $projectDir from task"
}

class ProjectDirTestClass extends DefaultTask {
    @TaskAction
    def greet() {
        println " -------------- $projectDir from class"
    }
}
configure(ProjectDirTest) {
    group = 'ProjectDirTest'
    description = 'ProjectDirTest'
}

但是如果我运行任务,第一个println工作正常,输出正确:

12:55:41: Executing external task 'ProjectDirTest'...
 -------------- C:\Users\543829657\testWorkspace from task
:ProjectDirTest FAILED

FAILURE: Build failed with an exception.

* Where:
Build file 'C:\Users\543829657\testWorkspace\build.gradle' line: 28

* What went wrong:
Execution failed for task ':ProjectDirTest'.
> Could not get unknown property 'projectDir' for task ':ProjectDirTest' of type ProjectDirTestClass.

但是,如您所见,在第二个println处存在问题 - Gradle没有看到projectDir变量。

我已经习惯了不正确的IntelliJ标记错误。但是如何让任务类在运行时看到projectDir变量?

在真正的任务类中我也不能使用exec()命令 - Gradle也没有看到它。

1 个答案:

答案 0 :(得分:1)

我找到了一个临时解决方案,将项目变量传递给类并用它调用所有项目变量:

task ProjectDirTest(type: ProjectDirTestClass){
    println " -------------- $projectDir from task"
    projectLoc = project
}

class ProjectDirTestClass extends DefaultTask {
    Project projectLoc
    @TaskAction
    def greet() {
        println " -------------- ${projectLoc.projectDir} from class"
    }
}

负面的一面是我必须为使用该任务类的每个任务传递相同的项目。 是一种好的风格。