aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jpdillingham@gmail.com>2021-07-27 08:53:18 -0500
committerGitHub <noreply@github.com>2021-07-27 08:53:18 -0500
commit69d29c1eaa03992cf786d1d9b1ec1935dd85ef42 (patch)
tree5253fcd096de96c3bf8c1cd3a9af0f303f4cb41f /src
parent58bc401dab5d7eb3bc6cb07a22e0ee9c97ddf4bd (diff)
parentc5a23135f01697e5fb234988a314be57c9e245d5 (diff)
downloadslskd-69d29c1eaa03992cf786d1d9b1ec1935dd85ef42.tar.gz
Merge pull request #130 from slskd/lists
Accept option lists via command line and environment variables
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Application/Service.cs2
-rw-r--r--src/slskd/Common/Configuration/CommandLineConfigurationSource.cs51
-rw-r--r--src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs13
-rw-r--r--src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs19
-rw-r--r--src/slskd/Common/Extensions.cs33
-rw-r--r--src/slskd/Program.cs13
-rw-r--r--src/slskd/slskd.csproj2
7 files changed, 118 insertions, 15 deletions
diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs
index 62f6eb32..1d2aec25 100644
--- a/src/slskd/Application/Service.cs
+++ b/src/slskd/Application/Service.cs
@@ -214,7 +214,7 @@ namespace slskd
var requiresRestart = HasAttribute<RequiresRestartAttribute>(property);
var requiresReconnect = HasAttribute<RequiresReconnectAttribute>(property);
- Logger.Debug($"{fqn} changed from '{left ?? "<null>"}' to '{right ?? "<null>"}'{(requiresRestart ? "; Restart required to take effect." : string.Empty)}{(requiresReconnect ? "; Reconnect required to take effect." : string.Empty)}");
+ Logger.Debug($"{fqn} changed from '{left.ToJson() ?? "<null>"}' to '{right.ToJson() ?? "<null>"}'{(requiresRestart ? "; Restart required to take effect." : string.Empty)}{(requiresReconnect ? "; Reconnect required to take effect." : string.Empty)}");
pendingRestart |= requiresRestart;
pendingReconnect |= requiresReconnect;
diff --git a/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs b/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs
index 6cf59808..0436c922 100644
--- a/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs
+++ b/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs
@@ -18,6 +18,7 @@
namespace slskd.Configuration
{
using System;
+ using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.Configuration;
@@ -33,9 +34,10 @@ namespace slskd.Configuration
/// </summary>
/// <param name="builder">The <see cref="IConfigurationBuilder"/> to which to add.</param>
/// <param name="targetType">The type from which to map properties.</param>
+ /// <param name="multiValuedArguments">An array of argument names which can be specified with multiple values.</param>
/// <param name="commandLine">The command line string from which to parse arguments.</param>
/// <returns>The updated <see cref="IConfigurationBuilder"/>.</returns>
- public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, Type targetType, string commandLine = null)
+ public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, Type targetType, string[] multiValuedArguments = null, string commandLine = null)
{
if (builder == null)
{
@@ -51,6 +53,7 @@ namespace slskd.Configuration
{
s.TargetType = targetType;
s.CommandLine = commandLine ?? Environment.CommandLine;
+ s.MultiValuedArguments = multiValuedArguments;
});
}
@@ -78,18 +81,20 @@ namespace slskd.Configuration
TargetType = source.TargetType;
Namespace = TargetType.Namespace.Split('.').First();
CommandLine = source.CommandLine;
+ MultiValuedArguments = source.MultiValuedArguments;
}
private string CommandLine { get; set; }
private string Namespace { get; set; }
private Type TargetType { get; set; }
+ private string[] MultiValuedArguments { get; set; }
/// <summary>
/// Parses command line arguments from the specified string and maps them to the corresponding keys.
/// </summary>
public override void Load()
{
- var dictionary = Arguments.Parse(CommandLine).ArgumentDictionary;
+ var dictionary = Arguments.Parse(CommandLine, options => options.CombinableArguments = MultiValuedArguments).ArgumentDictionary;
void Map(Type type, string path)
{
@@ -110,14 +115,41 @@ namespace slskd.Configuration
{
if (dictionary.ContainsKey(argument))
{
- var value = dictionary[argument].ToString();
-
- if (property.PropertyType == typeof(bool) && string.IsNullOrEmpty(value))
+ // if the backing type is an array, it supports multiple values.
+ if (property.PropertyType.IsArray)
{
- value = "true";
+ var value = dictionary[argument];
+
+ // Parse() will stuff multiple values into a List<T> if the argument name is
+ // in the list of those supporting multiple values, and more than one value was supplied.
+ // detect this, and add the values to the target.
+ if (value.GetType().IsGenericType && value.GetType().GetGenericTypeDefinition() == typeof(List<>))
+ {
+ var elements = (List<object>)dictionary[argument];
+
+ for (int i = 0; i < elements.Count; i++)
+ {
+ Data[ConfigurationPath.Combine(key, i.ToString())] = elements[i].ToString();
+ }
+ }
+ else
+ {
+ // there may have only been one value supplied, in which case the value is just a
+ // string. stick it in index 0 of the target.
+ Data[ConfigurationPath.Combine(key, "0")] = value.ToString();
+ }
}
+ else
+ {
+ var value = dictionary[argument].ToString();
- Data[key] = value;
+ if (property.PropertyType == typeof(bool) && string.IsNullOrEmpty(value))
+ {
+ value = "true";
+ }
+
+ Data[key] = value;
+ }
}
}
}
@@ -148,6 +180,11 @@ namespace slskd.Configuration
public Type TargetType { get; set; }
/// <summary>
+ /// Gets or sets an array of argument names which can be specified with multiple values.
+ /// </summary>
+ public string[] MultiValuedArguments { get; set; } = Array.Empty<string>();
+
+ /// <summary>
/// Builds the <see cref="CommandLineConfigurationProvider"/> for this source.
/// </summary>
/// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
diff --git a/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs b/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs
index 15cf4070..eae4b2eb 100644
--- a/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs
+++ b/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs
@@ -99,11 +99,16 @@ namespace slskd.Configuration
}
else
{
- var value = property.GetValue(defaults);
-
- if (value != null)
+ // don't add array values to the configuration; these are additive across providers
+ // and the default value from the class is "stuck", so adding them again results in duplicates.
+ if (!property.PropertyType.IsArray)
{
- Data[key] = value.ToString();
+ var value = property.GetValue(defaults);
+
+ if (value != null)
+ {
+ Data[key] = value.ToString();
+ }
}
}
}
diff --git a/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs b/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs
index 9a09d4e1..6d2896c2 100644
--- a/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs
+++ b/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs
@@ -100,15 +100,32 @@ namespace slskd.Configuration
if (attribute != default)
{
+ // retrieve the envar name from the attribute
var name = (string)attribute.ConstructorArguments[0].Value;
if (!string.IsNullOrEmpty(name))
{
+ // retrieve the corresponding value from environment variables
var value = Environment.GetEnvironmentVariable(Prefix + name);
if (value != null)
{
- Data[key] = value.ToString();
+ // if the type of the backing property is an array,
+ // split the retrieved value by semicolon and add the parts to
+ // config as zero-based children of the prop
+ if (property.PropertyType.IsArray)
+ {
+ var elements = value.Split(';');
+
+ for (int i = 0; i < elements.Length; i++)
+ {
+ Data[ConfigurationPath.Combine(key, i.ToString())] = elements[i];
+ }
+ }
+ else
+ {
+ Data[key] = value.ToString();
+ }
}
}
}
diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs
index 3e4f6e68..51c0d147 100644
--- a/src/slskd/Common/Extensions.cs
+++ b/src/slskd/Common/Extensions.cs
@@ -45,6 +45,30 @@ namespace slskd
public static T ToObject<T>(this string str) => JsonSerializer.Deserialize<T>(str);
/// <summary>
+ /// Recursively retrieves all properties.
+ /// </summary>
+ /// <param name="type">The type from which to retrieve properties.</param>
+ /// <returns>The list of properties.</returns>
+ public static IEnumerable<PropertyInfo> GetPropertiesRecursively(this Type type)
+ {
+ var props = new List<PropertyInfo>();
+
+ foreach (var prop in type.GetProperties())
+ {
+ if (prop.PropertyType.IsPrimitive || prop.PropertyType.IsArray || Nullable.GetUnderlyingType(prop.PropertyType) != null || new[] { typeof(string), typeof(decimal) }.Contains(prop.PropertyType))
+ {
+ props.Add(prop);
+ }
+ else
+ {
+ props.AddRange(prop.PropertyType.GetPropertiesRecursively());
+ }
+ }
+
+ return props;
+ }
+
+ /// <summary>
/// Deeply compares this object with the specified object and returns a list of properties that are different.
/// </summary>
/// <param name="left">The left side of the comparison.</param>
@@ -67,7 +91,14 @@ namespace slskd
var propType = prop.PropertyType;
var fqn = string.IsNullOrEmpty(parentFqn) ? prop.Name : string.Join(".", parentFqn, prop.Name);
- if (propType.IsPrimitive || Nullable.GetUnderlyingType(propType) != null || new[] { typeof(string), typeof(decimal) }.Contains(propType))
+ if (propType.IsArray)
+ {
+ if (leftVal.ToJson() != rightVal.ToJson())
+ {
+ differences.Add((prop, fqn, leftVal, rightVal));
+ }
+ }
+ else if (propType.IsPrimitive || Nullable.GetUnderlyingType(propType) != null || new[] { typeof(string), typeof(decimal) }.Contains(propType))
{
if (!Equals(leftVal, rightVal))
{
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index d22ab433..b5275756 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -332,6 +332,18 @@ namespace slskd
{
configurationFile = Path.GetFullPath(configurationFile);
+ var multiValuedArguments = typeof(Options)
+ .GetPropertiesRecursively()
+ .Where(p => p.PropertyType.IsArray)
+ .SelectMany(p =>
+ p.CustomAttributes
+ .Where(a => a.AttributeType == typeof(ArgumentAttribute))
+ .Select(a => new[] { a.ConstructorArguments[0].Value, a.ConstructorArguments[1].Value })
+ .SelectMany(v => v))
+ .Select(v => v.ToString())
+ .Where(v => v != "\u0000")
+ .ToArray();
+
return builder
.AddDefaultValues(
targetType: typeof(Options))
@@ -346,6 +358,7 @@ namespace slskd
provider: new PhysicalFileProvider(Path.GetDirectoryName(configurationFile), ExclusionFilters.None)) // required for locations outside of the app directory
.AddCommandLine(
targetType: typeof(Options),
+ multiValuedArguments,
commandLine: Environment.CommandLine);
}
diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj
index c2873938..44f4bf9c 100644
--- a/src/slskd/slskd.csproj
+++ b/src/slskd/slskd.csproj
@@ -75,7 +75,7 @@
</PackageReference>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.1.4" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.11.1" />
- <PackageReference Include="Utility.CommandLine.Arguments" Version="5.0.0" />
+ <PackageReference Include="Utility.CommandLine.Arguments" Version="6.0.0" />
<PackageReference Include="Utility.EnvironmentVariables" Version="1.0.5" />
<PackageReference Include="YamlDotNet" Version="11.2.0" />
</ItemGroup>