-
Notifications
You must be signed in to change notification settings - Fork 654
/
dotenv.gradle
77 lines (65 loc) · 2.38 KB
/
dotenv.gradle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import java.util.regex.Matcher
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-z0-9]+)")
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 loadDotEnv(flavor = getCurrentFlavor()) {
def envFile = project.hasProperty("defaultEnvFile") ? project.defaultEnvFile : ".env"
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 (flavor.startsWith(pair.key.toLowerCase())) {
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 ->
// https://regex101.com/r/cbm5Tp/1
def matcher = (line =~ /^\s*(?:export\s+|)([\w\d\.\-_]+)\s*=\s*['"]?(.*?)?['"]?\s*$/)
// TODO: Fail Android builds if line doesn't match
if (matcher.getCount() == 1 && matcher[0].size() == 3) {
env.put(matcher[0][1], matcher[0][2].replace('"', '\\"'))
}
}
} else {
println("**************************")
println("*** Missing .env file ****")
println("**************************")
}
project.ext.set("env", env)
}
loadDotEnv()
android {
defaultConfig {
project.env.each { k, v ->
def escaped = v.replaceAll("%","\\\\u0025")
buildConfigField "String", k, "\"$v\""
resValue "string", k, "\"$escaped\""
}
}
}