|
- namespace Campaign_Tracker.Server.Configuration;
-
- public static class DotEnvConfiguration
- {
- public static void Load(ConfigurationManager configuration, string contentRootPath)
- {
- var rootEnvPath = Path.GetFullPath(Path.Combine(contentRootPath, "..", ".env"));
- var serverEnvPath = Path.Combine(contentRootPath, ".env");
- var values = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
-
- AddFileValues(rootEnvPath, values);
- AddFileValues(serverEnvPath, values);
-
- if (values.Count > 0)
- {
- configuration.AddInMemoryCollection(values);
- }
- }
-
- private static void AddFileValues(string path, IDictionary<string, string?> values)
- {
- if (!File.Exists(path))
- {
- return;
- }
-
- foreach (var line in File.ReadLines(path))
- {
- var trimmed = line.Trim();
- if (trimmed.Length == 0 || trimmed.StartsWith('#'))
- {
- continue;
- }
-
- var separatorIndex = trimmed.IndexOf('=');
- if (separatorIndex <= 0)
- {
- continue;
- }
-
- var key = trimmed[..separatorIndex].Trim().Replace("__", ":");
- var value = trimmed[(separatorIndex + 1)..].Trim();
- values[key] = Unquote(value);
- }
- }
-
- private static string Unquote(string value)
- {
- if (value.Length >= 2 &&
- ((value.StartsWith('"') && value.EndsWith('"')) ||
- (value.StartsWith('\'') && value.EndsWith('\''))))
- {
- return value[1..^1];
- }
-
- return value;
- }
- }
|