Search code examples
gradlegroovy

Concatenate configuration with groovy


In my .build.gradle, I have defined a specific configuration :

project.ext.envConfigFiles = [
  aaaDebug: ".env.aaa",
  aaaRelease: ".env.aaa",
  bbbDebug: ".env.bbb",
  bbbRelease: ".env.bbb"
]

This configuration is taken from the react-native-config documentation and works very well (build OK).

But I'd like a dynamic configuration, from a table. For example :

def variants = [
  'aaa',
  'bbb',
  ...
]

def variantsConfig = []
variantsJson.each { name ->
    variantsConfig.push("${name}Debug: .env.${name}")        
    variantsConfig.push("${name}Release: .env.${name}")
}
project.ext.envConfigFiles = variantsConfig

But I can't concatenate the configuration, I keep getting errors


Solution

  • From what I see the project.ext.envConfigFiles is a map ConfigKey:'ConfigValue'. However, you are generating a list in you second script. Your problems have great chances to come from that.

    What you can do to correct that, and actually generate a Map:

    def variantsJson = [
      'aaa',
      'bbb',
      ...
    ]
    
    Map variantsConfig = [:]
    variantsJson.each { name ->
        variantsConfig["${name}Debug"] =  ".env.${name}"        
        variantsConfig["${name}Release"] = ".env.${name}"
    }
    
    project.ext.envConfigFiles = variantsConfig