aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jpdillingham@gmail.com>2021-01-23 00:39:50 -0600
committerJP Dillingham <jpdillingham@gmail.com>2021-01-23 00:39:50 -0600
commitff3b1fe36885442a6e40cac23ec8b186ef416e77 (patch)
tree5e15c163d6179fd1f6d5129b97c458fda588c1e1 /src
parentfc9a1aacfb9c4e005fd482ba37394840865e9e61 (diff)
downloadslskd-ff3b1fe36885442a6e40cac23ec8b186ef416e77.tar.gz
broken wip
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Common/CommandLineArgumentConfigurationSource.cs93
-rw-r--r--src/slskd/Common/Configuration.cs151
-rw-r--r--src/slskd/Common/EnvironmentVariableConfigurationSource.cs76
-rw-r--r--src/slskd/Common/Options/InstanceOptions.cs125
-rw-r--r--src/slskd/Common/Options/RuntimeOptions.cs97
-rw-r--r--src/slskd/Common/YamlConfigurationSource.cs214
-rw-r--r--src/slskd/Program.cs30
-rw-r--r--src/slskd/config.yml10
-rw-r--r--src/slskd/slskd.csproj1
9 files changed, 580 insertions, 217 deletions
diff --git a/src/slskd/Common/CommandLineArgumentConfigurationSource.cs b/src/slskd/Common/CommandLineArgumentConfigurationSource.cs
new file mode 100644
index 00000000..1762228d
--- /dev/null
+++ b/src/slskd/Common/CommandLineArgumentConfigurationSource.cs
@@ -0,0 +1,93 @@
+namespace slskd
+{
+ using Microsoft.Extensions.Configuration;
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using Utility.CommandLine;
+
+ public class Argument
+ {
+ public string Description { get; set; }
+ public char ShortName { get; set; }
+ public string LongName { get; set; }
+ public string Key { get; set; }
+ }
+
+ public static class CommandLineArgumentExtensions
+ {
+ public static IConfigurationBuilder MapCommandLineArguments(this IConfigurationBuilder builder, IEnumerable<Argument> map, string commandLine)
+ {
+ if (builder == null)
+ {
+ throw new ArgumentNullException(nameof(builder));
+ }
+
+ return builder.MapCommandLineArguments(s =>
+ {
+ s.Map = map;
+ s.CommandLine = commandLine;
+ });
+ }
+
+ public static IConfigurationBuilder MapCommandLineArguments(this IConfigurationBuilder builder, Action<CommandLineArgumentConfigurationSource> configureSource)
+ => builder.Add(configureSource);
+ }
+
+ public class CommandLineArgumentConfigurationSource : IConfigurationSource
+ {
+ public IEnumerable<Argument> Map { get; set; }
+ public string CommandLine { get; set; }
+
+ public IConfigurationProvider Build(IConfigurationBuilder builder)
+ {
+ return new CommandLineArgumentConfigurationProvider(this);
+ }
+ }
+
+ public class CommandLineArgumentConfigurationProvider : ConfigurationProvider
+ {
+ public CommandLineArgumentConfigurationSource Source { get; set; }
+
+ /// <summary>
+ /// Initializes a new instance with the specified source.
+ /// </summary>
+ /// <param name="source">The source settings.</param>
+ public CommandLineArgumentConfigurationProvider(CommandLineArgumentConfigurationSource source)
+ {
+ Source = source;
+ }
+
+ public override void Load()
+ {
+ var dictionary = Arguments.Parse(Source.CommandLine).ArgumentDictionary;
+
+ foreach (var item in Source.Map)
+ {
+ Console.WriteLine($"Item: {item.Key}");
+
+ if (string.IsNullOrEmpty(item.Key))
+ {
+ continue;
+ }
+
+ var arguments = new[] { item.ShortName.ToString(), item.LongName }.Where(i => !string.IsNullOrEmpty(i));
+
+ foreach (var argument in arguments)
+ {
+ if (dictionary.ContainsKey(argument))
+ {
+ var value = dictionary[argument].ToString();
+
+ if (string.IsNullOrEmpty(value))
+ {
+ value = "true";
+ }
+
+ Data[item.Key] = value;
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/src/slskd/Common/Configuration.cs b/src/slskd/Common/Configuration.cs
deleted file mode 100644
index fca57299..00000000
--- a/src/slskd/Common/Configuration.cs
+++ /dev/null
@@ -1,151 +0,0 @@
-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, Type targetType = null, [CallerMemberName] string caller = default(string))
- {
- var type = targetType ?? GetCallingType(caller);
- var targetProperties = GetTargetProperties(type);
-
- foreach (var property in targetProperties)
- {
- var propertyType = property.Value.PropertyType;
-
- string value = configuration.GetValue<string>(property.Key);
-
- if (string.IsNullOrEmpty(value))
- {
- 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/EnvironmentVariableConfigurationSource.cs b/src/slskd/Common/EnvironmentVariableConfigurationSource.cs
new file mode 100644
index 00000000..36a8ddf1
--- /dev/null
+++ b/src/slskd/Common/EnvironmentVariableConfigurationSource.cs
@@ -0,0 +1,76 @@
+namespace slskd
+{
+ using Microsoft.Extensions.Configuration;
+ using System;
+ using System.Collections.Generic;
+
+ public class EnvironmentVariable
+ {
+ public string Description { get; set; }
+ public string Name { get; set; }
+ public string Key { get; set; }
+ }
+
+ public static class EnvironmentVariableConfigurationExtensions
+ {
+ public static IConfigurationBuilder MapEnvironmentVariables(this IConfigurationBuilder builder, IEnumerable<EnvironmentVariable> map)
+ {
+ if (builder == null)
+ {
+ throw new ArgumentNullException(nameof(builder));
+ }
+
+ return builder.MapEnvironmentVariables(s =>
+ {
+ s.Map = map;
+ });
+ }
+
+ public static IConfigurationBuilder MapEnvironmentVariables(this IConfigurationBuilder builder, Action<EnvironmentVariableConfigurationSource> configureSource)
+ => builder.Add(configureSource);
+ }
+
+ public class EnvironmentVariableConfigurationSource : IConfigurationSource
+ {
+ public IConfigurationProvider Build(IConfigurationBuilder builder)
+ {
+ return new EnvironmentVariableConfigurationProvider(this);
+ }
+
+ public IEnumerable<EnvironmentVariable> Map { get; set; }
+ }
+
+ public class EnvironmentVariableConfigurationProvider : ConfigurationProvider
+ {
+ public EnvironmentVariableConfigurationSource Source { get; set; }
+ /// <summary>
+ /// Initializes a new instance with the specified source.
+ /// </summary>
+ /// <param name="source">The source settings.</param>
+ public EnvironmentVariableConfigurationProvider(EnvironmentVariableConfigurationSource source)
+ {
+ Source = source;
+ }
+
+ public override void Load()
+ {
+ foreach (var item in Source.Map)
+ {
+ if (string.IsNullOrEmpty(item.Key))
+ {
+ continue;
+ }
+
+ if (!string.IsNullOrEmpty(item.Name))
+ {
+ var value = Environment.GetEnvironmentVariable(item.Name);
+
+ if (!string.IsNullOrEmpty(value))
+ {
+ Data[item.Key] = value;
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/src/slskd/Common/Options/InstanceOptions.cs b/src/slskd/Common/Options/InstanceOptions.cs
index 09431956..52b46722 100644
--- a/src/slskd/Common/Options/InstanceOptions.cs
+++ b/src/slskd/Common/Options/InstanceOptions.cs
@@ -6,7 +6,6 @@
using System.Linq;
using Utility.CommandLine;
using Utility.EnvironmentVariables;
- using Utility.Extensions.Configuration.Yaml;
public class InstanceOptions
{
@@ -17,32 +16,32 @@
public static bool ShowVersion { get; private set; }
[EnvironmentVariable("SLSKD_DEBUG")]
- [Configuration("slskd:options:debug")]
+ [Configuration("slskd:debug")]
[Argument('d', "debug", "run in debug mode")]
public static bool Debug { get; private set; }
[EnvironmentVariable("SLSKD_NO_LOGO")]
- [Configuration("slskd:options:no_logo")]
+ [Configuration("slskd:no_logo")]
[Argument('n', "no-logo", "suppress logo on startup")]
public static bool DisableLogo { get; private set; }
[EnvironmentVariable("SLSKD_NO_AUTH")]
- [Configuration("slskd:options:no_auth")]
+ [Configuration("slskd:no_auth")]
[Argument('x', "no-auth", "disable authentication for web requests")]
public static bool DisableAuthentication { get; private set; }
[EnvironmentVariable("SLSKD_INSTANCE_NAME")]
- [Configuration("slskd:options:instance_name")]
+ [Configuration("slskd:instance_name")]
[Argument('i', "instance-name", "optional; a unique name for this instance")]
public static string InstanceName { get; private set; } = "default";
- [EnvironmentVariable("SLSKD_PROMETHEUS")]
- [Configuration("slskd:options:prometheus")]
+ [EnvironmentVariable("SLSKD_FEATURE_PROMETHEUS")]
+ [Configuration("slskd:feature:prometheus")]
[Argument('m', "prometheus", "enable collection and publish of prometheus metrics")]
public static bool EnablePrometheus { get; private set; }
- [EnvironmentVariable("SLSKD_SWAGGER")]
- [Configuration("slskd:options:swagger")]
+ [EnvironmentVariable("SLSKD_FEATURE_SWAGGER")]
+ [Configuration("slskd:feature:swagger")]
[Argument('s', "swagger", "enable swagger documentation")]
public static bool EnableSwagger { get; private set; }
@@ -83,52 +82,68 @@
public static bool EnableLoki { get; private set; }
- public static void Populate(string configurationFile = null, bool argumentsOnly = false)
- {
- if (!argumentsOnly)
- {
- try
- {
- EnvironmentVariables.Populate(typeof(InstanceOptions));
- }
- catch (Exception ex)
- {
- Console.WriteLine($"Error parsing environment variables: {ex.Message}");
- return;
- }
-
- try
- {
- var config = new ConfigurationBuilder()
- .SetBasePath(Directory.GetCurrentDirectory())
- .AddYamlFile(configurationFile, optional: true, reloadOnChange: false)
- .Build();
-
- Console.WriteLine(config.GetDebugView());
-
- config.Populate(typeof(InstanceOptions));
- }
- catch (Exception ex)
- {
- Console.WriteLine($"Error parsing configuration file '{configurationFile}': {ex.Message}");
- return;
- }
- }
-
- try
- {
- Arguments.Populate(typeof(InstanceOptions), clearExistingValues: false);
- }
- catch (Exception ex)
- {
- Console.WriteLine($"Error parsing command line input: {ex.Message}");
- return;
- }
-
- EnableLoki = !string.IsNullOrEmpty(LokiUrl);
- UrlBase = UrlBase.StartsWith("/") ? UrlBase : "/" + UrlBase;
- ContentPath = Path.GetFullPath(ContentPath);
- }
+ //public static void Populate(string configurationFile = null, bool argumentsOnly = false)
+ //{
+ // if (!argumentsOnly)
+ // {
+ // try
+ // {
+ // EnvironmentVariables.Populate(typeof(InstanceOptions));
+ // }
+ // catch (Exception ex)
+ // {
+ // Console.WriteLine($"Error parsing environment variables: {ex.Message}");
+ // return;
+ // }
+
+ // try
+ // {
+ // var config = new ConfigurationBuilder()
+ // .SetBasePath(Directory.GetCurrentDirectory())
+ // .AddMapping(new[]
+ // {
+ // new OptionMap {
+ // Description = "run in debug mode",
+ // EnvironmentVariable = "SLSK_DEBUG",
+ // ShortName = 'd',
+ // LongName = "debug",
+ // Key = "slskd:debug"
+ // },
+ // new OptionMap {
+ // Description = "optional; a unique name for this instance",
+ // EnvironmentVariable = "SLSK_INSTANCE_NAME",
+ // ShortName = 'i',
+ // LongName = "instance-name",
+ // Key = "slskd:instancename"
+ // }
+ // }, Environment.CommandLine, configurationFile, optional: true, reloadOnChange: false)
+ // .Build();
+
+ // Console.WriteLine(config.GetDebugView());
+
+ // config.Populate(typeof(InstanceOptions));
+ // }
+ // catch (Exception ex)
+ // {
+ // Console.WriteLine($"Error parsing configuration file '{configurationFile}': {ex.Message}");
+ // return;
+ // }
+ // }
+
+ // try
+ // {
+ // Arguments.Populate(typeof(InstanceOptions), clearExistingValues: false);
+ // }
+ // catch (Exception ex)
+ // {
+ // Console.WriteLine($"Error parsing command line input: {ex.Message}");
+ // return;
+ // }
+
+ // EnableLoki = !string.IsNullOrEmpty(LokiUrl);
+ // UrlBase = UrlBase.StartsWith("/") ? UrlBase : "/" + UrlBase;
+ // ContentPath = Path.GetFullPath(ContentPath);
+ //}
public static void PrintHelp()
{
diff --git a/src/slskd/Common/Options/RuntimeOptions.cs b/src/slskd/Common/Options/RuntimeOptions.cs
index d0c28e75..cded2334 100644
--- a/src/slskd/Common/Options/RuntimeOptions.cs
+++ b/src/slskd/Common/Options/RuntimeOptions.cs
@@ -1,9 +1,106 @@
namespace slskd
{
+ using System;
using System.Collections.Generic;
public class RuntimeOptions
{
+ public static IEnumerable<EnvironmentVariable> EnvironmentVariableMap => new[]
+ {
+ new EnvironmentVariable {
+ Description = "run in debug mode",
+ Name = "SLSK_DEBUG",
+ Key = "slskd:debug"
+ },
+ new EnvironmentVariable {
+ Description = "optional; a unique name for this instance",
+ Name = "SLSK_INSTANCE_NAME",
+ Key = "slskd:instancename"
+ },
+ new EnvironmentVariable {
+ Description = "enable collection and publish of prometheus metrics",
+ Name = "SLSK_PROMETHEUS",
+ Key = "slskd:feature:prometheus"
+ },
+ new EnvironmentVariable {
+ Description = "enable swagger documentation",
+ Name = "SLSK_SWAGGER",
+ Key = "slskd:feature:swagger"
+ },
+ new EnvironmentVariable {
+ Description = "jwt signing key",
+ Name = "SLSKD_JWT_KEY",
+ Key = "slskd:web:jwt:key"
+ }
+ };
+
+ public static IEnumerable<Argument> ArgumentMap => new[]
+ {
+ new Argument
+ {
+ Description = "print usage",
+ ShortName = 'h',
+ LongName = "help",
+ Key = "slskd:showhelp"
+ },
+ new Argument {
+ Description = "display version information",
+ ShortName = 'v',
+ LongName = "version",
+ Key = "slskd:showversion"
+ },
+ new Argument {
+ Description = "run in debug mode",
+ ShortName = 'd',
+ LongName = "debug",
+ Key = "slskd:debug"
+ },
+ new Argument
+ {
+ Description = "",
+ ShortName = 'i',
+ LongName = "instance-name",
+ Key = "slskd:instancename"
+ }
+ };
+
+ public class slskd
+ {
+ public bool ShowHelp { get; private set; } = false;
+ public bool ShowVersion { get; private set; } = false;
+ public bool Debug { get; private set; } = false;
+ public bool NoLogo { get; private set; } = false;
+ public bool NoAuth { get; private set; } = false;
+ public string InstanceName { get; private set; } = "default";
+ public FeatureOptions Feature { get; private set; } = new FeatureOptions();
+ public LoggerOptions Logger { get; private set; } = new LoggerOptions();
+ public WebOptions Web { get; private set; } = new WebOptions();
+
+ public class FeatureOptions
+ {
+ public bool Prometheus { get; private set; } = false;
+ public bool Swagger { get; private set; } = false;
+ }
+
+ public class LoggerOptions
+ {
+ public string Loki { get; private set; } = null;
+ }
+
+ public class WebOptions
+ {
+ public string UrlBase { get; private set; } = "/";
+ public string ContentPath { get; private set; } = "wwwroot";
+ public JwtOptions Jwt { get; private set; } = new JwtOptions();
+
+ public class JwtOptions
+ {
+ public int TTL { get; private set; } = 1234567890;
+ public string Key { get; private set; } = Guid.NewGuid().ToString();
+ }
+ }
+ }
+
public class Soulseek
{
public string Username { get; set; } = InstanceOptions.Username;
diff --git a/src/slskd/Common/YamlConfigurationSource.cs b/src/slskd/Common/YamlConfigurationSource.cs
new file mode 100644
index 00000000..a7c379e3
--- /dev/null
+++ b/src/slskd/Common/YamlConfigurationSource.cs
@@ -0,0 +1,214 @@
+/*
+ █▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀ ▀ ▀ ▀▀
+ █ 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.");
+ }
+
+ var value = NullValues.Contains(scalar.Value.ToLower()) ? null : scalar.Value;
+
+ if (value != null)
+ {
+ 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()));
+ }
+ }
+ }
+ }
+}
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index e366e62f..5ea7c304 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -9,8 +9,9 @@
using Serilog.Sinks.Grafana.Loki;
using System;
using System.Diagnostics;
+ using System.IO;
using System.Reflection;
- using Utility.Extensions.Configuration.Yaml;
+ using System.Text.Json;
public class Program
{
@@ -20,22 +21,30 @@
public static readonly string ConfigurationFile = "config.yml";
+ private static Action<BinderOptions> BinderOptions = (o) => { o.BindNonPublicProperties = true; };
+ public static RuntimeOptions.slskd Options { get; private set; } = new();
+
+
public static void Main(string[] args)
{
- InstanceOptions.Populate(argumentsOnly: true);
+ new ConfigurationBuilder()
+ .MapCommandLineArguments(RuntimeOptions.ArgumentMap, Environment.CommandLine)
+ .Build()
+ .GetSection("slskd")
+ .Bind(Options, BinderOptions);
var assembly = Assembly.GetExecutingAssembly();
var assemblyVersion = assembly.GetName().Version;
var informationVersion = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
Version = $"{assemblyVersion} ({informationVersion})";
- if (InstanceOptions.ShowVersion)
+ if (Options.ShowVersion)
{
Console.WriteLine(Version);
return;
}
- if (InstanceOptions.ShowHelp)
+ if (Options.ShowHelp)
{
if (!InstanceOptions.DisableLogo)
{
@@ -46,7 +55,18 @@
return;
}
- InstanceOptions.Populate(ConfigurationFile, argumentsOnly: false);
+ new ConfigurationBuilder()
+ .MapEnvironmentVariables(RuntimeOptions.EnvironmentVariableMap)
+ .SetBasePath(Directory.GetCurrentDirectory())
+ .AddYamlFile(ConfigurationFile, optional: true, reloadOnChange: false)
+ .MapCommandLineArguments(RuntimeOptions.ArgumentMap, Environment.CommandLine)
+ .Build()
+ .GetSection("slskd")
+ .Bind(Options, BinderOptions);
+
+ Console.WriteLine(JsonSerializer.Serialize(Options));
+
+ return;
InvocationId = Guid.NewGuid();
ProcessId = Environment.ProcessId;
diff --git a/src/slskd/config.yml b/src/slskd/config.yml
index a7840141..df1514d0 100644
--- a/src/slskd/config.yml
+++ b/src/slskd/config.yml
@@ -1,9 +1,9 @@
slskd:
- options:
- debug: false
- no_logo: false
- no_auth: false
- instance_name: FromYAML
+ debug: false
+ no_logo: false
+ no_auth: false
+ instance_name: FromYAML
+ feature:
prometheus: true
swagger: true
logger:
diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj
index d67e6eb8..cae5d27c 100644
--- a/src/slskd/slskd.csproj
+++ b/src/slskd/slskd.csproj
@@ -51,7 +51,6 @@
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.8.0" />
<PackageReference Include="Utility.CommandLine.Arguments" Version="5.0.0" />
<PackageReference Include="Utility.EnvironmentVariables" Version="1.0.4" />
- <PackageReference Include="Utility.Extensions.Configuration.Yaml" Version="1.0.1" />
<PackageReference Include="YamlDotNet" Version="9.1.4" />
</ItemGroup>