baekacaek
baekacaek

Reputation: 1557

How to make gradle copy task run on execution only

I have a gradle task for copying, like below:

task hello << {
    println "hello"
}

task myCopy(type: Copy) {
    println "copy"
    from(file('srcDir'))
    into(buildDir)
}

but "myCopy" task gets executed even when I execute "hello" like below:

gradle hello

Now I understand this is the intended behavior. I read thru the entire Gradle Task page here: https://docs.gradle.org/current/userguide/more_about_tasks.html . But I want to make "myCopy" task only execute when explicitly executed. In other words, I want to make it so that "myCopy" does not execute when I execute "hello", and only execute when I run the command:

gradle myCopy

Is there a way to do this? Thanks

Upvotes: 1

Views: 535

Answers (1)

Stanislav
Stanislav

Reputation: 28096

It's not getting executed, but getting configured. Take a closer look, nothing get copied if you don't run your copy task. Configuration is happenning always and for all the tasks you have, in your case you are printing "copy" during the configuration. Move it into the doLast section to print it at the execution phase, as:

task myCopy(type: Copy) {
   doLast { 
       println 'Copy'
   }
   from(file('srcDir'))
   into(buildDir)
}

Note, that doLast closure is the same as a task closure with << sign and it is executed only if task executed at the execution phase.

Upvotes: 1

Related Questions