Search code examples
androidgroovyandroid-gradle-pluginbuild.gradlebuildconfig

How to define a function at android.defaultConfig level?


In my Android project in build.gradle use the following instructions to create build config fields.

android {
    defaultConfig {
        if (project.hasProperty('serverOnePath')) {
            buildConfigField "String", "SERVER_ONE_PATH",
                    "\"${serverOnePath}\""
        }
        if (project.hasProperty('serverTwoPath')) {
            buildConfigField "String", "SERVER_TWO_PATH",
                    "\"${serverTwoPath}\""
        }
    }
}

The properties therefore must be defined in gradle.properties as such:

serverOnePath=http://example1.com/path
serverTwoPath=http://example2.com/path

I would like to move the instructions into a function available at android.default level. Here is a non-working draft:

def addBuildConfigFieldIfPropertyIsPresent(
    String propertyName, String buildConfigFieldName) {
    if (project.hasProperty(propertyName)) {
        android.defaultConfig.buildConfigField "String", buildConfigFieldName,
                "\"${propertyName}\""
    }
}

The tricky part is ${propertyName}. Also it would be nice to actually put the declaration into the defaultConfig closure.


Solution

  • Try this:

    android {
      defaultConfig {
        def configFieldFromProp = { propName, constName ->
          if (project.hasProperty(propName)) {
            buildConfigField "String", constName, "\"${project[propName]}\""
          }
        }
    
        configFieldFromProp "serverOnePath", "SERVER_ONE_PATH"
        configFieldFromProp "serverTwoPath", "SERVER_TWO_PATH"
      }
    }
    

    You can also add guava as a dependency to your build script and use LOWER_CAMEL.to(UPPER_UNDERSCORE, propName) to avoid typing the same thing twice.