mirror of
https://github.com/nsnail/spectre.console.git
synced 2025-07-05 03:58:16 +08:00
Add support for arrays in [DefaultValue] attributes (#1164)
Fixes #1163
This commit is contained in:
@ -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;
|
||||
|
@ -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)
|
||||
{
|
||||
|
@ -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('.') ?? " ");
|
||||
|
Reference in New Issue
Block a user