dotenv.gradle: Set environment variables per variant buildConfig task, with .env fallback (#180)

* dotenv.gradle: Environment variables are set per variant task

* Syncing readDotEnv with latest version

* Updating variable names

* Load default .env file

* BuildDotnevConfig.ruby: allow for default .env values
This commit is contained in:
Henry Chan 2017-11-16 14:48:57 -05:00 committed by Pedro Belo
parent b9d9571ba1
commit be8d77e501
2 changed files with 41 additions and 28 deletions

View File

@ -1,27 +1,4 @@
import java.util.regex.Matcher def loadDotEnv(currentFlavor) {
import java.util.regex.Pattern
def getCurrentFlavor() {
Gradle gradle = getGradle()
// match optional modules followed by the task
// (?:.*:)* is a non-capturing group to skip any :foo:bar: if they exist
// *[a-z]+([A-Za-z]+) will capture the flavor part of the task name onward (e.g., assembleRelease --> Release)
def pattern = Pattern.compile("(?:.*:)*[a-z]+([A-Z][A-Za-z]+)")
def flavor = ""
gradle.getStartParameter().getTaskNames().any { name ->
Matcher matcher = pattern.matcher(name)
if (matcher.find()) {
flavor = matcher.group(1).toLowerCase()
return true
}
}
return flavor
}
def readDotEnv = {
def envFile = ".env" def envFile = ".env"
if (project.hasProperty("defaultEnvFile")) { if (project.hasProperty("defaultEnvFile")) {
@ -31,11 +8,10 @@ def readDotEnv = {
if (System.env['ENVFILE']) { if (System.env['ENVFILE']) {
envFile = System.env['ENVFILE']; envFile = System.env['ENVFILE'];
} else if (project.hasProperty("envConfigFiles")) { } else if (project.hasProperty("envConfigFiles")) {
def flavor = getCurrentFlavor()
// use startsWith because sometimes the task is "generateDebugSources", so we want to match "debug" // use startsWith because sometimes the task is "generateDebugSources", so we want to match "debug"
project.ext.envConfigFiles.any { pair -> project.ext.envConfigFiles.any { pair ->
if (flavor.startsWith(pair.key)) { if (currentFlavor.startsWith(pair.key)) {
envFile = pair.value envFile = pair.value
return true return true
} }
@ -47,7 +23,7 @@ def readDotEnv = {
File f = new File("$project.rootDir/../$envFile"); File f = new File("$project.rootDir/../$envFile");
if (!f.exists()) { if (!f.exists()) {
f = new File("$envFile"); f = new File("$envFile");
} }
if (f.exists()) { if (f.exists()) {
@ -66,7 +42,7 @@ def readDotEnv = {
project.ext.set("env", env) project.ext.set("env", env)
} }
readDotEnv() loadDotEnv('.env')
android { android {
defaultConfig { defaultConfig {
@ -77,3 +53,26 @@ android {
} }
} }
} }
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\""
}
}
}
}
}
}
}
}

View File

@ -9,6 +9,7 @@ Encoding.default_internal = Encoding::UTF_8
if File.exists?("/tmp/envfile") if File.exists?("/tmp/envfile")
custom_env = true custom_env = true
file = File.read("/tmp/envfile").strip file = File.read("/tmp/envfile").strip
defaultEnvFile = ".env"
else else
custom_env = false custom_env = false
file = ENV["ENVFILE"] || ".env" file = ENV["ENVFILE"] || ".env"
@ -27,6 +28,19 @@ dotenv = begin
path = file path = file
end end
raw = File.read(path) raw = File.read(path)
if (defaultEnvFile)
defaultEnvPath = File.join(Dir.pwd, "../../../#{defaultEnvFile}")
if !File.exists?(defaultEnvPath)
# try as absolute path
defaultEnvPath = defaultEnvFile
end
defaultRaw = File.read(defaultEnvPath)
if (defaultRaw)
raw = defaultRaw + "\n" + raw
end
end
raw.split("\n").inject({}) do |h, line| raw.split("\n").inject({}) do |h, line|
m = line.match(dotenv_pattern) m = line.match(dotenv_pattern)
next h if m.nil? next h if m.nil?