【问题标题】:Cannot have different system properties values for different tasks不同的任务不能有不同的系统属性值
【发布时间】:2017-12-10 10:11:12
【问题描述】:

我正在尝试创建 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

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

【问题讨论】:

    标签: gradle sonarqube build.gradle sonarqube-scan


    【解决方案1】:

    首先: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
    }
    

    【讨论】:

    • 很好的答案,一个问题我如何通过命令行'gradle sonarqube fullScan'传递诸如'fullScan'之类的条件?
    • 项目属性通过-P<name>=<value> 设置。因此,对于上面的代码示例,您可以指定-PfullScan=true。您还可以通过检查hasProperty('fullScan') 来使用项目属性的存在作为条件。在这种情况下,-PfullScan 就足够了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-12
    • 2012-09-29
    • 2019-07-20
    • 2014-02-06
    • 2017-06-10
    • 2021-07-20
    相关资源
    最近更新 更多