Repository navigation
Expand file tree
/
Copy pathEnv.java
More file actions
61 lines (55 loc) · 1.77 KB
/
Copy pathEnv.java
File metadata and controls
61 lines (55 loc) · 1.77 KB
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
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
/** Loads DB_URL, DB_USER and DB_PASSWORD from the project's .env file. */
public final class Env {
private static final Map<String, String> VALUES = load();
private Env() {
}
public static String get(String key) {
String value = System.getenv(key);
if (value == null || value.isEmpty()) {
value = VALUES.get(key);
}
return value;
}
private static Map<String, String> load() {
Map<String, String> values = new HashMap<>();
Path file = findEnv();
if (file == null) {
return values;
}
try {
for (String raw : Files.readAllLines(file)) {
String line = raw.trim();
if (line.isEmpty() || line.startsWith("#")) {
continue;
}
int eq = line.indexOf('=');
if (eq > 0) {
values.put(line.substring(0, eq).trim(), line.substring(eq + 1).trim());
}
}
} catch (Exception e) {
System.out.println("WARNING: could not read " + file + ": " + e.getMessage());
}
return values;
}
private static Path findEnv() {
Path dir = Paths.get("").toAbsolutePath();
while (dir != null) {
Path local = dir.resolve(".env");
if (Files.isRegularFile(local)) {
return local;
}
Path project = dir.resolve("GroupProject").resolve(".env");
if (Files.isRegularFile(project)) {
return project;
}
dir = dir.getParent();
}
return null;
}
}