aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJP Dillingham <jpdillingham@gmail.com>2021-01-21 23:04:02 -0600
committerJP Dillingham <jpdillingham@gmail.com>2021-01-21 23:04:02 -0600
commite52ca241f55e47e1e707134097ad5c4f8a641b07 (patch)
tree16b79b2cbe82738d7e3471c34326aeabc3387c56
parent4afc5f54c37a1bcc7b2593e4a04d4cdf9c5f8b12 (diff)
downloadslskd-e52ca241f55e47e1e707134097ad5c4f8a641b07.tar.gz
move stuff to common
-rw-r--r--src/slskd/Common/Configuration.cs153
-rw-r--r--src/slskd/Common/YamlConfigurationSource.cs209
2 files changed, 362 insertions, 0 deletions
diff --git a/src/slskd/Common/Configuration.cs b/src/slskd/Common/Configuration.cs
new file mode 100644
index 00000000..621c150e
--- /dev/null
+++ b/src/slskd/Common/Configuration.cs
@@ -0,0 +1,153 @@
+namespace slskd
+{
+ using Microsoft.Extensions.Configuration;
+ using System;
+ using System.Collections;
+ using System.Collections.Generic;
+ using System.Diagnostics;
+ using System.Globalization;
+ using System.Linq;
+ using System.Reflection;
+ using System.Runtime.CompilerServices;
+
+ public class ConfigurationAttribute : Attribute
+ {
+ public ConfigurationAttribute(string key)
+ {
+ Key = key;
+ }
+
+ public string Key { get; set; }
+ }
+
+ public static class Configuration
+ {
+ public static void Populate(this IConfiguration configuration, [CallerMemberName] string caller = default(string))
+ {
+ var type = GetCallingType(caller);
+ var targetProperties = GetTargetProperties(type);
+
+ foreach (var property in targetProperties)
+ {
+ var propertyType = property.Value.PropertyType;
+
+ string value = configuration.GetValue<string>(property.Key);
+ Console.WriteLine($"key {property.Key} value {value}");
+
+ if (string.IsNullOrEmpty(value))
+ {
+ Console.WriteLine("skip");
+ continue;
+ }
+
+ object convertedValue;
+
+ if (propertyType == typeof(bool))
+ {
+ convertedValue = value?.Equals("true", StringComparison.InvariantCultureIgnoreCase) ?? false;
+ }
+ else if (propertyType.IsArray || (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(List<>)))
+ {
+ Type valueType;
+
+ if (propertyType.IsArray)
+ {
+ valueType = propertyType.GetElementType();
+ }
+ else
+ {
+ valueType = propertyType.GetGenericArguments()[0];
+ }
+
+ // create a list to store converted values
+ Type valueListType = typeof(List<>).MakeGenericType(valueType);
+ var valueList = (IList)Activator.CreateInstance(valueListType);
+
+ // populate the list
+ foreach (object v in value.Split(',').Select(s => s.Trim()))
+ {
+ valueList.Add(ChangeType(v, property.Key, valueType));
+ }
+
+ if (propertyType.IsArray)
+ {
+ var valueArray = Array.CreateInstance(propertyType.GetElementType(), valueList.Count);
+
+ for (int i = 0; i < valueArray.Length; i++)
+ {
+ valueArray.SetValue(valueList[i], i);
+ }
+
+ convertedValue = valueArray;
+ }
+ else
+ {
+ convertedValue = valueList;
+ }
+ }
+ else
+ {
+ convertedValue = ChangeType(value, property.Key, property.Value.PropertyType);
+ }
+
+ property.Value.SetValue(null, convertedValue);
+ }
+ }
+
+ private static Type GetCallingType(string caller)
+ {
+ var callingMethod = new StackTrace().GetFrames()
+ .Select(f => f.GetMethod())
+ .FirstOrDefault(m => m.Name == caller);
+
+ if (callingMethod == default(MethodBase))
+ {
+ throw new InvalidOperationException($"Unable to determine the containing type of the calling method '{caller}'. Explicitly specify the originating Type.");
+ }
+
+ return callingMethod.DeclaringType;
+ }
+
+ private static Dictionary<string, PropertyInfo> GetTargetProperties(Type type)
+ {
+ Dictionary<string, PropertyInfo> properties = new Dictionary<string, PropertyInfo>();
+
+ foreach (PropertyInfo property in type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static))
+ {
+ // attempt to fetch the ArgumentAttribute of the property
+ CustomAttributeData attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == typeof(ConfigurationAttribute).Name);
+
+ // if found, extract the Name property and add it to the dictionary
+ if (attribute != default(CustomAttributeData))
+ {
+ string name = ((string)attribute.ConstructorArguments[0].Value)?.Replace("_", string.Empty).Replace("-", string.Empty);
+
+ if (!properties.ContainsKey(name))
+ {
+ properties.Add(name, property);
+ }
+ }
+ }
+
+ return properties;
+ }
+
+ private static object ChangeType(object value, string name, Type type)
+ {
+ try
+ {
+ if (type.IsEnum)
+ {
+ return Enum.Parse(type, (string)value, true);
+ }
+
+ return Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
+ }
+ catch (Exception ex) when (ex is InvalidCastException || ex is FormatException || ex is OverflowException || ex is ArgumentNullException)
+ {
+ string message = $"Failed to convert value '{value}' to target type {type}";
+ throw new ArgumentException(message, name, ex);
+ }
+ }
+ }
+}
diff --git a/src/slskd/Common/YamlConfigurationSource.cs b/src/slskd/Common/YamlConfigurationSource.cs
new file mode 100644
index 00000000..9dde3179
--- /dev/null
+++ b/src/slskd/Common/YamlConfigurationSource.cs
@@ -0,0 +1,209 @@
+/*
+ █▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀ ▀ ▀ ▀▀
+ █ The MIT License (MIT)
+ █
+ █ Copyright (c) 2021 JP Dillingham (jp@dillingham.ws)
+ █
+ █ Permission is hereby granted, free of charge, to any person obtaining a copy
+ █ of this software and associated documentation files (the "Software"), to deal
+ █ in the Software without restriction, including without limitation the rights
+ █ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ █ copies of the Software, and to permit persons to whom the Software is
+ █ furnished to do so, subject to the following conditions:
+ █
+ █ The above copyright notice and this permission notice shall be included in all
+ █ copies or substantial portions of the Software.
+ █
+ █ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ █ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ █ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ █ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ █ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ █ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ █ SOFTWARE.
+ █
+ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀██
+ ██
+ ▀█▄ ██ ▄█▀
+ ▀████▀
+ ▀▀ */
+
+namespace slskd
+{
+ using Microsoft.Extensions.Configuration;
+ using Microsoft.Extensions.FileProviders;
+ using System;
+ using System.IO;
+ using System.Linq;
+ using YamlDotNet.Core;
+ using YamlDotNet.RepresentationModel;
+
+ /// <summary>
+ /// Extension methods for adding <see cref="YamlConfigurationProvider"/>.
+ /// </summary>
+ public static class YamlConfigurationExtensions
+ {
+ /// <summary>
+ /// Adds the YAML configuration provider at <paramref name="path"/> to <paramref name="builder"/>.
+ /// </summary>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param>
+ /// <param name="path">Path relative to the base path stored in
+ /// <see cref="IConfigurationBuilder.Properties"/> of <paramref name="builder"/>.</param>
+ /// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
+ public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path)
+ {
+ return AddYamlFile(builder, provider: null, path: path, optional: false, reloadOnChange: false);
+ }
+
+ /// <summary>
+ /// Adds the YAML configuration provider at <paramref name="path"/> to <paramref name="builder"/>.
+ /// </summary>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param>
+ /// <param name="path">Path relative to the base path stored in
+ /// <see cref="IConfigurationBuilder.Properties"/> of <paramref name="builder"/>.</param>
+ /// <param name="optional">Whether the file is optional.</param>
+ /// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
+ public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, bool optional)
+ {
+ return AddYamlFile(builder, provider: null, path: path, optional: optional, reloadOnChange: false);
+ }
+
+ /// <summary>
+ /// Adds the YAML configuration provider at <paramref name="path"/> to <paramref name="builder"/>.
+ /// </summary>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param>
+ /// <param name="path">Path relative to the base path stored in
+ /// <see cref="IConfigurationBuilder.Properties"/> of <paramref name="builder"/>.</param>
+ /// <param name="optional">Whether the file is optional.</param>
+ /// <param name="reloadOnChange">Whether the configuration should be reloaded if the file changes.</param>
+ /// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
+ public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, bool optional, bool reloadOnChange)
+ {
+ return AddYamlFile(builder, provider: null, path: path, optional: optional, reloadOnChange: reloadOnChange);
+ }
+
+ /// <summary>
+ /// Adds a YAML configuration source to <paramref name="builder"/>.
+ /// </summary>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param>
+ /// <param name="provider">The <see cref="IFileProvider"/> to use to access the file.</param>
+ /// <param name="path">Path relative to the base path stored in
+ /// <see cref="IConfigurationBuilder.Properties"/> of <paramref name="builder"/>.</param>
+ /// <param name="optional">Whether the file is optional.</param>
+ /// <param name="reloadOnChange">Whether the configuration should be reloaded if the file changes.</param>
+ /// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
+ public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, IFileProvider provider, string path, bool optional, bool reloadOnChange)
+ {
+ 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.FileProvider = provider;
+ s.Path = path;
+ s.Optional = optional;
+ s.ReloadOnChange = reloadOnChange;
+ s.ResolveFileProvider();
+ });
+ }
+
+ /// <summary>
+ /// Adds a YAML configuration source to <paramref name="builder"/>.
+ /// </summary>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param>
+ /// <param name="configureSource">Configures the source.</param>
+ /// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
+ public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, Action<YamlConfigurationSource> configureSource)
+ => builder.Add(configureSource);
+ }
+
+ /// <summary>
+ /// Represents a YAML file as an <see cref="IConfigurationSource"/>.
+ /// </summary>
+ public class YamlConfigurationSource : FileConfigurationSource
+ {
+ /// <summary>
+ /// Builds the <see cref="YamlConfigurationProvider"/> for this source.
+ /// </summary>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
+ /// <returns>A <see cref="YamlConfigurationProvider"/></returns>
+ public override IConfigurationProvider Build(IConfigurationBuilder builder)
+ {
+ EnsureDefaults(builder);
+ return new YamlConfigurationProvider(this);
+ }
+ }
+
+ /// <summary>
+ /// A YAML file based <see cref="FileConfigurationProvider"/>.
+ /// </summary>
+ public class YamlConfigurationProvider : FileConfigurationProvider
+ {
+ /// <summary>
+ /// Initializes a new instance with the specified source.
+ /// </summary>
+ /// <param name="source">The source settings.</param>
+ public YamlConfigurationProvider(YamlConfigurationSource source) : base(source) { }
+
+ private string[] NullValues { get; } = new[] { "~", "null", "" };
+
+ /// <summary>
+ /// Loads the YAML data from a stream.
+ /// </summary>
+ /// <param name="stream">The stream to read.</param>
+ 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)
+ {
+ static string Clean(string str) => str?.Replace("_", string.Empty).Replace("-", string.Empty);
+
+ if (root is YamlScalarNode scalar)
+ {
+ if (Data.ContainsKey(Clean(path)))
+ {
+ throw new FormatException($"A duplicate key '{Clean(path)}' was found.");
+ }
+
+ Data[Clean(path)] = NullValues.Contains(scalar.Value.ToLower()) ? null : scalar.Value;
+ }
+ else if (root is YamlMappingNode map)
+ {
+ foreach (var node in map.Children)
+ {
+ var key = Clean(((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()));
+ }
+ }
+ }
+ }
+}