From 487860ce5d0303e3839f6d658f8fb5fa5f162ec8 Mon Sep 17 00:00:00 2001 From: Eoin Motherway <25342760+YuKitsune@users.noreply.github.com> Date: Sat, 7 Oct 2023 12:39:07 +1000 Subject: [PATCH] Fix env files not being read from parent directories --- .../EnvConfigurationSourceTests.cs | 12 ++++++++++++ .../EnvConfigurationSource.cs | 2 +- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/YuKitsune.Configuration.Env/YuKitsune.Configuration.Env.Tests/EnvConfigurationSourceTests.cs b/YuKitsune.Configuration.Env/YuKitsune.Configuration.Env.Tests/EnvConfigurationSourceTests.cs index e3be3cf..09b6ecd 100644 --- a/YuKitsune.Configuration.Env/YuKitsune.Configuration.Env.Tests/EnvConfigurationSourceTests.cs +++ b/YuKitsune.Configuration.Env/YuKitsune.Configuration.Env.Tests/EnvConfigurationSourceTests.cs @@ -1,3 +1,4 @@ +using System; using System.IO; using Microsoft.Extensions.Configuration; using Xunit; @@ -26,5 +27,16 @@ public void CanLoadDotPrefixedFiles_FromRelativePath() var config = new ConfigurationBuilder().AddEnvFile(envFile).Build(); Assert.Equal("val", config["var"]); } + + [Fact] + public void CanLoadDotPrefixedFiles_FromParentDirectory() + { + var parentDirectory = new DirectoryInfo(Environment.CurrentDirectory).Parent!.FullName; + var envFile = Path.Join(parentDirectory, ".env"); + File.WriteAllText(envFile, "var=val"); + + var config = new ConfigurationBuilder().AddEnvFile(envFile).Build(); + Assert.Equal("val", config["var"]); + } } } \ No newline at end of file diff --git a/YuKitsune.Configuration.Env/YuKitsune.Configuration.Env/EnvConfigurationSource.cs b/YuKitsune.Configuration.Env/YuKitsune.Configuration.Env/EnvConfigurationSource.cs index 72fe3fc..eb1b74f 100644 --- a/YuKitsune.Configuration.Env/YuKitsune.Configuration.Env/EnvConfigurationSource.cs +++ b/YuKitsune.Configuration.Env/YuKitsune.Configuration.Env/EnvConfigurationSource.cs @@ -23,7 +23,7 @@ public class EnvConfigurationSource : FileConfigurationSource public override IConfigurationProvider Build(IConfigurationBuilder builder) { // This is necessary as the default PhysicalFileProvider filters out dot-prefixed files (.env) - FileProvider = MakeFileProvider(AppContext.BaseDirectory); + FileProvider ??= MakeFileProvider(AppContext.BaseDirectory); EnsureDefaults(builder); return new EnvConfigurationProvider(this);