gradle任务笔记

2018-10-31  本文已影响0人  吉凶以情迁
open class GreetingTask : DefaultTask() {
    var greeting = "hello from GreetingTask"

    @TaskAction
    fun greet() {
        println(greeting)
    }
}

// Use the default greeting
task<GreetingTask>("hello")

// Customize the greeting
task<GreetingTask>("greeting") {
    greeting = "greetings from GreetingTask"
}

执行gradle --quiet hello greeting
结果

hello from GreetingTask
greetings from GreetingTask

结论 一个是修改了,一个是没修改,执行会默认调用@TaskAction里面的方法

// tag::all[]
// tag::task[]
class GreetingToFileTask extends DefaultTask {

    def destination

    File getDestination() {
        project.file(destination)
    }

    @TaskAction
    def greet() {
        def file = getDestination()
        file.parentFile.mkdirs()
        file.write 'Hello!'
    }
}
// end::task[]

// tag::config[]
task greet(type: GreetingToFileTask) {
    destination = { project.greetingFile }
}

task sayGreeting(dependsOn: greet) {
    doLast {
        println file(greetingFile).text
    }
}

ext.greetingFile = "$buildDir/hello.txt"

执行gradle --quiet sayGreeting
结论, 先执行 任务 greet,而这个任务会执行写入hello到hello.txt 然后sayGreeting执行就把写入的文本打印出来。

任务的变量写法

task myCopy(type: Copy)

// tag::configure[]
Copy myCopy = tasks.getByName("myCopy")
myCopy.from 'resources'
myCopy.into 'target'
myCopy.include('**/*.txt', '**/*.xml', '**/*.properties')

或者

task myCopy(type: Copy)
// end::declare-task[]

// tag::configure[]
// Configure task using Groovy dynamic task configuration block
myCopy {
   from 'resources'
   into 'target'
}
myCopy.include('**/*.txt', '**/*.xml', '**/*.properties')

或者

task copy(type: Copy) {
// end::no-description[]
   description 'Copies the resource directory to the target directory.'
// tag::no-description[]
   from 'resources'
   into 'target'
   include('**/*.txt', '**/*.xml', '**/*.properties')
}

都是一个意思,是代表从这个目录复制指定后缀的到某个目录。

finalizedBy

task taskX {
    doLast {
        println 'taskX'
    }
}
task taskY {
    doLast {
        println 'taskY'
    }
}

taskX.finalizedBy taskY

表示不管成功或者失败都会在taskX执行完毕之后执行taskY,

上一篇下一篇

猜你喜欢

热点阅读