Skip to content

Commit

Permalink
Add AddFileConfigurationSourceOptions, AddFileConfigurationSourceOpti…
Browse files Browse the repository at this point in the history
…onsBuilder; addFile configuration override secrets.json
  • Loading branch information
thohng committed May 13, 2024
1 parent 99ef526 commit bc224f4
Show file tree
Hide file tree
Showing 6 changed files with 90 additions and 21 deletions.
25 changes: 14 additions & 11 deletions src/NetLah.Extensions.Configuration/AddFileConfigurationSource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,27 @@ namespace NetLah.Extensions.Configuration;

public class AddFileConfigurationSource : IConfigurationSource
{
private readonly IConfigurationSection _configurationSection;
private readonly bool? _throwIfNotSupport;
private readonly AddFileConfigurationSourceOptions _options;
private readonly AddFileOptions _defaultOptions;
private string? _lastAddFileState;
private IConfigurationRoot? _lastConfiguration;

public AddFileConfigurationSource(IConfigurationSection configurationSection, bool? throwIfNotSupport = null)
public AddFileConfigurationSource(AddFileConfigurationSourceOptions options)
{
_configurationSection = configurationSection ?? throw new ArgumentNullException(nameof(configurationSection));
_throwIfNotSupport = throwIfNotSupport;
_options = options ?? throw new ArgumentNullException(nameof(options));
if (options.ConfigurationSection == null)
{
throw new ArgumentNullException(nameof(options.ConfigurationSection));
}
_defaultOptions = new AddFileOptions { Optional = true, ReloadOnChange = true };
}

public IConfigurationProvider Build(IConfigurationBuilder builder)
{
var logger = Helper.GetLogger();
var configurationSection = _options.ConfigurationSection;

var settingLines = _configurationSection.AsEnumerable()
var settingLines = configurationSection.AsEnumerable()
.OrderBy(kv => kv.Key, StringComparer.OrdinalIgnoreCase)
.Select(kv => $"{kv.Key}={kv.Value}")
.ToArray();
Expand All @@ -45,7 +48,7 @@ public IConfigurationProvider Build(IConfigurationBuilder builder)
#endif
configurationBuilder.SetFileProvider(builder.GetFileProvider());

foreach (var item in _configurationSection.GetChildren())
foreach (var item in configurationSection.GetChildren())
{
if (item.Value == null && item["Type"] is { } typeValue1)
{
Expand All @@ -69,7 +72,7 @@ public IConfigurationProvider Build(IConfigurationBuilder builder)
}
}

foreach (var item in _configurationSection.GetChildren())
foreach (var item in configurationSection.GetChildren())
{
if (item.Value is { } value1)
{
Expand Down Expand Up @@ -128,12 +131,12 @@ void AddFile(AddFileSource source)
{
if (source.IsEnableLogging())
{
logger.LogError("AddFile is not supported file extension {extension} of file {sourceFile}", ext, source.Path);
logger.LogError("AddFile is not supported file extension {extension} with {sourceFile}", ext, source.Path);
}

if (_defaultOptions.ThrowIfNotSupport ?? _throwIfNotSupport ?? false)
if (_defaultOptions.ThrowIfNotSupport ?? _options.ThrowIfNotSupport ?? false)
{
throw new Exception($"AddFile is not supported file extension {ext}, only support .json, .ini and .xml. AddFile source {source.Path}");
throw new Exception($"AddFile is not supported file extension {ext}, only support .json, .ini and .xml with file {source.Path}");
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using Microsoft.Extensions.Configuration;

namespace NetLah.Extensions.Configuration;

public class AddFileConfigurationSourceOptions
{
public AddFileConfigurationSourceOptions(IConfigurationSection configurationSection)
{
ConfigurationSection = configurationSection;
}

public IConfigurationSection ConfigurationSection { get; set; }

public bool? ThrowIfNotSupport { get; set; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace NetLah.Extensions.Configuration;

public class AddFileConfigurationSourceOptionsBuilder
{
public AddFileConfigurationSourceOptionsBuilder(string sectionKey)
{
SectionKey = sectionKey;
}

public string SectionKey { get; }

public bool? ThrowIfNotSupport { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ public sealed class ConfigurationBuilderBuilder
private BuilderOrManager? _builderOrManager;
private IConfiguration? _configuration;
private IEnumerable<KeyValuePair<string, string?>>? _initialData;
private AddFileConfigurationSourceOptionsBuilder? _addFile;

private BuilderOrManager ConfigureBuilder()
{
Expand Down Expand Up @@ -172,7 +173,15 @@ public ConfigurationBuilderBuilder WithInMemory(IEnumerable<KeyValuePair<string,

public ConfigurationBuilderBuilder WithAddFileConfiguration(string sectionKey = "AddFile", bool? throwIfNotSupport = null)
{
return WithAddPostConfiguration(builder => builder.AddAddFileConfiguration(sectionKey, throwIfNotSupport));
if (!_configurePostConfigActions.Contains(ConfigureAddFile))
{
_configurePostConfigActions.Add(ConfigureAddFile);
}
_addFile = new AddFileConfigurationSourceOptionsBuilder(sectionKey)
{
ThrowIfNotSupport = throwIfNotSupport,
};
return ResetBuilder();
}

public ConfigurationBuilderBuilder WithTransformConfiguration(string sectionKey = "Transform")
Expand All @@ -193,4 +202,12 @@ public static ConfigurationBuilderBuilder Create(Assembly assembly, string[]? ar
public static ConfigurationBuilderBuilder Create(string[]? args = null)
=> new ConfigurationBuilderBuilder()
.WithCommandLines(args);

private void ConfigureAddFile(IConfigurationBuilder builder)
{
if (_addFile != null)
{
builder.AddAddFileConfiguration(_addFile);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,42 @@ public static TConfigurationBuilder AddTransformConfiguration<TConfigurationBuil
public static TConfigurationBuilder AddAddFileConfiguration<TConfigurationBuilder>(this TConfigurationBuilder configBuilder, string sectionKey = "AddFile", bool? throwIfNotSupport = null)
where TConfigurationBuilder : IConfigurationBuilder
{
if (string.IsNullOrWhiteSpace(sectionKey))
return configBuilder.AddAddFileConfiguration(options => options.ThrowIfNotSupport = throwIfNotSupport, sectionKey);
}

internal static TConfigurationBuilder AddAddFileConfiguration<TConfigurationBuilder>(this TConfigurationBuilder configBuilder, AddFileConfigurationSourceOptionsBuilder optionsBuilder)
where TConfigurationBuilder : IConfigurationBuilder
{
return optionsBuilder == null
? throw new ArgumentNullException(nameof(optionsBuilder))
: configBuilder.AddAddFileConfiguration(options =>
{
throw new ArgumentException($"{nameof(sectionKey)} is required", nameof(sectionKey));
}
options.ThrowIfNotSupport = optionsBuilder.ThrowIfNotSupport;
}, optionsBuilder.SectionKey);
}

public static TConfigurationBuilder AddAddFileConfiguration<TConfigurationBuilder>(this TConfigurationBuilder configBuilder, Action<AddFileConfigurationSourceOptions> configureOptions, string sectionKey = "AddFile")
where TConfigurationBuilder : IConfigurationBuilder
{
var configuration = configBuilder is IConfigurationRoot configurationRoot
? configurationRoot
: configBuilder.Build();
? configurationRoot
: configBuilder.Build();

var configurationSection = configuration.GetSection(sectionKey);

var options = new AddFileConfigurationSourceOptions(configurationSection);
configureOptions(options);

return configBuilder.AddAddFileConfiguration(options);
}

internal static TConfigurationBuilder AddAddFileConfiguration<TConfigurationBuilder>(this TConfigurationBuilder configBuilder, AddFileConfigurationSourceOptions options)
where TConfigurationBuilder : IConfigurationBuilder
{
var sources = configBuilder.Sources;
var lastIndexJson = FindLastIndex(sources, s => s is JsonConfigurationSource js && js.Path != "secrets.json");
var lastIndexJson = FindLastIndex(sources, s => s is JsonConfigurationSource js); // && js.Path != "secrets.json")
lastIndexJson = lastIndexJson >= 0 ? lastIndexJson + 1 : sources.Count;
sources.Insert(lastIndexJson, new AddFileConfigurationSource(configurationSection, throwIfNotSupport));
sources.Insert(lastIndexJson, new AddFileConfigurationSource(options));

return configBuilder;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -941,15 +941,15 @@ public void AddFileConfigurationDevelopmentSecrets_NoSources()
AssertProviders(configuration, new[] {
"JsonConfigurationProvider",
"JsonConfigurationProvider",
"ChainedConfigurationProvider",
"JsonConfigurationProvider",
"ChainedConfigurationProvider",
"EnvironmentVariablesConfigurationProvider",
}, new[] {
"appsettings.json",
"appsettings.Development.json",
null,
"secrets.json",
null,
null,
});

AssertDevelopment(configuration);
Expand Down

0 comments on commit bc224f4

Please sign in to comment.