81 lines
2.6 KiB
Groovy
Raw Normal View History

def loadDotEnv(currentFlavor) {
def envFile = ".env"
2017-04-27 04:55:36 +07:00
if (project.hasProperty("defaultEnvFile")) {
envFile = project.defaultEnvFile
}
if (System.env['ENVFILE']) {
envFile = System.env['ENVFILE'];
} else if (System.getProperty('ENVFILE')) {
envFile = System.getProperty('ENVFILE');
} else if (project.hasProperty("envConfigFiles")) {
// use startsWith because sometimes the task is "generateDebugSources", so we want to match "debug"
project.ext.envConfigFiles.any { pair ->
if (currentFlavor.startsWith(pair.key)) {
envFile = pair.value
return true
}
}
}
def env = [:]
println("Reading env from: $envFile")
File f = new File("$project.rootDir/../$envFile");
if (!f.exists()) {
f = new File("$envFile");
}
if (f.exists()) {
f.eachLine { line ->
def matcher = (line =~ /^\s*(?:export\s+|)([\w\d\.\-_]+)\s*=\s*['"]?(.*?)?['"]?\s*$/)
if (matcher.getCount() == 1 && matcher[0].size() == 3) {
env.put(matcher[0][1], matcher[0][2])
}
}
} else {
println("**************************")
println("*** Missing .env file ****")
println("**************************")
}
project.ext.set("env", env)
}
loadDotEnv('.env')
android {
defaultConfig {
project.env.each { k, v ->
def escaped = v.replaceAll("%","\\\\u0025")
buildConfigField "String", k, "\"$v\""
resValue "string", k, "\"$escaped\""
}
}
}
tasks.whenTaskAdded { task ->
if (project.hasProperty("envConfigFiles")) {
project.envConfigFiles.each { envConfigName, envConfigFile ->
if (task.name.toLowerCase() == "generate"+envConfigName+"buildconfig") {
task.doFirst() {
android.applicationVariants.all { variant ->
def variantConfigString = variant.getVariantData().getVariantConfiguration().getFullName()
if (envConfigName.contains(variantConfigString.toLowerCase())) {
loadDotEnv(envConfigName)
project.env.each { k, v ->
def escaped = v.replaceAll("%","\\\\u0025")
variant.buildConfigField "String", k, "\"$v\""
variant.resValue "string", k, "\"$escaped\""
}
}
}
}
}
}
}
}