Add autocomplete for text prompt

Closes #166
This commit is contained in:
Patrik Svensson
2020-12-21 03:21:02 +01:00
committed by Patrik Svensson
parent e280b82679
commit 1cf30f62fc
41 changed files with 218 additions and 104 deletions

View File

@ -0,0 +1,55 @@
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
namespace Spectre.Console.Internal
{
internal static class TypeConverterHelper
{
public static string ConvertToString<T>(T input)
{
return GetTypeConverter<T>().ConvertToInvariantString(input);
}
[SuppressMessage("Design", "CA1031:Do not catch general exception types")]
public static bool TryConvertFromString<T>(string input, [MaybeNull] out T result)
{
try
{
result = (T)GetTypeConverter<T>().ConvertFromInvariantString(input);
return true;
}
catch
{
result = default;
return false;
}
}
public static TypeConverter GetTypeConverter<T>()
{
var converter = TypeDescriptor.GetConverter(typeof(T));
if (converter != null)
{
return converter;
}
var attribute = typeof(T).GetCustomAttribute<TypeConverterAttribute>();
if (attribute != null)
{
var type = Type.GetType(attribute.ConverterTypeName, false, false);
if (type != null)
{
converter = Activator.CreateInstance(type) as TypeConverter;
if (converter != null)
{
return converter;
}
}
}
throw new InvalidOperationException("Could not find type converter");
}
}
}