javagradleflywaygradle-task

How to run a JavaExec gradle task with arguments when the task is called in finalizedBy?


I created a JavaExec task that connects to a db and does some checks. In my flyway build.gradle I call the task like this:

flywayMigrate.finalizedBy(rootProject.checkOracleStandards)

The task works fine, but the problem is that the connection url, user and password are hardcoded in the program that connects to the db and does the checks. I want to pass them as args to the custom task.

How to run the custom task with args after flywayMigrate?

This is how my task gradle file looks like:

apply plugin: 'java'

dependencies {
    implementation rootProject.files("libs/check-oracle-db-standards-1.jar")

    implementation group: 'com.oracle.database.jdbc', name: 'ojdbc8', version: '21.3.0.0'
    implementation group: 'org.springframework', name: 'spring-jdbc', version: '5.3.13'
    implementation 'org.junit.jupiter:junit-jupiter-api:5.7.0'
}

task checkOracleStandards(type: JavaExec) {
    classpath = sourceSets.main.runtimeClasspath
    main = 'com.package.checkoracledbstandards.Main'
}

Solution

  • Since the best way to share/pass arguments between tasks is through files, have a task write them to a file somewhere, and then have your checkOracleStandards task load them from that file.

    Make sure the arguments are written to the file in the doLast block, to avoid having the task run every time gradle syncs for example.

    Finally, have your checkOracleStandards task open up the file, parse the parameters and use them somehow.

    val outputPath = "${rootProjectPath}/build/check_params" <-- you may not want to use a folder for this
    val paramFile = file("${outputPath}/check_params")
    
     doLast {
                if (paramFile.exists().not()) {
                    paramFile.writeText()
    
                    File(outputPath)
                        .walk()
                        .maxDepth(1)
                        .filter {
                            it.isFile
                                    && it.name.endsWith("_params")
                        }
                        .forEach {
                            println("Passing params of ${it.name} into ${paramsFile.absolutePath}")
                            // PARSE params here
                            paramsFile.appendText("url: ${use_your_real_url}\tuser: ${use_your_real_user}\tpass: ${use_the_password}")
                            paramsFile.appendText("\n")
                        }
    

    if unsure, should make this part of a "pass params" task to run before your checkOracleStandards task, and then just modify your checkOracleStandards task to read params from this file and use them.

    EDIT: lemme add some clarifications, unrelated to the answer itself - i would've just posted a comment; however SO changed something, and my browser is currently unable to leave comments anywhere, so i gave you an answer that should've just been a comment.