doFirst and doLast

A task is a list of actions. doFirst pushes one to the front of the list and doLast appends one to the end, so a script that calls them in the wrong order still runs correctly — but the order of four calls is not the order of four lines. This lesson makes a task print its own order.

The four actions

settings.gradle

rootProject.name = 'shop'

build.gradle

plugins { id 'base' } tasks.register('ordered') { group = 'shop' description = 'Shows the order of the actions of a task' doLast { println 'last 1' } doFirst { println 'first 1' } doLast { println 'last 2' } doFirst { println 'first 2' } }

The order they ran in

gradle -q ordered --console=plain --offline --no-daemon

first 2
first 1
last 1
last 2

Why the order is this

The actions of a task are one list, and the two methods work at its two ends:

A plugin that configures a task of yours with doFirst therefore runs before your own doFirst actions only if it configured the task later than your script did, and the rule of thumb is to configure a task with tasks.named(...) in one place and to keep doFirst for a task of your own.

Actions are what a build cache key does not cover: Gradle cannot know what an action prints, so a task with an action is only UP-TO-DATE if it also declares inputs and outputs. A task of one printout runs every time, which is what this one does.

Related

Автор статьи: Arthur Isaev

Изображение баннера