How do I cleanly separate tasks that might require two different configuration tasks in Gradle? I’m attempting to separate the actual tasks that I want to execute in a buildSrc/dbhelpertasks.gradle file from the parent build.gradle file. build.gradle will contain partially configured tasks that are used in dbhelpertasks.gradle.
I have a number of different databases that I want to connect and execute SQL on so I created a SQLServerTask that takes a database name and URL.
Custom SQLServerTask.groovy
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
import groovy.sql.Sql
class SQLServerTask extends DefaultTask {
def hostname
def database
def port = 1433
def username
def password
def sql
def sqlServerDriver = 'net.sourceforge.jtds.jdbc.Driver'
@TaskAction
def executeSql() {
url = hostname + ":" + port + "/" + database
databaseConnProps = [user: username, password: password]
def sqlInstance = Sql.newInstance(url, databaseConnProps, sqlServerDriver)
println "I would execute " + sql
}
}
I then created a task in my build.gradle that would configure the SQLServerTask with some of the properties.
build.gradle
import groovy.sql.Sql
apply from: 'buildSrc/dbhelpertasks.gradle'
repositories {
mavenCentral()
}
configurations {
driver
}
dependencies {
driver group: 'net.sourceforge.jtds', name: "jtds", version: "1.2.4"
}
//Load up all the drivers for use in this project
URLClassLoader loader = GroovyObject.class.classLoader
configurations.driver.each {File file ->
loader.addURL(file.toURL())
}
task contentDbTask(type: SQLServerTask) {
println "Configuring content db task"
hostname = contentDbUrl
database = contentDbName
username = contentDbUserName
password = contentDbPassword
}
The dbhelpertasks.gradle file contains the final configuration (SQL Statement) of the actual tasks that I want to execute.
buildSrc/dbhelpertasks.gradle
task getSiteParams(type: contentDbTask) {
println "Configuring Site Params Task"
sql = "SELECT * FROM CMS_SITE_PARAM"
}
When I execute gradle getSiteParams it ends up failing
* What went wrong: A problem occurred evaluating script. > Could not find property 'contentDbTask' on root project 'shipyard'.
There are a number of misconceptions here.
First, only class
SQLServerTaskshould be inbuildSrc, as the only purpose ofbuildSrcis to produce classes which are then used by the main build.dbhelpertasks.grovvywould typically go into a top-levelgradledirectory (sibling ofbuildSrc) and end in.gradle. Preconfiguration of a task, likecontentDbTaskdoes, would typically be done by a plugin (like thedbhelpertasks.gradlescript plugin) rather than a task.A task’s type is always a class, so
task getSiteParams(type: contentDbTask)won’t work. Also,dbhelpertasks.groovycan’t see tasks added (or any other configuraion done) bybuild.gradle, only the other way around. This is because the latter applies the former at the very top (which is fine).