Skip to content

enable easier custom model binding #848

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 13, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ public void Parameters_named_arguments_generate_command_arguments_having_the_cor

var rootCommandArgument = parser.Configuration.RootCommand.Arguments.Single();

rootCommandArgument.Type
rootCommandArgument.ValueType
.Should()
.Be(expectedType);
}
Expand Down
4 changes: 2 additions & 2 deletions src/System.CommandLine.DragonFruit/CommandLine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ public static IEnumerable<Option> BuildOptions(this MethodInfo type)
};

foreach (var option in descriptor.ParameterDescriptors
.Where(d => !omittedTypes.Contains (d.Type))
.Where(d => !omittedTypes.Contains (d.ValueType))
.Where(d => !_argumentParameterNames.Contains(d.ValueName))
.Select(p => p.BuildOption()))
{
Expand All @@ -291,7 +291,7 @@ public static Option BuildOption(this ParameterDescriptor parameter)
{
var argument = new Argument
{
ArgumentType = parameter.Type
ArgumentType = parameter.ValueType
};

if (parameter.HasDefaultValue)
Expand Down
29 changes: 2 additions & 27 deletions src/System.CommandLine.Tests/Binding/HandlerDescriptorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public void It_provides_the_types_of_the_handler_parameters(Type parameterType)
var descriptor = HandlerDescriptor.FromMethodInfo(method);

descriptor.ParameterDescriptors
.Select(p => p.Type)
.Select(p => p.ValueType)
.Should()
.BeEquivalentSequenceTo(parameterType);
}
Expand Down Expand Up @@ -76,7 +76,7 @@ public void It_provides_the_types_of_the_handler_parameters(Type parameterType)
var descriptor = HandlerDescriptor.FromMethodInfo(method);

descriptor.ParameterDescriptors
.Select(p => p.Type)
.Select(p => p.ValueType)
.Should()
.BeEquivalentSequenceTo(parameterType);
}
Expand All @@ -85,30 +85,5 @@ public void It_provides_the_types_of_the_handler_parameters(Type parameterType)
public void Handler<T>(T value)
{
}

public class FromExpression
{
[Fact]
public void Handler_descriptor_describes_the_parameter_names_of_the_handler_method()
{
var descriptor = HandlerDescriptor.FromExpression<ClassWithInvokeAndDefaultCtor, string, int, Task<int>>((model, s, i) => model.Invoke(s, i));

descriptor.ParameterDescriptors
.Select(p => p.ValueName)
.Should()
.BeEquivalentSequenceTo("stringParam", "intParam");
}

[Fact]
public void Handler_descriptor_describes_the_parameter_types_of_the_handler_method()
{
var descriptor = HandlerDescriptor.FromExpression<ClassWithInvokeAndDefaultCtor, string, int, Task<int>>((model, s, i) => model.Invoke(s, i));

descriptor.ParameterDescriptors
.Select(p => p.Type)
.Should()
.BeEquivalentSequenceTo(typeof(string), typeof(int));
}
}
}
}
70 changes: 66 additions & 4 deletions src/System.CommandLine.Tests/Binding/ModelBinderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.CommandLine.Binding;
using System.CommandLine.Builder;
using System.CommandLine.Invocation;
using System.CommandLine.Parsing;
using System.IO;
using FluentAssertions;
Expand Down Expand Up @@ -523,8 +525,10 @@ public void Explicit_model_binder_binds_only_to_configured_properties()
var parser = new Parser(intOption, stringOption);

var bindingContext = new BindingContext(parser.Parse("--int-property 42 --string-property Hello"));
var binder = new ModelBinder<ClassWithMultiLetterSetters>()
{ EnforceExplicitBinding = true };
var binder = new ModelBinder<ClassWithMultiLetterSetters>
{
EnforceExplicitBinding = true
};
binder.BindMemberFromValue(obj => obj.IntOption, intOption);
var instance = binder.CreateInstance(bindingContext) as ClassWithMultiLetterSetters;

