summaryrefslogtreecommitdiff
path: root/src/main/java/moe/nea/prickly/config/ConfigCompat.java
blob: 6c94947bbfac8cb77c66f8143365945e5d85a5c4 (plain)
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
/* (C) 2025 Linnea Gräf - Licensed to everyone under the BSD 3 Clause License */
package moe.nea.prickly.config;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.jspecify.annotations.Nullable;

@Slf4j
public class ConfigCompat {
	public static final Path ENV_FILE = Path.of(".env").toAbsolutePath();

	@SuppressWarnings({"unchecked", "rawtypes"})
	private static Map<String, String> loadDotenv() {
		var properties = new Properties();
		if (!Files.exists(ENV_FILE)) {
			log.info("no .env file found at {}", ENV_FILE);
		} else {
			try (var reader = Files.newBufferedReader(ENV_FILE, StandardCharsets.UTF_8)) {
				properties.load(reader);
				log.info("loaded environment from {} ({} entries)", ENV_FILE, properties.size());
			} catch (IOException e) {
				log.error("could not read .env file at {}", ENV_FILE, e);
			}
		}
		return (Map) properties;
	}

	public static Map<String, String> DOTENV_FALLBACK = Collections.unmodifiableMap(loadDotenv());
	public static NavigableMap<String, String> ENV;

	static {
		var env = new TreeMap<String, String>();
		env.putAll(DOTENV_FALLBACK);
		env.putAll(System.getenv());
		ENV = Collections.unmodifiableNavigableMap(env);
	}

	public static @Nullable String getEnv(String key) {
		return ENV.get(key);
	}

	public static Map<String, String> getAllEnvStartingWith(String prefix) {
		return ENV.subMap(prefix + "_", prefix + (char) ((int) '_' + 1));
	}

	public static Set<String> getAllDirectChildren(String prefix) {
		int start = prefix.length() + 1;
		return getAllEnvStartingWith(prefix).keySet().stream()
				.map(it -> {
					int nextUnderscore = it.indexOf('_', start);
					if (nextUnderscore < 0) return it.substring(start);
					else return it.substring(start, nextUnderscore);
				})
				.collect(Collectors.toSet());
	}
}