From 9b433eb9266f26f21c82def6b6c720974a8a0bde Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 23 Jan 2021 13:39:45 -0600 Subject: add configuration providers --- .../Configuration/YamlConfigurationSource.cs | 158 +++++++++++++++++++++ 1 file changed, 158 insertions(+) create mode 100644 src/slskd/Common/Configuration/YamlConfigurationSource.cs (limited to 'src/slskd/Common/Configuration/YamlConfigurationSource.cs') diff --git a/src/slskd/Common/Configuration/YamlConfigurationSource.cs b/src/slskd/Common/Configuration/YamlConfigurationSource.cs new file mode 100644 index 00000000..220cc00b --- /dev/null +++ b/src/slskd/Common/Configuration/YamlConfigurationSource.cs @@ -0,0 +1,158 @@ +namespace slskd +{ + using Microsoft.Extensions.Configuration; + using Microsoft.Extensions.FileProviders; + using System; + using System.IO; + using System.Linq; + using YamlDotNet.Core; + using YamlDotNet.RepresentationModel; + + /// + /// Extension methods for adding . + /// + public static class YamlConfigurationExtensions + { + /// + /// Adds a YAML configuration source to . + /// + /// The to add to. + /// Path relative to the base path stored in + /// of . + /// Whether the file is optional. + /// Whether the configuration should be reloaded if the file changes. + /// A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). + /// The to use to access the file. + /// The . + public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, bool optional = true, bool reloadOnChange = false, bool normalizeKeys = true, IFileProvider provider = null) + { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + + if (string.IsNullOrEmpty(path)) + { + throw new ArgumentException("File path must be a non-empty string.", nameof(path)); + } + + return builder.AddYamlFile(s => + { + s.Path = path; + s.Optional = optional; + s.ReloadOnChange = reloadOnChange; + s.NormalizeKeys = normalizeKeys; + s.FileProvider = provider; + s.ResolveFileProvider(); + }); + } + + /// + /// Adds a YAML configuration source to . + /// + /// The to add to. + /// Configures the source. + /// The . + public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, Action configureSource) + => builder.Add(configureSource); + } + + /// + /// Represents a YAML file as an . + /// + public class YamlConfigurationSource : FileConfigurationSource + { + /// + /// Builds the for this source. + /// + /// The . + /// A + public override IConfigurationProvider Build(IConfigurationBuilder builder) + { + EnsureDefaults(builder); + return new YamlConfigurationProvider(this); + } + + /// + /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). + /// + public bool NormalizeKeys { get; set; } + } + + /// + /// A YAML file based . + /// + public class YamlConfigurationProvider : FileConfigurationProvider + { + /// + /// Initializes a new instance with the specified source. + /// + /// The source settings. + public YamlConfigurationProvider(YamlConfigurationSource source) + : base(source) + { + NormalizeKeys = source.NormalizeKeys; + } + + private bool NormalizeKeys { get; set; } + private string[] NullValues { get; } = new[] { "~", "null", "" }; + + /// + /// Loads the YAML data from a stream. + /// + /// The stream to read. + public override void Load(Stream stream) + { + try + { + using var reader = new StreamReader(stream); + + var yaml = new YamlStream(); + yaml.Load(reader); + + var rootNode = (YamlMappingNode)yaml.Documents[0].RootNode; + + Traverse(rootNode); + } + catch (YamlException e) + { + throw new FormatException("Could not parse the YAML file.", e); + } + } + + private void Traverse(YamlNode root, string path = null) + { + string Normalize(string str) => NormalizeKeys ? str?.Replace("_", string.Empty).Replace("-", string.Empty).ToLowerInvariant() : str; + + if (root is YamlScalarNode scalar) + { + if (Data.ContainsKey(Normalize(path))) + { + throw new FormatException($"A duplicate key '{Normalize(path)}' was found."); + } + + var value = NullValues.Contains(scalar.Value.ToLower()) ? null : scalar.Value; + + if (value != null) + { + Data[Normalize(path)] = NullValues.Contains(scalar.Value.ToLower()) ? null : scalar.Value; + } + } + else if (root is YamlMappingNode map) + { + foreach (var node in map.Children) + { + var key = Normalize(((YamlScalarNode)node.Key).Value); + Traverse(node.Value, path == null ? key : ConfigurationPath.Combine(path, key)); + } + } + else if (root is YamlSequenceNode sequence) + { + for (int i = 0; i < sequence.Children.Count(); i++) + { + Traverse(sequence.Children[i], ConfigurationPath.Combine(path, i.ToString())); + } + } + } + } +} -- cgit v1.2.3