javagradlegroovykotlinbuild-script

Gradle task not running as demanded (before compiling)


INTRODUCTION

The project is in Kotlin and builds using Gradle. I'm trying to generate a basic data class with some build info, let's say for now that I need it [re]generated every time before running.

Here's the Gradle task I have now:

def generatedDir = "$buildDir/generated"

// noinspection GroovyAssignabilityCheck
task generateBuildInfo {
    inputs.property "version", rootProject.version.toString()
    inputs.property "name", rootProject.name.toString()

    outputs.dir generatedDir
    outputs.upToDateWhen { false }

    doFirst {
        def buildInfoFile = file("$generatedDir/BuildInfo.kt")
        buildInfoFile.parentFile.mkdirs()
        buildInfoFile.text = """
        internal data class BuildInfo(
          val version: String = "${project.version.toString() ?: "unspecified"}",
          val name: String = "${project.name.toString() ?: "unspecified"}"
        )
        """.replace("        ", "").trim()
    }
}

To be able to resolve this from IntelliJ IDEA, I added my new folder to project sources, and obviously wired up the dependencies, like so:

sourceSets.main.kotlin.srcDirs += generatedDir

project.afterEvaluate {
    compileJava.dependsOn generateBuildInfo
    compileKotlin.dependsOn generateBuildInfo
}

This is all done in a separate file (to avoid polluting my main scripts). Due to this organization, after applying plugins, I just include the generator in my main script, like this:

apply from: "gradle/scripts/build-info-generator.gradle"

THE PROBLEM

It looks like the generator code is executed only once, after running assemble when I first ran clean on this module. This is not what I want, because when I change some of the project properties (like version), the source does not get updated... as if compileJava/compileKotlin and my custom task are not executed.

They do not appear in build logs as executed.

Is there any way I can run this task every time I want to run my module's launcher? Sure, I can do some smart file comparison to see if generation is needed, but for now I just want it done each time. Am I missing something?


Solution

  • IDEA has its own build system, indepenant from Gradle.

    You can configure it to run a Gradle task before its own build task.

    You can also configure it to delegate all the build/run tasks to Gradle. But that's not the default.