namespace slskd.Configuration
{
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
///
/// Provides extension method(s) for the CommandLineArguments namespace.
///
public static class CommandLineArgumentsExtensions
{
///
/// Gets the DeclaringType of the first method on the stack whose name matches the specified .
///
/// The name of the calling method for which the DeclaringType is to be fetched.
/// The DeclaringType of the first method on the stack whose name matches the specified .
internal static Type GetCallingType(string caller)
{
var callingMethod = new StackTrace().GetFrames()
.Select(f => f.GetMethod())
.FirstOrDefault(m => m.Name == caller);
if (callingMethod == default)
{
throw new InvalidOperationException($"Unable to determine the containing type of the calling method '{caller}'. Explicitly specify the originating Type.");
}
return callingMethod.DeclaringType;
}
///
/// Removes the outermost pair of enclosing quotes.
///
/// The string to trim.
/// The trimmed string.
internal static string TrimOuterQuotes(this string value)
{
if (value.StartsWith("\"", StringComparison.InvariantCultureIgnoreCase) && value.EndsWith("\"", StringComparison.InvariantCultureIgnoreCase))
{
value = value.Trim('"');
}
else if (value.StartsWith("'", StringComparison.InvariantCultureIgnoreCase) && value.EndsWith("'", StringComparison.InvariantCultureIgnoreCase))
{
value = value.Trim('\'');
}
return value;
}
}
///
/// Indicates that the property is to be used as a target for automatic population of values from command line arguments
/// when invoking the method.
///
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class CommandLineArgumentAttribute : Attribute
{
///
/// Initializes a new instance of the class.
///
/// The short name of the argument, represented as a single character.
/// The long name of the argument.
/// The help text of the argument.
public CommandLineArgumentAttribute(char shortName, string longName, string helpText = null)
{
ShortName = shortName;
LongName = longName;
HelpText = helpText;
}
///
/// Gets or sets the help text of the argument.
///
public string HelpText { get; set; }
///
/// Gets or sets the long name of the argument.
///
public string LongName { get; set; }
///
/// Gets or sets the short name of the argument.
///
public char ShortName { get; set; }
}
///
/// Encapsulates argument names and help text.
///
public class ArgumentInfo
{
///
/// Initializes a new instance of the class.
///
/// The short name of the argument.
/// The long name of the argument.
/// The help text for the argument.
/// The property with which the argument is associated.
public ArgumentInfo(char shortName, string longName, string helpText, PropertyInfo property)
{
ShortName = shortName;
LongName = longName;
HelpText = helpText;
Property = property;
}
///
/// Gets the help text for the argument.
///
public string HelpText { get; }
///
/// Gets a value indicating whether the argument backing Type is a collection.
///
public bool IsCollection => Property.PropertyType.IsArray || (Property.PropertyType.IsGenericType && Property.PropertyType.GetGenericTypeDefinition() == typeof(List<>));
///
/// Gets the long name of the argument.
///
public string LongName { get; }
///
/// Gets the property with which the argument is associated.
///
public PropertyInfo Property { get; }
///
/// Gets the short name of the argument.
///
public char ShortName { get; }
}
///
/// Provides static methods used to retrieve the command line arguments and operands with which the application was
/// started, as well as a Type to contain them.
///
public class CommandLineArguments
{
///
/// The regular expression with which to parse the command line string.
///
private const string ArgumentRegExWithoutForwardSlash = "(?:[-]{1,2})([^=: ]+)[=: ]?([^-'\"]\\S*|\\\"[^\"]*\\\"|\\\'[^']*\\\')?|([^ ([^'\\\"]+|\"[^\\\"]+\"|\\\'[^']+\\\')";
///
/// The regular expression with which to parse the command line string, including the ability to specify forward slashes.
///
private const string ArgumentRegExWithForwardSlash = "(?:[-]{1,2}|\\/)([^=: ]+)[=: ]?([^-'\"\\/]\\S*|\\\"[^\"]*\\\"|\\\'[^']*\\\')?|([^ ([^'\\\"]+|\"[^\\\"]+\"|\\\'[^']+\\\')";
///
/// The regular expression with which to parse argument-value groups.
///
private const string GroupRegEx = "^-[^-]+";
///
/// The regular expression with which to parse strings strictly containing operands.
///
private const string OperandRegEx = "([^ ([^'\\\"]+|\\\"[^\\\"]+\\\"|\\\'[^']+\\\')";
///
/// The regular expression with which to split the command line string explicitly among argument/value pairs and
/// operands, and strictly operands.
///
///
/// This regular expression effectively splits a string into two parts; the part before the first "--", and the part
/// after. Instances of "--" not surrounded by a word boundary and those enclosed in quotes are ignored.
///
private const string StrictOperandSplitRegEx = "(.*?[^\\\"\\\'])?(\\B-{2}\\B)[^\\\"\\\']?(.*)";
private CommandLineArguments(string commandLineString, List> argumentList, Dictionary argumentDictionary, List operandList, Type targetType = null)
{
CommandLineString = commandLineString;
ArgumentList = argumentList;
ArgumentDictionary = argumentDictionary;
OperandList = operandList;
TargetType = targetType;
}
///
/// Gets or sets a value indicating whether forward slashes are processed as argument delimiters.
///
public static bool EnableForwardSlash { get; set; } = false;
///
/// Gets a dictionary containing the arguments and values specified in the command line arguments with which the
/// application was started.
///
///
/// This dictionary contains argument key/value pairs compiled from the and checked against
/// the to combine duplicated pairs into lists where the backing property is a collection, and
/// to overwrite where the backing property is not a collection.
///
public Dictionary ArgumentDictionary { get; }
///
/// Gets the list of arguments specified in the command line arguments with which the application was started.
///
///
/// This list contains each argument key/value pair as supplied in the original string, preserving the original order
/// and any duplicated pairs.
///
public List> ArgumentList { get; }
///
/// Gets the command line string from which the arguments were parsed.
///
public string CommandLineString { get; }
///
/// Gets a list containing the operands specified in the command line arguments with which the application was started.
///
public List OperandList { get; private set; }
///
/// Gets the target Type, if applicable.
///
public Type TargetType { get; }
private static string ArgumentRegEx => EnableForwardSlash ? ArgumentRegExWithForwardSlash : ArgumentRegExWithoutForwardSlash;
///
/// Gets the argument value corresponding to the specified .
///
/// The index for which the value is to be retrieved.
/// The argument value corresponding to the specified index.
public object this[int index]
{
get
{
return ArgumentList[index].Value;
}
}
///
/// Gets the argument value corresponding to the specified from the
/// property.
///
/// The key for which the value is to be retrieved.
/// The argument value corresponding to the specified key.
public object this[string key]
{
get
{
return ArgumentDictionary[key];
}
}
///
/// Retrieves a collection of gathered from properties in the target
/// marked with the along with the short and long names and help text.
///
/// The for which the matching properties are to be retrieived.
/// Internal parameter used to identify the calling method.
/// The retrieved collection of .
public static IEnumerable GetArgumentInfo(Type type = null, [CallerMemberName] string caller = default)
{
type ??= CommandLineArgumentsExtensions.GetCallingType(caller);
var retVal = new List();
foreach (PropertyInfo property in GetArgumentProperties(type).Values.Distinct())
{
CustomAttributeData attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == typeof(CommandLineArgumentAttribute).Name);
if (attribute != default(CustomAttributeData))
{
retVal.Add(new ArgumentInfo(
shortName: (char)attribute.ConstructorArguments[0].Value,
longName: (string)attribute.ConstructorArguments[1].Value,
helpText: (string)attribute.ConstructorArguments[2].Value,
property: property));
}
}
return retVal;
}
///
/// Returns a dictionary containing the values specified in the command line arguments with which the application was
/// started, keyed by argument name.
///
/// The command line arguments with which the application was started.
/// The for which the command line string is to be parsed.
///
/// The dictionary containing the arguments and values specified in the command line arguments with which the
/// application was started.
///
public static CommandLineArguments Parse(string commandLineString = default, Type type = null)
{
commandLineString = commandLineString == default || string.IsNullOrEmpty(commandLineString) ? Environment.CommandLine : commandLineString;
List> argumentList;
List operandList;
// use the strict operand regular expression to test for/extract the two halves of the string, if the operator is used.
MatchCollection matches = Regex.Matches(commandLineString, StrictOperandSplitRegEx);
// if there is a match, the string contains the strict operand delimiter. parse the first and second matches accordingly.
if (matches.Count > 0)
{
// the first group of the first match will contain everything in the string prior to the strict operand delimiter,
// so extract the argument key/value pairs and list of operands from that string.
argumentList = GetArgumentList(matches[0].Groups[1].Value);
operandList = GetOperandList(matches[0].Groups[1].Value);
// the first group of the second match will contain everything in the string after the strict operand delimiter, so
// extract the operands from that string using the strict method.
if (!string.IsNullOrEmpty(matches[0].Groups[3].Value))
{
List operandListStrict = GetOperandListStrict(matches[0].Groups[3].Value);
operandList.AddRange(operandListStrict);
}
}
else
{
argumentList = GetArgumentList(commandLineString);
operandList = GetOperandList(commandLineString);
}
var argumentDictionary = GetArgumentDictionary(argumentList, type);
return new CommandLineArguments(commandLineString, argumentList, argumentDictionary, operandList, type);
}
///
/// Populates the properties in the invoking class marked with the
/// with the values specified in the list of command line
/// arguments, if present.
///
/// The command line arguments with which the application was started.
/// Whether to clear the properties before populating them. Defaults to true.
/// Internal parameter used to identify the calling method.
public static void Populate(string commandLineString = default, bool clearExistingValues = true, [CallerMemberName] string caller = default)
{
var type = CommandLineArgumentsExtensions.GetCallingType(caller);
Populate(type, Parse(commandLineString, type), clearExistingValues);
}
///
/// Populates the properties in the specified Type marked with the
/// with the values specified in the list of command line
/// arguments, if present.
///
///
/// The Type for which the static properties matching the list of command line arguments are to be populated.
///
/// The command line arguments with which the application was started.
/// Whether to clear the properties before populating them. Defaults to true.
public static void Populate(Type type, string commandLineString = default, bool clearExistingValues = true)
{
Populate(type, Parse(commandLineString, type), clearExistingValues);
}
///
/// Populates the properties in the specified Type marked with the
/// with the values specified in the specified argument
/// dictionary, if present. All property values are set to null at the start of the routine.
///
///
/// The Type for which the static properties matching the list of command line arguments are to be populated.
///
///
/// The Arguments object containing the dictionary containing the argument-value pairs with which the destination
/// properties should be populated and the list of operands.
///
/// Whether to clear the properties before populating them. Defaults to true.
public static void Populate(Type type, CommandLineArguments arguments, bool clearExistingValues = true)
{
// fetch any properties in the specified type marked with the ArgumentAttribute attribute and clear them
Dictionary properties = GetArgumentProperties(type);
if (clearExistingValues)
{
ClearProperties(properties);
}
foreach (string propertyName in properties.Keys)
{
// if the argument dictionary contains a matching argument
if (arguments.ArgumentDictionary.ContainsKey(propertyName))
{
// retrieve the property and type
PropertyInfo property = properties[propertyName];
Type propertyType = property.PropertyType;
// retrieve the value from the argument dictionary
object value = arguments.ArgumentDictionary[propertyName];
object convertedValue;
// if the type of the property is bool and the argument value is empty set the property value to true,
// indicating the argument is present
if (propertyType == typeof(bool))
{
convertedValue = true;
// if a value is specified, a bool flag was followed by an operand and the parser interpreted this as key
// value pair because it wasn't aware the flag was backed by a bool. remove the argument from the original
// string and re-parse operands from it to preserve order.
if (!string.IsNullOrEmpty(value.ToString()))
{
var arg = Regex.Matches(arguments.CommandLineString, "(?:[-]{1,2}|\\/)" + propertyName)[0].Value;
arguments.OperandList = GetOperandList(arguments.CommandLineString.Replace(arg, string.Empty));
}
}
else if (propertyType.IsArray || (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(List<>)))
{
convertedValue = value;
// next, create a list with the same type as the target property
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 (List