Expand All @@ -545,14 +549,72 @@ public void Explicit_model_binder_binds_only_to_configured_ctor_parameters()
var paramInfo = ctor.GetParameters().First();

var bindingContext = new BindingContext(parser.Parse("-a 42 -b Hello"));
var binder = new ModelBinder<ClassWithMultiLetterCtorParameters>()
{ EnforceExplicitBinding = true };
var binder = new ModelBinder<ClassWithMultiLetterCtorParameters>
{
EnforceExplicitBinding = true
};
binder.BindConstructorArgumentFromValue(paramInfo, intOption);
var instance = binder.CreateInstance(bindingContext) as ClassWithMultiLetterCtorParameters;

instance.Should().NotBeNull();
instance.IntOption.Should().Be(42);
instance.StringOption.Should().Be("the default");
}

[Fact]
public void Custom_ModelBinders_specified_via_BindingContext_can_be_used_for_option_binding()
{
ClassWithSetter<int> boundInstance = null;

var rootCommand = new RootCommand
{
new Option<int>("--value")
};

rootCommand.Handler = CommandHandler.Create<ClassWithSetter<int>>(x => boundInstance = x);

var parser = new CommandLineBuilder(rootCommand)
.UseMiddleware(context =>
{
var binder = new ModelBinder<ClassWithSetter<int>>();

binder.BindMemberFromValue(instance => instance.Value, _ => 456);

context.BindingContext.AddModelBinder(binder);
})
.Build();

parser.Invoke("--value 123");

boundInstance.Value.Should().Be(456);
}

[Fact]
public void Custom_ModelBinders_specified_via_BindingContext_can_be_used_for_command_argument_binding()
{
ClassWithSetter<int> boundInstance = null;

var rootCommand = new RootCommand
{
new Argument<int>()
};

rootCommand.Handler = CommandHandler.Create<ClassWithSetter<int>>(x => boundInstance = x);

var parser = new CommandLineBuilder(rootCommand)
.UseMiddleware(context =>
{
var binder = new ModelBinder<ClassWithSetter<int>>();

binder.BindMemberFromValue(instance => instance.Value, _ => 456);

context.BindingContext.AddModelBinder(binder);
})
.Build();

parser.Invoke("123");

boundInstance.Value.Should().Be(456);
}
}
}
1 change: 0 additions & 1 deletion src/System.CommandLine.Tests/Binding/TestModels.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Threading.Tasks;

namespace System.CommandLine.Tests.Binding
Expand Down
2 changes: 1 addition & 1 deletion src/System.CommandLine/Argument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,6 @@ public override IEnumerable<string> GetSuggestions(string textToMatch = null)

string IValueDescriptor.ValueName => Name;

Type IValueDescriptor.Type => ArgumentType;
Type IValueDescriptor.ValueType => ArgumentType;
}
}
42 changes: 22 additions & 20 deletions src/System.CommandLine/Binding/BindingContext.cs
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.Generic;
using System.CommandLine.Help;
using System.CommandLine.Invocation;
using System.CommandLine.IO;
using System.CommandLine.Parsing;
using System.Linq;

#nullable enable

