// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see https://www.gnu.org/licenses/. // namespace slskd.Configuration { using System; using System.IO; using System.Linq; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.FileProviders; using YamlDotNet.Core; using YamlDotNet.RepresentationModel; /// /// Extension methods for adding . /// public static class YamlConfigurationExtensions { /// /// Adds a YAML configuration source to . /// /// The to which to add . /// /// Path relative to the base path stored in of . /// /// The type from which to map properties. /// 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 updated to use to access the file. /// The . public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, Type targetType, 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.TargetType = targetType; s.Optional = optional; s.ReloadOnChange = reloadOnChange; s.NormalizeKeys = normalizeKeys; s.FileProvider = provider; s.ResolveFileProvider(); }); } /// /// Adds a YAML configuration source to . /// /// The to which to add. /// Configures the source. /// The updated . public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, Action configureSource) => builder.Add(configureSource); } /// /// A YAML file based . /// public class YamlConfigurationProvider : FileConfigurationProvider { /// /// Initializes a new instance of the class. /// /// The source settings. public YamlConfigurationProvider(YamlConfigurationSource source) : base(source) { TargetType = source.TargetType; Namespace = TargetType.Namespace.Split('.').First(); NormalizeKeys = source.NormalizeKeys; } private Type TargetType { get; set; } private string Namespace { get; set; } private bool NormalizeKeys { get; set; } private string[] NullValues { get; } = new[] { "~", "null", string.Empty }; /// /// Loads the YAML data from a stream. /// /// The stream to read. public override void Load(Stream stream) { try { // clear the data collection before we populate // not doing this will cause array and dictionary keys // to get "stuck" when the config is reloaded Data.Clear(); using var reader = new StreamReader(stream); var yaml = new YamlStream(); yaml.Load(reader); if (yaml.Documents.Count > 0) { var rootNode = (YamlMappingNode)yaml.Documents[0].RootNode; Traverse(rootNode, Namespace); } } 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) { 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())); } } } } /// /// Represents a YAML file as an . /// public class YamlConfigurationSource : FileConfigurationSource { /// /// Gets or sets the type from which to map properties. /// public Type TargetType { get; set; } /// /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). /// public bool NormalizeKeys { get; set; } /// /// Builds the for this source. /// /// The . /// A . public override IConfigurationProvider Build(IConfigurationBuilder builder) { EnsureDefaults(builder); return new YamlConfigurationProvider(this); } } }