2017-07-06 88 views
0

我正在嘗試創建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

它就好像這些屬性是在運行時設置的並且無法更新。我覺得我錯過了很明顯的任何建議,大大收到。

回答

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 
} 
+0

偉大的答案,有一個問題我怎麼在傳遞一個條件,如「全掃描」會是這樣通過命令行'gradle sonarqube fullScan'? – JaChNo

+0

項目屬性通過'-P = '來設置。因此,對於上面的代碼示例,您可以指定'-PfullScan = true'。你也可以通過檢查hasProperty('fullScan')來使用項目屬性的存在性作爲條件。在這種情況下,'-PfullScan'就足夠了。 –

相關問題