From 289f8921ff837495df6399be25929ae22c2336a5 Mon Sep 17 00:00:00 2001 From: Marcel Baumgartner Date: Tue, 16 Jan 2024 14:38:43 +0100 Subject: [PATCH] Implemented environment variable loading in config service --- Moonlight/App/Services/ConfigService.cs | 42 +++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/Moonlight/App/Services/ConfigService.cs b/Moonlight/App/Services/ConfigService.cs index 3971940..e10553c 100644 --- a/Moonlight/App/Services/ConfigService.cs +++ b/Moonlight/App/Services/ConfigService.cs @@ -21,6 +21,9 @@ public class ConfigService var text = File.ReadAllText(Path); Data = JsonConvert.DeserializeObject(text) ?? new(); + + ApplyEnvironmentVariables("Moonlight", Data); + Save(); } @@ -57,4 +60,43 @@ public class ConfigService return JsonConvert.SerializeObject(data, Formatting.Indented); } + + private void ApplyEnvironmentVariables(string prefix, object objectToLookAt) + { + foreach (var property in objectToLookAt.GetType().GetProperties()) + { + var envName = $"{prefix}_{property.Name}"; + + if (property.PropertyType.Assembly == GetType().Assembly) + { + ApplyEnvironmentVariables(envName, property.GetValue(objectToLookAt)!); + } + else + { + if(!Environment.GetEnvironmentVariables().Contains(envName)) + continue; + + var envValue = Environment.GetEnvironmentVariable(envName)!; + + if (property.PropertyType == typeof(string)) + { + property.SetValue(objectToLookAt, envValue); + } + else if (property.PropertyType == typeof(int)) + { + if(!int.TryParse(envValue, out int envIntValue)) + continue; + + property.SetValue(objectToLookAt, envIntValue); + } + else if (property.PropertyType == typeof(bool)) + { + if(!bool.TryParse(envValue, out bool envBoolValue)) + continue; + + property.SetValue(objectToLookAt, envBoolValue); + } + } + } + } } \ No newline at end of file