namespace System.CommandLine.Binding
{
public sealed class BindingContext
{
private IConsole _console;
private readonly Dictionary<Type, ModelBinder> _modelBindersByValueDescriptor = new Dictionary<Type, ModelBinder>();

public BindingContext(
ParseResult parseResult,
IConsole console = null)
IConsole? console = default)
{
_console = console ?? new SystemConsole();

Expand All @@ -25,9 +29,9 @@ public BindingContext(

public ParseResult ParseResult { get; set; }

internal IConsoleFactory ConsoleFactory { get; set; }
internal IConsoleFactory? ConsoleFactory { get; set; }

internal IHelpBuilder HelpBuilder => (IHelpBuilder)ServiceProvider.GetService(typeof(IHelpBuilder));
internal IHelpBuilder HelpBuilder => (IHelpBuilder)ServiceProvider.GetService(typeof(IHelpBuilder))!;

public IConsole Console
{
Expand All @@ -46,18 +50,16 @@ public IConsole Console

internal ServiceProvider ServiceProvider { get; }

public void AddService(Type serviceType, Func<IServiceProvider, object> factory)
{
if (serviceType == null)
{
throw new ArgumentNullException(nameof(serviceType));
}
public void AddModelBinder(ModelBinder binder) =>
_modelBindersByValueDescriptor.Add(binder.ValueDescriptor.ValueType, binder);

if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
public ModelBinder GetModelBinder(IValueDescriptor valueDescriptor) =>
_modelBindersByValueDescriptor.GetOrAdd(
valueDescriptor.ValueType,
_ => new ModelBinder(valueDescriptor));

public void AddService(Type serviceType, Func<IServiceProvider, object> factory)
{
ServiceProvider.AddService(serviceType, factory);
}

Expand All @@ -73,26 +75,26 @@ public void AddService<T>(Func<IServiceProvider, T> factory)

internal bool TryGetValueSource(
IValueDescriptor valueDescriptor,
out IValueSource valueSource)
out IValueSource? valueSource)
{
if (ServiceProvider.AvailableServiceTypes.Contains(valueDescriptor.Type))
if (ServiceProvider.AvailableServiceTypes.Contains(valueDescriptor.ValueType))
{
valueSource = new ServiceProviderValueSource();
return true;
}

valueSource = null;
valueSource = default;
return false;
}

internal bool TryBindToScalarValue(
IValueDescriptor valueDescriptor,
IValueSource valueSource,
out BoundValue boundValue)
out BoundValue? boundValue)
{
if (valueSource.TryGetValue(valueDescriptor, this, out var value))
{
if (value == null || valueDescriptor.Type.IsInstanceOfType(value))
if (value == null || valueDescriptor.ValueType.IsInstanceOfType(value))
{
boundValue = new BoundValue(value, valueDescriptor, valueSource);
return true;
Expand All @@ -101,7 +103,7 @@ internal bool TryBindToScalarValue(
{
var parsed = ArgumentConverter.ConvertObject(
valueDescriptor as IArgument ?? new Argument(valueDescriptor.ValueName),
valueDescriptor.Type,
valueDescriptor.ValueType,
value);

if (parsed is SuccessfulArgumentConversionResult successful)
Expand All @@ -112,7 +114,7 @@ internal bool TryBindToScalarValue(
}
}

boundValue = null;
boundValue = default;
return false;
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/System.CommandLine/Binding/BoundValue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ internal BoundValue(
IValueSource valueSource)
{
if (value != null &&
!valueDescriptor.Type.IsInstanceOfType(value))
!valueDescriptor.ValueType.IsInstanceOfType(value))
{
throw new ArgumentException($"Value {value} ({value.GetType()}) must be an instance of type {valueDescriptor.Type}");
throw new ArgumentException($"Value {value} ({value.GetType()}) must be an instance of type {valueDescriptor.ValueType}");
}

Value = value;
Expand Down
6 changes: 1 addition & 5 deletions src/System.CommandLine/Binding/DelegateHandlerDescriptor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,9 @@ public DelegateHandlerDescriptor(Delegate handlerDelegate)

public override ICommandHandler GetCommandHandler()
{
var parameterBinders = ParameterDescriptors
.Select(p => new ModelBinder(p))
.ToList();

return new ModelBindingCommandHandler(
_handlerDelegate,
parameterBinders);
ParameterDescriptors);
}

public override ModelDescriptor Parent => null;
Expand Down
60 changes: 0 additions & 60 deletions src/System.CommandLine/Binding/ExpressionHandlerDescriptor.cs

This file was deleted.

Loading