TIL: Gradle tasks and doLast

I’ve known about custom Gradle tasks and functions for a while (Android Studio). I’ve used one, copied from SO and edited to suit my needs, in one of my projects before. This week I got to create a task from scratch to add a dev feature to the app at work. So far so good.

This TIL is not about learning about Gradle tasks. This is about a tiny detail that I didn’t know. I usually write/see tasks written like this

task countChicken {
    // count chicken
    ...
}

When written like this, the chicken are counted immediately every time the Gradle project is synced or built (task configuration).

What I had not known till this week was that anything directly inside that task definition block is executed at the task configuration stage. So, in this case the whole counting of chicken is happening at the task configuration stage, whether we explicitly execute the task or not.

If we only want to execute the task on demand, the task configuration needs to be separated from execution, like so:

task countChicken {
    doLast {
        // count chicken
        ...
    }
}

The doLast ensures that this code block is only executed during task execution. It basically tells Gradle during configuration to run this code block last while executing this task1. We can also use the doFirst code block to run something first while executing the task. Continue reading

TIL: Automatic date in version name // Android+Gradle

I name my app versions as YYYY.MMDD.Major.Minor.Working. As an example, the current version of an app while I’m working on it may be 2020.0506.1.24.3 while the published version may be 2020.0501.1.23.

I’ve got a good habit of updating the versions section—the Major.Minor.Working bit. But I often forget to update the date bit, specially the DD section. So, after a bit of research (THANK YOU STACKOVERFLOW, FOR EVERYTHING), I got this bit working.

This is all it took:

// build.gradle (app module)

def versionString="0.6.1"

static def getDate() {
    return new Date().format('yyyy.MMdd')
}

android {
    ...
    defaultConfig {
    ...
    versionName "${getDate()}.${versionString}"
    ...

I manually update the versionString when I move to the next version. The build process automatically adds the date to it. Simple, and robust :)