W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
Gradle 提供了好幾種跳過(guò)一個(gè)任務(wù)的方式.
你可以使用 onlyIf() 方法來(lái)為一個(gè)任務(wù)加入判斷條件. 就和 Java 里的 if 語(yǔ)句一樣, 任務(wù)只有在條件判斷為真時(shí)才會(huì)執(zhí)行. 你通過(guò)一個(gè)閉包來(lái)實(shí)現(xiàn)判斷條件. 閉包像變量一樣傳遞任務(wù), 如果任務(wù)應(yīng)該被執(zhí)行則返回真, 反之亦然. 判斷條件在任務(wù)執(zhí)行之前進(jìn)行判斷.
例子 15.20. 使用判斷條件跳過(guò)一個(gè)任務(wù)
build.gradle
task hello << {
println 'hello world'
}
hello.onlyIf { !project.hasProperty('skipHello') }
gradle hello -PskipHello 的輸出
> gradle hello -PskipHello
:hello SKIPPED
BUILD SUCCESSFUL
Total time: 1 secs
如果想要跳過(guò)一個(gè)任務(wù)的邏輯并不能被判斷條件通過(guò)表達(dá)式表達(dá)出來(lái), 你可以使用 StopExecutionException. 如果這個(gè)異常是被一個(gè)任務(wù)要執(zhí)行的動(dòng)作拋出的, 這個(gè)動(dòng)作之后的執(zhí)行以及所有緊跟它的動(dòng)作都會(huì)被跳過(guò). 構(gòu)建將會(huì)繼續(xù)執(zhí)行下一個(gè)任務(wù).
例子 15.21. 通過(guò) StopExecutionException 跳過(guò)任務(wù)
build.gradle
task compile << {
println 'We are doing the compile.'
}
compile.doFirst {
// Here you would put arbitrary conditions in real life.
// But this is used in an integration test so we want defined behavior.
if (true) { throw new StopExecutionException() }
}
task myTask(dependsOn: 'compile') << {
println 'I am not affected'
}
gradle -q myTask 的輸出
> gradle -q myTask
I am not affected
如果你直接使用 Gradle 提供的任務(wù), 這項(xiàng)功能還是十分有用的. 它允許你為內(nèi)建的任務(wù)加入條件來(lái)控制執(zhí)行. [6]
每一個(gè)任務(wù)都有一個(gè)已經(jīng)激活的標(biāo)記(enabled flag), 這個(gè)標(biāo)記一般默認(rèn)為真. 將它設(shè)置為假, 那它的任何動(dòng)作都不會(huì)被執(zhí)行.
例子 15.22. 激活和注銷 tasks
build.gradle
task disableMe << {
println 'This should not be printed if the task is disabled.'
}
disableMe.enabled = false
gradle disableMe 的輸出
> gradle disableMe
:disableMe SKIPPED
BUILD SUCCESSFUL
Total time: 1 secs
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: