Skip to content
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

Treat Options without parameterless constructor as immutable #891

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 8 additions & 6 deletions src/CommandLine/Core/InstanceBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using CommandLine.Infrastructure;
using CSharpx;
using RailwaySharp.ErrorHandling;
using System.Reflection;

namespace CommandLine.Core
{
Expand Down Expand Up @@ -61,11 +62,12 @@ static class InstanceBuilder
.OfType<OptionSpecification>()
.Memoize();

Func<T> makeDefault = () =>
Func<T> makeDefaultImmutable = () => ReflectionHelper.CreateDefaultImmutableInstance<T>((from p in specProps select p.Specification.ConversionType).ToArray());

Func<T> makeDefault =
typeof(T).IsMutable()
? factory.MapValueOrDefault(f => f(), () => Activator.CreateInstance<T>())
: ReflectionHelper.CreateDefaultImmutableInstance<T>(
(from p in specProps select p.Specification.ConversionType).ToArray());
? () => factory.MapValueOrDefault(f => f(), () => typeof(T).HasParameterlessConstructor() ? Activator.CreateInstance<T>() : makeDefaultImmutable())
: makeDefaultImmutable;

Func<IEnumerable<Error>, ParserResult<T>> notParsed =
errs => new NotParsed<T>(makeDefault().GetType().ToTypeInfo(), errs);
Expand Down Expand Up @@ -110,7 +112,7 @@ static class InstanceBuilder

//build the instance, determining if the type is mutable or not.
T instance;
if(typeInfo.IsMutable() == true)
if (typeInfo.IsMutable() && (!factory.IsNothing() || typeInfo.HasParameterlessConstructor()))
{
instance = BuildMutable(factory, specPropsWithValue, setPropertyErrors);
}
Expand Down
9 changes: 7 additions & 2 deletions src/CommandLine/Core/ReflectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ public static bool IsMutable(this Type type)
// Find all inherited defined properties and fields on the type
var inheritedTypes = type.GetTypeInfo().FlattenHierarchy().Select(i => i.GetTypeInfo());

foreach (var inheritedType in inheritedTypes)
foreach (var inheritedType in inheritedTypes)
{
if (
inheritedType.GetTypeInfo().GetProperties(BindingFlags.Public | BindingFlags.Instance).Any(p => p.CanWrite) ||
Expand All @@ -145,6 +145,11 @@ public static bool IsMutable(this Type type)
return false;
}

public static bool HasParameterlessConstructor(this Type type)
{
return type.GetTypeInfo().GetConstructor(Type.EmptyTypes) != null;
}

public static object CreateDefaultForImmutable(this Type type)
{
if (type.GetTypeInfo().IsGenericType && type.GetTypeInfo().GetGenericTypeDefinition() == typeof(IEnumerable<>))
Expand All @@ -156,7 +161,7 @@ public static object CreateDefaultForImmutable(this Type type)

public static object AutoDefault(this Type type)
{
if (type.IsMutable())
if (type.IsMutable() && type.HasParameterlessConstructor())
{
return Activator.CreateInstance(type);
}
Expand Down
2 changes: 1 addition & 1 deletion src/CommandLine/Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public ParserResult<T> ParseArguments<T>(IEnumerable<string> args)
{
if (args == null) throw new ArgumentNullException("args");

var factory = typeof(T).IsMutable()
var factory = typeof(T).IsMutable() && typeof(T).HasParameterlessConstructor()
? Maybe.Just<Func<T>>(Activator.CreateInstance<T>)
: Maybe.Nothing<Func<T>>();

Expand Down
38 changes: 38 additions & 0 deletions tests/CommandLine.Tests/Unit/Issue890Tests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using System.Linq;
using CommandLine.Tests.Fakes;
using CommandLine.Text;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;

//Issue #890
//When options class is mutable but doesn't have a parameterless constructor parsing fails.

namespace CommandLine.Tests.Unit
{
public class Issue890Tests
{
const char OptionSwitch = 'o';
[Fact]
public void Create_mutable_instance_without_parameterless_ctor_should_not_fail()
{
const string optionValue = "val";

var result = Parser.Default.ParseArguments<Options>(new string[] { $"-{OptionSwitch}", optionValue });

Assert.Equal(ParserResultType.Parsed, result.Tag);
Assert.NotNull(result.Value);
Assert.Equal(optionValue, result.Value.Opt);
Assert.Empty(result.Errors);
}
private class Options
{
public Options(string opt)
{
Opt = opt;
}
[Option(OptionSwitch, "opt", Required = false)]
public string Opt { get; set; }
}
}
}