From d8eb620c39da4d6ac61fd2d55babb2d73558c9e6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 11 Jul 2021 22:08:50 -0500 Subject: rename Configuration namespace to ConfigurationSources --- .../CommandLineConfigurationSource.cs | 157 ----------------- .../DefaultValueConfigurationSource.cs | 136 --------------- .../EnvironmentVariableConfigurationSource.cs | 151 ---------------- .../Configuration/YamlConfigurationSource.cs | 191 --------------------- .../CommandLineConfigurationSource.cs | 157 +++++++++++++++++ .../DefaultValueConfigurationSource.cs | 136 +++++++++++++++ .../EnvironmentVariableConfigurationSource.cs | 151 ++++++++++++++++ .../YamlConfigurationSource.cs | 191 +++++++++++++++++++++ src/slskd/Program.cs | 2 +- 9 files changed, 636 insertions(+), 636 deletions(-) delete mode 100644 src/slskd/Common/Configuration/CommandLineConfigurationSource.cs delete mode 100644 src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs delete mode 100644 src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs delete mode 100644 src/slskd/Common/Configuration/YamlConfigurationSource.cs create mode 100644 src/slskd/Common/ConfigurationSources/CommandLineConfigurationSource.cs create mode 100644 src/slskd/Common/ConfigurationSources/DefaultValueConfigurationSource.cs create mode 100644 src/slskd/Common/ConfigurationSources/EnvironmentVariableConfigurationSource.cs create mode 100644 src/slskd/Common/ConfigurationSources/YamlConfigurationSource.cs (limited to 'src') diff --git a/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs b/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs deleted file mode 100644 index 6cf59808..00000000 --- a/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs +++ /dev/null @@ -1,157 +0,0 @@ -// -// 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.Linq; - using System.Reflection; - using Microsoft.Extensions.Configuration; - using Utility.CommandLine; - - /// - /// Extension methods for adding . - /// - public static class CommandLineConfigurationExtensions - { - /// - /// Adds a command line argument configuration soruce to . - /// - /// The to which to add. - /// The type from which to map properties. - /// The command line string from which to parse arguments. - /// The updated . - public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, Type targetType, string commandLine = null) - { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (targetType == null) - { - throw new ArgumentNullException(nameof(targetType)); - } - - return builder.AddCommandLine(s => - { - s.TargetType = targetType; - s.CommandLine = commandLine ?? Environment.CommandLine; - }); - } - - /// - /// Adds a command line argument configuration source to . - /// - /// The to which to add. - /// Configures the source. - /// The updated . - public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, Action configureSource) - => builder.Add(configureSource); - } - - /// - /// A command line argument . - /// - public class CommandLineConfigurationProvider : ConfigurationProvider - { - /// - /// Initializes a new instance of the class. - /// - /// The source settings. - public CommandLineConfigurationProvider(CommandLineConfigurationSource source) - { - TargetType = source.TargetType; - Namespace = TargetType.Namespace.Split('.').First(); - CommandLine = source.CommandLine; - } - - private string CommandLine { get; set; } - private string Namespace { get; set; } - private Type TargetType { get; set; } - - /// - /// Parses command line arguments from the specified string and maps them to the corresponding keys. - /// - public override void Load() - { - var dictionary = Arguments.Parse(CommandLine).ArgumentDictionary; - - void Map(Type type, string path) - { - var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); - - foreach (PropertyInfo property in props) - { - var attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(ArgumentAttribute)); - var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant()); - - if (attribute != default) - { - var shortName = ((char)attribute.ConstructorArguments[0].Value).ToString(); - var longName = (string)attribute.ConstructorArguments[1].Value; - var arguments = new[] { shortName, longName }.Where(i => !string.IsNullOrEmpty(i)); - - foreach (var argument in arguments) - { - if (dictionary.ContainsKey(argument)) - { - var value = dictionary[argument].ToString(); - - if (property.PropertyType == typeof(bool) && string.IsNullOrEmpty(value)) - { - value = "true"; - } - - Data[key] = value; - } - } - } - else - { - Map(property.PropertyType, key); - } - } - } - - Map(TargetType, Namespace); - } - } - - /// - /// Represents command line arguments as an . - /// - public class CommandLineConfigurationSource : IConfigurationSource - { - /// - /// Gets or sets the command line string from which to parse arguments. - /// - public string CommandLine { get; set; } - - /// - /// Gets or sets the type from which to map properties. - /// - public Type TargetType { get; set; } - - /// - /// Builds the for this source. - /// - /// The . - /// A . - public IConfigurationProvider Build(IConfigurationBuilder builder) => new CommandLineConfigurationProvider(this); - } -} \ No newline at end of file diff --git a/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs b/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs deleted file mode 100644 index 15cf4070..00000000 --- a/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs +++ /dev/null @@ -1,136 +0,0 @@ -// -// 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.Linq; - using System.Reflection; - using Microsoft.Extensions.Configuration; - - /// - /// Extension methods for adding . - /// - public static class DefaultValueConfigurationExtensions - { - /// - /// Adds a default value configuration source to . - /// - /// The to which to add. - /// The type from which to load default values. - /// The updated . - public static IConfigurationBuilder AddDefaultValues(this IConfigurationBuilder builder, Type targetType) - { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (targetType == null) - { - throw new ArgumentNullException(nameof(targetType)); - } - - return builder.AddDefaultValues(s => - { - s.TargetType = targetType; - }); - } - - /// - /// Adds a default value configuration source to . - /// - /// The to which to add. - /// Configures the source. - /// The updated . - public static IConfigurationBuilder AddDefaultValues(this IConfigurationBuilder builder, Action configureSource) - => builder.Add(configureSource); - } - - /// - /// A default value . - /// - public class DefaultValueConfigurationProvider : ConfigurationProvider - { - /// - /// Initializes a new instance of the class. - /// - /// The source settings. - public DefaultValueConfigurationProvider(DefaultValueConfigurationSource source) - { - TargetType = source.TargetType; - Namespace = TargetType.Namespace.Split('.').First(); - } - - private string Namespace { get; set; } - private Type TargetType { get; set; } - - /// - /// Loads default values from the specified and maps them to the corresponding keys. - /// - public override void Load() - { - void Map(Type type, string path) - { - var defaults = Activator.CreateInstance(type); - var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); - - foreach (PropertyInfo property in props) - { - var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant()); - - if (property.PropertyType.Namespace.StartsWith(Namespace)) - { - Map(property.PropertyType, key); - } - else - { - var value = property.GetValue(defaults); - - if (value != null) - { - Data[key] = value.ToString(); - } - } - } - } - - Map(TargetType, Namespace); - } - } - - /// - /// Represents default values as an . - /// - public class DefaultValueConfigurationSource : IConfigurationSource - { - /// - /// Gets or sets the type from which to map properties. - /// - public Type TargetType { get; set; } - - /// - /// Builds the for this source. - /// - /// The . - /// A . - public IConfigurationProvider Build(IConfigurationBuilder builder) - { - return new DefaultValueConfigurationProvider(this); - } - } -} \ No newline at end of file diff --git a/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs b/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs deleted file mode 100644 index 9a09d4e1..00000000 --- a/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs +++ /dev/null @@ -1,151 +0,0 @@ -// -// 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.Linq; - using System.Reflection; - using Microsoft.Extensions.Configuration; - using Utility.EnvironmentVariables; - - /// - /// Extension methods for adding . - /// - public static class EnvironmentVariableConfigurationExtensions - { - /// - /// Adds an environment variable configuration source to . - /// - /// The to which to add. - /// The type from which to map properties. - /// A prefix to prepend to all variable names. - /// The updated . - public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, Type targetType, string prefix = null) - { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (targetType == null) - { - throw new ArgumentNullException(nameof(targetType)); - } - - return builder.AddEnvironmentVariables(s => - { - s.TargetType = targetType; - s.Prefix = prefix ?? string.Empty; - }); - } - - /// - /// Adds an enviroment variable configuration source to . - /// - /// The to which to add. - /// Configures the source. - /// The updated . - public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, Action configureSource) - => builder.Add(configureSource); - } - - /// - /// An enviroment variable . - /// - public class EnvironmentVariableConfigurationProvider : ConfigurationProvider - { - /// - /// Initializes a new instance of the class. - /// - /// The source settings. - public EnvironmentVariableConfigurationProvider(EnvironmentVariableConfigurationSource source) - { - TargetType = source.TargetType; - Namespace = TargetType.Namespace.Split('.').First(); - Prefix = source.Prefix; - } - - private Type TargetType { get; set; } - private string Namespace { get; set; } - private string Prefix { get; set; } - - /// - /// Loads environment variables and maps them to the corresponding keys. - /// - public override void Load() - { - void Map(Type type, string path) - { - var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); - - foreach (PropertyInfo property in props) - { - var attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(EnvironmentVariableAttribute)); - var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant()); - - if (attribute != default) - { - var name = (string)attribute.ConstructorArguments[0].Value; - - if (!string.IsNullOrEmpty(name)) - { - var value = Environment.GetEnvironmentVariable(Prefix + name); - - if (value != null) - { - Data[key] = value.ToString(); - } - } - } - else - { - Map(property.PropertyType, key); - } - } - } - - Map(TargetType, Namespace); - } - } - - /// - /// Represents environment variables as an . - /// - public class EnvironmentVariableConfigurationSource : IConfigurationSource - { - /// - /// Gets or sets the type from which to map properties. - /// - public Type TargetType { get; set; } - - /// - /// Gets or sets a prefix to prepend to all variable names. - /// - public string Prefix { get; set; } - - /// - /// Builds the for this source. - /// - /// The . - /// A . - public IConfigurationProvider Build(IConfigurationBuilder builder) - { - return new EnvironmentVariableConfigurationProvider(this); - } - } -} \ No newline at end of file diff --git a/src/slskd/Common/Configuration/YamlConfigurationSource.cs b/src/slskd/Common/Configuration/YamlConfigurationSource.cs deleted file mode 100644 index 82e2227d..00000000 --- a/src/slskd/Common/Configuration/YamlConfigurationSource.cs +++ /dev/null @@ -1,191 +0,0 @@ -// -// 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 - { - 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) - { - 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())); - } - } - } - } - - /// - /// 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); - } - } -} \ No newline at end of file diff --git a/src/slskd/Common/ConfigurationSources/CommandLineConfigurationSource.cs b/src/slskd/Common/ConfigurationSources/CommandLineConfigurationSource.cs new file mode 100644 index 00000000..724a52b3 --- /dev/null +++ b/src/slskd/Common/ConfigurationSources/CommandLineConfigurationSource.cs @@ -0,0 +1,157 @@ +// +// 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.ConfigurationSources +{ + using System; + using System.Linq; + using System.Reflection; + using Microsoft.Extensions.Configuration; + using Utility.CommandLine; + + /// + /// Extension methods for adding . + /// + public static class CommandLineConfigurationExtensions + { + /// + /// Adds a command line argument configuration soruce to . + /// + /// The to which to add. + /// The type from which to map properties. + /// The command line string from which to parse arguments. + /// The updated . + public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, Type targetType, string commandLine = null) + { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + + if (targetType == null) + { + throw new ArgumentNullException(nameof(targetType)); + } + + return builder.AddCommandLine(s => + { + s.TargetType = targetType; + s.CommandLine = commandLine ?? Environment.CommandLine; + }); + } + + /// + /// Adds a command line argument configuration source to . + /// + /// The to which to add. + /// Configures the source. + /// The updated . + public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, Action configureSource) + => builder.Add(configureSource); + } + + /// + /// A command line argument . + /// + public class CommandLineConfigurationProvider : ConfigurationProvider + { + /// + /// Initializes a new instance of the class. + /// + /// The source settings. + public CommandLineConfigurationProvider(CommandLineConfigurationSource source) + { + TargetType = source.TargetType; + Namespace = TargetType.Namespace.Split('.').First(); + CommandLine = source.CommandLine; + } + + private string CommandLine { get; set; } + private string Namespace { get; set; } + private Type TargetType { get; set; } + + /// + /// Parses command line arguments from the specified string and maps them to the corresponding keys. + /// + public override void Load() + { + var dictionary = Arguments.Parse(CommandLine).ArgumentDictionary; + + void Map(Type type, string path) + { + var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); + + foreach (PropertyInfo property in props) + { + var attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(ArgumentAttribute)); + var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant()); + + if (attribute != default) + { + var shortName = ((char)attribute.ConstructorArguments[0].Value).ToString(); + var longName = (string)attribute.ConstructorArguments[1].Value; + var arguments = new[] { shortName, longName }.Where(i => !string.IsNullOrEmpty(i)); + + foreach (var argument in arguments) + { + if (dictionary.ContainsKey(argument)) + { + var value = dictionary[argument].ToString(); + + if (property.PropertyType == typeof(bool) && string.IsNullOrEmpty(value)) + { + value = "true"; + } + + Data[key] = value; + } + } + } + else + { + Map(property.PropertyType, key); + } + } + } + + Map(TargetType, Namespace); + } + } + + /// + /// Represents command line arguments as an . + /// + public class CommandLineConfigurationSource : IConfigurationSource + { + /// + /// Gets or sets the command line string from which to parse arguments. + /// + public string CommandLine { get; set; } + + /// + /// Gets or sets the type from which to map properties. + /// + public Type TargetType { get; set; } + + /// + /// Builds the for this source. + /// + /// The . + /// A . + public IConfigurationProvider Build(IConfigurationBuilder builder) => new CommandLineConfigurationProvider(this); + } +} \ No newline at end of file diff --git a/src/slskd/Common/ConfigurationSources/DefaultValueConfigurationSource.cs b/src/slskd/Common/ConfigurationSources/DefaultValueConfigurationSource.cs new file mode 100644 index 00000000..1784ce26 --- /dev/null +++ b/src/slskd/Common/ConfigurationSources/DefaultValueConfigurationSource.cs @@ -0,0 +1,136 @@ +// +// 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.ConfigurationSources +{ + using System; + using System.Linq; + using System.Reflection; + using Microsoft.Extensions.Configuration; + + /// + /// Extension methods for adding . + /// + public static class DefaultValueConfigurationExtensions + { + /// + /// Adds a default value configuration source to . + /// + /// The to which to add. + /// The type from which to load default values. + /// The updated . + public static IConfigurationBuilder AddDefaultValues(this IConfigurationBuilder builder, Type targetType) + { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + + if (targetType == null) + { + throw new ArgumentNullException(nameof(targetType)); + } + + return builder.AddDefaultValues(s => + { + s.TargetType = targetType; + }); + } + + /// + /// Adds a default value configuration source to . + /// + /// The to which to add. + /// Configures the source. + /// The updated . + public static IConfigurationBuilder AddDefaultValues(this IConfigurationBuilder builder, Action configureSource) + => builder.Add(configureSource); + } + + /// + /// A default value . + /// + public class DefaultValueConfigurationProvider : ConfigurationProvider + { + /// + /// Initializes a new instance of the class. + /// + /// The source settings. + public DefaultValueConfigurationProvider(DefaultValueConfigurationSource source) + { + TargetType = source.TargetType; + Namespace = TargetType.Namespace.Split('.').First(); + } + + private string Namespace { get; set; } + private Type TargetType { get; set; } + + /// + /// Loads default values from the specified and maps them to the corresponding keys. + /// + public override void Load() + { + void Map(Type type, string path) + { + var defaults = Activator.CreateInstance(type); + var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); + + foreach (PropertyInfo property in props) + { + var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant()); + + if (property.PropertyType.Namespace.StartsWith(Namespace)) + { + Map(property.PropertyType, key); + } + else + { + var value = property.GetValue(defaults); + + if (value != null) + { + Data[key] = value.ToString(); + } + } + } + } + + Map(TargetType, Namespace); + } + } + + /// + /// Represents default values as an . + /// + public class DefaultValueConfigurationSource : IConfigurationSource + { + /// + /// Gets or sets the type from which to map properties. + /// + public Type TargetType { get; set; } + + /// + /// Builds the for this source. + /// + /// The . + /// A . + public IConfigurationProvider Build(IConfigurationBuilder builder) + { + return new DefaultValueConfigurationProvider(this); + } + } +} \ No newline at end of file diff --git a/src/slskd/Common/ConfigurationSources/EnvironmentVariableConfigurationSource.cs b/src/slskd/Common/ConfigurationSources/EnvironmentVariableConfigurationSource.cs new file mode 100644 index 00000000..94823d11 --- /dev/null +++ b/src/slskd/Common/ConfigurationSources/EnvironmentVariableConfigurationSource.cs @@ -0,0 +1,151 @@ +// +// 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.ConfigurationSources +{ + using System; + using System.Linq; + using System.Reflection; + using Microsoft.Extensions.Configuration; + using Utility.EnvironmentVariables; + + /// + /// Extension methods for adding . + /// + public static class EnvironmentVariableConfigurationExtensions + { + /// + /// Adds an environment variable configuration source to . + /// + /// The to which to add. + /// The type from which to map properties. + /// A prefix to prepend to all variable names. + /// The updated . + public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, Type targetType, string prefix = null) + { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + + if (targetType == null) + { + throw new ArgumentNullException(nameof(targetType)); + } + + return builder.AddEnvironmentVariables(s => + { + s.TargetType = targetType; + s.Prefix = prefix ?? string.Empty; + }); + } + + /// + /// Adds an enviroment variable configuration source to . + /// + /// The to which to add. + /// Configures the source. + /// The updated . + public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, Action configureSource) + => builder.Add(configureSource); + } + + /// + /// An enviroment variable . + /// + public class EnvironmentVariableConfigurationProvider : ConfigurationProvider + { + /// + /// Initializes a new instance of the class. + /// + /// The source settings. + public EnvironmentVariableConfigurationProvider(EnvironmentVariableConfigurationSource source) + { + TargetType = source.TargetType; + Namespace = TargetType.Namespace.Split('.').First(); + Prefix = source.Prefix; + } + + private Type TargetType { get; set; } + private string Namespace { get; set; } + private string Prefix { get; set; } + + /// + /// Loads environment variables and maps them to the corresponding keys. + /// + public override void Load() + { + void Map(Type type, string path) + { + var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); + + foreach (PropertyInfo property in props) + { + var attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(EnvironmentVariableAttribute)); + var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant()); + + if (attribute != default) + { + var name = (string)attribute.ConstructorArguments[0].Value; + + if (!string.IsNullOrEmpty(name)) + { + var value = Environment.GetEnvironmentVariable(Prefix + name); + + if (value != null) + { + Data[key] = value.ToString(); + } + } + } + else + { + Map(property.PropertyType, key); + } + } + } + + Map(TargetType, Namespace); + } + } + + /// + /// Represents environment variables as an . + /// + public class EnvironmentVariableConfigurationSource : IConfigurationSource + { + /// + /// Gets or sets the type from which to map properties. + /// + public Type TargetType { get; set; } + + /// + /// Gets or sets a prefix to prepend to all variable names. + /// + public string Prefix { get; set; } + + /// + /// Builds the for this source. + /// + /// The . + /// A . + public IConfigurationProvider Build(IConfigurationBuilder builder) + { + return new EnvironmentVariableConfigurationProvider(this); + } + } +} \ No newline at end of file diff --git a/src/slskd/Common/ConfigurationSources/YamlConfigurationSource.cs b/src/slskd/Common/ConfigurationSources/YamlConfigurationSource.cs new file mode 100644 index 00000000..654f5b2e --- /dev/null +++ b/src/slskd/Common/ConfigurationSources/YamlConfigurationSource.cs @@ -0,0 +1,191 @@ +// +// 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.ConfigurationSources +{ + 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 + { + 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) + { + 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())); + } + } + } + } + + /// + /// 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); + } + } +} \ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 987a39a0..01618efb 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -36,7 +36,7 @@ namespace slskd using Serilog; using Serilog.Events; using Serilog.Sinks.Grafana.Loki; - using slskd.Configuration; + using slskd.ConfigurationSources; using slskd.Cryptography; using slskd.Validation; using Utility.CommandLine; -- cgit v1.2.3