isaac
isaac

Reputation: 13

when does doFirst is executed in gradle

Why 0000 does NOT exit after gradle foo? After I remove doFirst foo.doFirst{ delete '0000' }, the 0000 is there.

doFirst should be executed before foo task scripts.

The docs says:

Task doFirst(Closure action)

Adds the given closure to the beginning of this task's action list. The closure is passed this task as a parameter when executed.

Full command log:

isaac-mbp:swap isaac$ cat build.gradle
task foo {
    mkdir '0000/a'
    mkdir '0000/b'
}
foo.doFirst{ delete '0000' }

isaac-mbp:swap isaac$ gradle foo
:foo

BUILD SUCCESSFUL

Total time: 0.581 secs
isaac-mbp:swap isaac$ ls -lha 0000
ls: cannot access 0000: No such file or directory
isaac-mbp:swap isaac$ gradle -v

------------------------------------------------------------
Gradle 2.14
------------------------------------------------------------

Build time:   2016-06-14 07:16:37 UTC
Revision:     cba5fea19f1e0c6a00cc904828a6ec4e11739abc

Groovy:       2.4.4
Ant:          Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM:          1.8.0_25 (Oracle Corporation 25.25-b02)
OS:           Mac OS X 10.11.5 x86_64

Upvotes: 1

Views: 1697

Answers (1)

Opal
Opal

Reputation: 84884

No.

  1. A task is (simplifying) a collection of actions that are executed in order they were added
  2. build.gradle is run in two phases: configuration and execution.

The logic (mkdirs) in the following piece of code will be executed every time build.gradle is evaluated since it's added in configuration time:

task foo {
    mkdir '0000/a'
    mkdir '0000/b'
}

To fix it - add an action:

task foo << {
    mkdir '0000/a'
    mkdir '0000/b'
}

And now doFirst:

task foo << {
        mkdir '0000/a'
        mkdir '0000/b'
}
foo.doFirst { delete '0000' }

Now the task has 2 actions: mkdirss and delete and they will be executed in an appropriate order. Please have a look here as well

Upvotes: 2

Related Questions