Tyrrrz / CliFx

Class-first framework for building command-line interfaces
MIT License
1.5k stars 61 forks source link

Custom value conversion #41

Closed Tyrrrz closed 4 years ago

Tyrrrz commented 4 years ago

Add some sort of functionality that lets users specify custom converter for command parameters/options.

Needs to work well with both scalar and non-scalar (i.e. array) arguments.

Thinking about using attributes for this, but maybe there are better options.

Tyrrrz commented 4 years ago

Initial design:

Extend CommandOptionAttribute/CommandParameterAttribute with an additional property Type? ConverterType { get; set; }. The converter has to implement some IArgumentConverter.

Since an argument can be scalar and non-scalar, in order to support both, IArgumentConverter would need to either have two methods (for a list of arguments and for one argument) or have one just for a list and let the user deal with it (nasty). It also needs a property IsScalar which is important when binding parameters from multiple arguments because it needs to be known pretty early.

This overall sounds pretty meh because it exposes quite a few points of failure where the user may forget something or do something incorrectly.

Tyrrrz commented 4 years ago

Current workaround without implementing anything:

Assume we have type MyType and a function MyType Convert(string). We can simply define our option/parameter as a string or IEnumerable<string> and then do the conversion inside ExecuteAsync manually. Not too pretty but still reasonable.

oshustov commented 4 years ago

Hey, @Tyrrrz ! I would like to have a look at this issue. I maybe have a solution which works with both MyCustomType and IEnumerable<MyCustomType> and other generic collections, but I am not sure that I clearly catched what did you mean at It also needs a property IsScalar which is important when binding parameters from multiple arguments because it needs to be known pretty early. As I see, non-scalar types use same scalar type converters for each argument in the list, aren`t they?

Tyrrrz commented 4 years ago

Hi @AlexandrShustov.

As I see, non-scalar types use same scalar type converters for each argument in the list, aren`t they?

They do. I think when I wrote this I was thinking of cases where the user may want to convert the entire list, not just item by item. You can ignore this for now and see maybe it's not necessary after all.