From 38febbe791609e5266ee4ce8888d5399f4033d89 Mon Sep 17 00:00:00 2001 From: hazre <37149950+hazre@users.noreply.github.com> Date: Fri, 29 Aug 2025 20:04:07 +0200 Subject: [PATCH] Add .env integration closes #105 --- .gitignore | 6 +++ ThunderstoreCLI/Configuration/Config.cs | 5 +++ ThunderstoreCLI/Configuration/DotEnv.cs | 55 +++++++++++++++++++++++++ 3 files changed, 66 insertions(+) create mode 100644 ThunderstoreCLI/Configuration/DotEnv.cs diff --git a/.gitignore b/.gitignore index 475ece6..437fa46 100644 --- a/.gitignore +++ b/.gitignore @@ -366,3 +366,9 @@ FodyWeavers.xsd # Rider config directory .idea/ + +# Environment files +*.env +*.env.* +!*.env.template +!*.env.*.template diff --git a/ThunderstoreCLI/Configuration/Config.cs b/ThunderstoreCLI/Configuration/Config.cs index ff35a83..7909c05 100644 --- a/ThunderstoreCLI/Configuration/Config.cs +++ b/ThunderstoreCLI/Configuration/Config.cs @@ -32,6 +32,11 @@ private Config() } public static Config FromCLI(IConfigProvider cliConfig) { + var environment = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") + ?? Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") + ?? Environment.GetEnvironmentVariable("ENVIRONMENT"); + DotEnv.LoadAll(environment); + List providers = new(); providers.Add(cliConfig); providers.Add(new EnvironmentConfig()); diff --git a/ThunderstoreCLI/Configuration/DotEnv.cs b/ThunderstoreCLI/Configuration/DotEnv.cs new file mode 100644 index 0000000..f444279 --- /dev/null +++ b/ThunderstoreCLI/Configuration/DotEnv.cs @@ -0,0 +1,55 @@ +namespace ThunderstoreCLI.Configuration; + +public static class DotEnv +{ + public static void Load(string filePath) + { + if (!File.Exists(filePath)) + return; + + foreach (var line in File.ReadAllLines(filePath)) + { + if (string.IsNullOrWhiteSpace(line) || line.TrimStart().StartsWith('#')) + continue; + + var parts = line.Split('=', 2); + if (parts.Length != 2) + continue; + + var key = parts[0].Trim(); + var value = parts[1].Trim(); + + if (value.Length >= 2) + { + if ((value.StartsWith('"') && value.EndsWith('"')) || + (value.StartsWith('\'') && value.EndsWith('\''))) + { + value = value.Substring(1, value.Length - 2); + } + } + + Environment.SetEnvironmentVariable(key, value); + } + } + + public static void LoadAll(string? environment = null) + { + var filesToLoad = new List { ".env" }; + + if (!string.IsNullOrEmpty(environment)) + { + filesToLoad.Add($".env.{environment}"); + filesToLoad.Add($".env.{environment.ToLowerInvariant()}"); + filesToLoad.Add($".{environment}.env"); + filesToLoad.Add($".{environment.ToLowerInvariant()}.env"); + } + + filesToLoad.Add(".env.local"); + filesToLoad.Add(".local.env"); + + foreach (var file in filesToLoad) + { + Load(file); + } + } +}