ConfigSlurper and subprojects


(Sion Williams) #1

I have a scenario where I want to slurp all of my config from an env.groovy file. To do that I have this task:

ext{
 configFile = file('env.groovy')
}
  task configEnv << {
  def environment = "$env"
 project.ext.environement = "environment"
    project.ext.config = new ConfigSlurper(environment).parse(configFile.toURL())
 logger.lifecycle "Environment is set to $environment"
}

This works great when I only have a single project and pass in -Penv=local

I would like to extend this to my subprojects, and so set a dependsOn flag:

Parent build.gradle

subprojects {
 ext.configFile = file('env.groovy')
     task migrateDB(dependsOn: 'configEnv') << {
  mkdir('build/sql')
  ant.taskdef(name: 'dbdeploy',
      classname: 'com.dbdeploy.AntTarget',
      classpath: (configurations.dbdeploy + configurations.ora).asPath)
  ant.dbdeploy(driver: "oracle.jdbc.OracleDriver",
       url: "jdbc:oracle:thin:@localhost:1521/$dbsid",
       userid: "$dbaUsername",
       password: "$dbaPassword",
       dir: "$dbddl",
       dbms: "ora",
       outputfile: "$buildDir/sql/run.sql")
     }
    task configEnv << {
   def environment = "$env"
  project.ext.environement = "environment"
     project.ext.config = new ConfigSlurper(environment).parse(configFile.toURL())
  logger.lifecycle "Environment is set to $environment"
 }
}

and the children using this config:

migrateDB{
 ext.dbaUsername = $config.db.krill.user
 ext.dbaPassword = $config.db.krill.password
 ext.dbddl = "sql/running_orders"
 ext.dbsid = $config.db.krill.sid
}

Finally the env.groovy:

environments {
     local {
         serverName = 'localVM'
  db {
    krill{
    sid = 'orcl'
    user = 'krill'
     password = 'krill'
        }
    }
 }

The problem is:

$ ./gradlew migrateDB -Penv=local
  FAILURE: Build failed with an exception.
  * Where:
Build file '/media/sf_vm_shared/water/krill/build.gradle' line: 4
  * What went wrong:
A problem occurred evaluating project ':krill'.
> Could not find property '$config' on task ':krill:migrateDB'.
  * Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
  BUILD FAILED
  Total time: 3.023 secs

(Peter Niederwieser) #2

The ‘configEnv’ task sets the ‘config’ extra property when it executes, that is in the execution phase. The subproject is trying to access the property in the configuration phase, which comes before the execution phase. One solution is to move property accesses into the execution phase by replacing ‘migrateDb { …}’ with ‘migrateDb.doFirst { … }’.


(Sion Williams) #3

Thank you very much, Peter. You are teaching me a lot :slight_smile: