Add support for arrays in [DefaultValue] attributes (#1164)

Fixes #1163
This commit is contained in:
Cédric Luthi
2023-05-11 15:26:53 +02:00
committed by GitHub
parent 6acf9b8c63
commit dac2097321
11 changed files with 125 additions and 20 deletions

View File

@ -65,6 +65,11 @@ internal sealed class CommandValueBinder
private object GetArray(CommandParameter parameter, object? value)
{
if (value is Array)
{
return value;
}
// Add a new item to the array
var array = (Array?)_lookup.GetValue(parameter);
Array newArray;

View File

@ -133,13 +133,33 @@ internal static class CommandValueResolver
var (converter, _) = GetConverter(lookup, binder, resolver, parameter);
if (converter != null)
{
result = converter.ConvertFrom(result);
result = result is Array array ? ConvertArray(array, converter) : converter.ConvertFrom(result);
}
}
return result;
}
private static Array ConvertArray(Array sourceArray, TypeConverter converter)
{
Array? targetArray = null;
for (var i = 0; i < sourceArray.Length; i++)
{
var item = sourceArray.GetValue(i);
if (item != null)
{
var converted = converter.ConvertFrom(item);
if (converted != null)
{
targetArray ??= Array.CreateInstance(converted.GetType(), sourceArray.Length);
targetArray.SetValue(converted, i);
}
}
}
return targetArray ?? sourceArray;
}
[SuppressMessage("Style", "IDE0019:Use pattern matching", Justification = "It's OK")]
private static (TypeConverter? Converter, ConstructorInfo? StringConstructor) GetConverter(CommandValueLookup lookup, CommandValueBinder binder, ITypeResolver resolver, CommandParameter parameter)
{

View File

@ -348,7 +348,17 @@ internal static class HelpWriter
var columns = new List<string> { GetOptionParts(option) };
if (defaultValueColumn)
{
columns.Add(option.DefaultValue == null ? " " : $"[bold]{option.DefaultValue.ToString().EscapeMarkup()}[/]");
static string Bold(object obj) => $"[bold]{obj.ToString().EscapeMarkup()}[/]";
var defaultValue = option.DefaultValue switch
{
null => " ",
"" => " ",
Array { Length: 0 } => " ",
Array array => string.Join(", ", array.Cast<object>().Select(Bold)),
_ => Bold(option.DefaultValue),
};
columns.Add(defaultValue);
}
columns.Add(option.Description?.TrimEnd('.') ?? " ");