Gradle筆記系列(二)

一、使用Gradle命令行安全

  在這篇博客中,咱們將簡要介紹Gradle命令行的使用。ide

1.1 執行多任務測試

  經過在命令行列出每一個任務(task),你能夠在一次構建(build)中執行多個任務。例如,命令gradle compile test會執行compile和test這兩個任務,Gradle按照任務在命令行列出的順序依次執行每一個任務,同時也會執行每一個任務的依賴任務。每一個任務無論如何被包含在build中,它只會被執行一次(無論它是被指定在命令行中,或者是做爲另外一個task的依賴出現,或者二者兼有)。看一個例子,下圖列出了4個任務,其中dist和test都依賴於compile。gradle

 

build.gradleui

 1 task compile << {
 2     println 'compiling source'
 3 }
 4 task compileTest(dependsOn: compile) << {
 5     println 'compiling unit tests'
 6 }
 7 task test(dependsOn: [compile, compileTest]) << {
 8     println 'running unit tests'
 9 }
10 task dist(dependsOn: [compile, test]) << {
11     println 'building the distribution'
12 }
build.gradle

執行命令gradle dist test,輸出結果以下spa

C:\Users\Administrator\Desktop\gradle>gradle dist test
:compile
compiling source
:compileTest
compiling unit tests
:test
running unit tests
:dist
building the distribution

BUILD SUCCESSFUL

Total time: 2.012 secs

從上面輸出結果能夠看出,每一個任務只被執行了1次,所以gradle test testgradle test效果徹底同樣。命令行

1.2 移除任務code

  你能夠經過-x命令參數移除task,依然以上述代碼爲例,下面是測試結果輸出blog

C:\Users\Administrator\Desktop\gradle>gradle dist -x test
:compile
compiling source
:dist
building the distribution

BUILD SUCCESSFUL

Total time: 1.825 secs

  經過上述輸出結果能夠看出,任務test沒有被執行,即使它被dist所依賴。同時你也會注意到任務test所依賴的任務之一compileTest也沒有被執行,同時被test和dist所依賴的任務(如compile)仍然被執行了。博客

  1.3 出錯時的繼續build

  默認狀況下,當gradle構建過程當中遇到任何task執行失敗時將會馬上中斷。這樣運行你立刻去解決這個構建錯誤,可是這樣也會隱藏可能會發生的其餘錯誤。爲了在一次執行過程當中儘量暴露多的錯誤,你可使用--continue選項。當你執行命令的時候加上了--continue選項,Gradle將會執行每一個任務的全部依賴,而無論失敗的發生,而不是在第一個錯誤發生時就立馬中止。在執行過程當中所發生的全部錯誤在構建的結尾都會被列出來。若是一個任務失敗了,隨後其餘依賴於這個任務的子任務,這麼作是不安全的。例如,若是在test代碼裏面有一個編譯錯誤,test任務將不會執行;因爲test任務依賴於compilation任務(無論是直接仍是間接)。

1.4 簡化task名字

   在命令行指定task時,咱們不須要給出任務的全名,只須要給出可以足夠惟一標識某個任務的簡化的名字便可。例如,在上面的例子中,咱們可使用gradle di命令來執行task dist。此外,當task名是由多於1個的單詞構成時,咱們也可使用每一個單詞的首字母做爲task名的簡化形式。好比一個名字爲compileTest的task,咱們可使用命令:gradle cT來進行編譯(或者使用gradle compTest)。簡化後的task名字也適用-x選項。

1.5 選擇性的執行某個build文件

  當咱們執行gradle命令時,會在當前路徑下尋找build文件。可使用-b選項指定另外一個build文件。若是指定了-b選項,那麼settings.gradle文件將不會起做用。看例子:

subdir/myproject.gradle:

task hello << {
    println "using build file '$buildFile.name' in '$buildFile.parentFile.name'."
}

  執行命令:gradle -q -b subdir/myproject.gradle hello輸出結果以下:

using build file 'myproject.gradle' in 'subdir'.

  或者,可使用-p選項指定要使用的工程目錄。對多工程編譯時,應該使用-p選項而不是-b選項。例子:

  subdir/build.gradle

 

task hello << {
    println "using build file '$buildFile.name' in '$buildFile.parentFile.name'."
}

  執行命令:gradle -q -p subdir hello輸出結果以下:

using build file 'build.gradle' in 'subdir'.

若是使用其它構建文件名,可與-b一塊兒使用:gradle -q -p subdir -b subdir/myproject.gradle hello

相關文章
相關標籤/搜索