不能为不同的任务使用不同的系统属性值

时间:2017-07-06 12:00:42

标签: gradle sonarqube build.gradle sonarqube-scan

我正在尝试创建2个任务来执行sonarcube任务。我希望能够根据任务指定不同的属性

   task sonarqubePullRequest(type: Test){

        System.setProperty( "sonar.projectName", "sonarqubePullRequest")
        System.setProperty("sonar.projectKey", "sonarqubePullRequest")
        System.setProperty("sonar.projectVersion", serviceVersion)
        System.setProperty("sonar.jacoco.reportPath", 
        "${project.buildDir}/jacoco/test.exec")

        tasks.sonarqube.execute()
    }


task sonarqubeFullScan(type: Test){
    System.setProperty("sonar.projectName", "sonarqubeFullScan")
    System.setProperty("sonar.projectKey", "sonarqubeFullScan")
    System.setProperty("sonar.projectVersion", serviceVersion)
    System.setProperty("sonar.jacoco.reportPath", 
    "${project.buildDir}/jacoco/test.exec")
    tasks.sonarqube.execute()
}

任务有效,但我设置的属性似乎存在问题

如果我运行第一个任务是sonarqubePullRequest,那么一切都很好,但如果运行sonarqubeFullScan则使用sonarqubePullRequest中指定的值。所以项目名称设置为sonarqubePullRequest

就好像这些属性是在运行时设置的,无法更新。我觉得我错过了一些很明显的建议。

1 个答案:

答案 0 :(得分:2)

首先:NEVER use execute() on tasks。该方法不是公共Gradle API的一部分,因此,其行为可能会更改或未定义。 Gradle将自己执行任务,因为您指定了它们(命令行或settings.gradle)或作为任务依赖项。

为什么您的代码不起作用的原因是difference between the configuration phase and the execution phase。在配置阶段中,执行任务闭包中的所有(配置)代码,但不执行任务。因此,您将始终覆盖系统属性。仅<(内部)任务操作,doFirstdoLast闭包在执行阶段中执行。请注意,每个任务只在构建中执行 ONCE ,因此您将两次参数化任务的方法永远不会有效。

另外,我不明白为什么要使用系统属性来配置sonarqube任务。您可以直接通过以下方式配置任务:

sonarqube {
    properties {
        property 'sonar.projectName', 'sonarqubePullRequest'
        // ...
    }
}

现在您可以配置sonarqube任务。要区分您的两种情况,可以为不同的属性值添加条件。下一个示例使用项目属性作为条件:

sonarqube {
    properties {
        // Same value for both cases
        property 'sonar.projectVersion', serviceVersion
        // Value based on condition
        if (project.findProperty('fullScan') {
            property 'sonar.projectName', 'sonarqubeFullScan'
        } else {
            property 'sonar.projectName', 'sonarqubePullRequest'
        }
    }
}

或者,您可以添加SonarQubeTask类型的其他任务。这样,您可以以不同方式对两个任务进行参数化,并在需要时调用它们(通过命令行或依赖项):

sonarqube {
    // Generated by the plugin, parametrize like described above
}

task sonarqubeFull(type: org.sonarqube.gradle.SonarQubeTask) {
    // Generated by your build script, parametrize in the same way
}