Skip to content

Fix #1638 #1677

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 11 commits into from
Mar 23, 2022
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
29 changes: 29 additions & 0 deletions src/Common/ArgumentBuilder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@

using System;
using System.CommandLine;
using System.Reflection;

internal static class ArgumentBuilder
{
private static readonly ConstructorInfo _ctor;

static ArgumentBuilder()
{
_ctor = typeof(Argument<string>).GetConstructor(new[] { typeof(string), typeof(string) });
}

public static Argument CreateArgument(Type valueType, string name = "value")
{
var argumentType = typeof(Argument<>).MakeGenericType(valueType);

#if NET6_0_OR_GREATER
var ctor = (ConstructorInfo)argumentType.GetMemberWithSameMetadataDefinitionAs(_ctor);
#else
var ctor = argumentType.GetConstructor(new[] { typeof(string), typeof(string) });
#endif

var option = (Argument)ctor.Invoke(new object[] { name, null });

return option;
}
}
31 changes: 31 additions & 0 deletions src/Common/OptionBuilder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// 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.Reflection;

namespace System.CommandLine.Utility;

internal static class OptionBuilder
{
private static readonly ConstructorInfo _ctor;

static OptionBuilder()
{
_ctor = typeof(Option<string>).GetConstructor(new[] { typeof(string), typeof(string) });
}

public static Option CreateOption(string name, Type valueType)
{
var optionType = typeof(Option<>).MakeGenericType(valueType);

#if NET6_0_OR_GREATER
var ctor = (ConstructorInfo)optionType.GetMemberWithSameMetadataDefinitionAs(_ctor);
#else
var ctor = optionType.GetConstructor(new[] { typeof(string), typeof(string) });
#endif

var option = (Option)ctor.Invoke(new object[] { name, null });

return option;
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
System.CommandLine
public class Argument : Symbol, System.CommandLine.Binding.IValueDescriptor, System.CommandLine.Completions.ICompletionSource
.ctor()
.ctor(System.String name = null, System.String description = null)
public abstract class Argument : Symbol, System.CommandLine.Binding.IValueDescriptor, System.CommandLine.Completions.ICompletionSource
public ArgumentArity Arity { get; set; }
public CompletionSourceList Completions { get; }
public System.Boolean HasDefaultValue { get; }
public System.String HelpName { get; set; }
public System.Type ValueType { get; set; }
public System.Type ValueType { get; }
public System.Void AddValidator(System.CommandLine.Parsing.ValidateSymbolResult<System.CommandLine.Parsing.ArgumentResult> validate)
public System.Collections.Generic.IEnumerable<System.CommandLine.Completions.CompletionItem> GetCompletions(System.CommandLine.Completions.CompletionContext context)
public System.Object GetDefaultValue()
Expand All @@ -21,7 +19,7 @@
.ctor(Func<T> getDefaultValue)
.ctor(System.String name, ParseArgument<T> parse, System.Boolean isDefault = False, System.String description = null)
.ctor(ParseArgument<T> parse, System.Boolean isDefault = False)
public System.Type ValueType { get; set; }
public System.Type ValueType { get; }
public struct ArgumentArity : System.ValueType, System.IEquatable<ArgumentArity>
public static ArgumentArity ExactlyOne { get; }
public static ArgumentArity OneOrMore { get; }
Expand Down Expand Up @@ -181,9 +179,7 @@
public System.String UnrecognizedCommandOrArgument(System.String arg)
public System.String VersionOptionCannotBeCombinedWithOtherArguments(System.String optionAlias)
public System.String VersionOptionDescription()
public class Option : IdentifierSymbol, System.CommandLine.Binding.IValueDescriptor, System.CommandLine.Completions.ICompletionSource
.ctor(System.String name, System.String description = null, System.Type argumentType = null, System.Func<System.Object> getDefaultValue = null, ArgumentArity arity = null)
.ctor(System.String[] aliases, System.String description = null, System.Type argumentType = null, System.Func<System.Object> getDefaultValue = null, ArgumentArity arity = null)
public abstract class Option : IdentifierSymbol, System.CommandLine.Binding.IValueDescriptor, System.CommandLine.Completions.ICompletionSource
public System.Boolean AllowMultipleArgumentsPerToken { get; set; }
public System.String ArgumentHelpName { get; set; }
public ArgumentArity Arity { get; set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,9 @@ public class Perf_Parser_Options_Bare
private IEnumerable<Option> GenerateTestOptions(int count, ArgumentArity arity)
=> Enumerable.Range(0, count)
.Select(i =>
new Option($"-option{i}", arity: arity)
new Option<string>($"-option{i}")
{
Arity = arity,
Description = $"Description for -option {i} ...."
}
);
Expand All @@ -50,7 +51,7 @@ public void SetupTestOptions()
[Benchmark]
public Parser ParserFromOptions_Ctor()
{
return Utils.CreateParser(_testSymbols);
return _testSymbols.CreateParser();
}

[GlobalSetup(Target = nameof(ParserFromOptions_Parse))]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@ public class Perf_Parser_Options_With_Arguments

private IEnumerable<Option> GenerateTestOptions(int count, ArgumentArity arity)
=> Enumerable.Range(0, count)
.Select(i => new Option($"-option{i}", arity: arity)
.Select(i => new Option<string>($"-option{i}")
{
Arity = arity,
Description = $"Description for -option {i} ...."
}
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public class Perf_Parser_ParseResult

public Perf_Parser_ParseResult()
{
var option = new Option("-opt");
var option = new Option<bool>("-opt");

_testParser =
new CommandLineBuilder(new RootCommand { option })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public class Perf_Parser_TypoCorrection

public Perf_Parser_TypoCorrection()
{
var option = new Option("--0123456789");
var option = new Option<bool>("--0123456789");

_testParser = new CommandLineBuilder(new RootCommand { option })
.UseTypoCorrections()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,15 @@ private string[] GenerateSuggestionsArray(int count)

private IEnumerable<Option> GenerateOptionsArray(int count)
=> Enumerable.Range(0, count)
.Select(i => new Option($"suggestion{i}"));
.Select(i => new Option<string>($"suggestion{i}"));

[Params(1, 5, 20, 100)]
public int TestSuggestionsCount;

[GlobalSetup(Target = nameof(SuggestionsFromSymbol))]
public void Setup_FromSymbol()
{
_testSymbol = new Option("--hello", arity: ArgumentArity.ExactlyOne)
_testSymbol = new Option<string>("--hello")
.AddCompletions(GenerateSuggestionsArray(TestSuggestionsCount));
}

Expand Down
28 changes: 15 additions & 13 deletions src/System.CommandLine.DragonFruit/CommandLine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.CommandLine.NamingConventionBinder;
using System.CommandLine.Parsing;
using System.CommandLine.Rendering;
using System.CommandLine.Utility;
using System.IO;
using System.Linq;
using System.Reflection;
Expand Down Expand Up @@ -163,18 +164,13 @@ public static void ConfigureFromMethod(
command.AddOption(option);
}

if (method.GetParameters()
.FirstOrDefault(p => _argumentParameterNames.Contains(p.Name)) is ParameterInfo argsParam)
if (method.GetParameters().FirstOrDefault(p => _argumentParameterNames.Contains(p.Name)) is { } argsParam)
{
var argument = new Argument
{
ValueType = argsParam.ParameterType,
Name = argsParam.Name
};
var argument = ArgumentBuilder.CreateArgument(argsParam.ParameterType, argsParam.Name);

if (argsParam.HasDefaultValue)
{
if (argsParam.DefaultValue != null)
if (argsParam.DefaultValue is not null)
{
argument.SetDefaultValue(argsParam.DefaultValue);
}
Expand Down Expand Up @@ -296,11 +292,17 @@ public static Option BuildOption(this ParameterDescriptor parameter)
{
getDefaultValue = parameter.GetDefaultValue;
}
return new Option(
parameter.BuildAlias(),
parameter.ValueName,
parameter.ValueType,
getDefaultValue);

var option = OptionBuilder.CreateOption(parameter.BuildAlias(), parameter.ValueType);

option.Description = parameter.ValueName;

if (getDefaultValue is not null)
{
option.SetDefaultValueFactory(getDefaultValue);
}

return option;
}

private static string GetDefaultXmlDocsFileLocation(Assembly assembly)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,9 @@
<ProjectReference Include="..\System.CommandLine.NamingConventionBinder\System.CommandLine.NamingConventionBinder.csproj" />
<Content Include="targets/*" PackagePath="build/$(TargetFramework)/" />
</ItemGroup>

<ItemGroup>
<Compile Include="..\Common\ArgumentBuilder.cs" Link="Utility\ArgumentBuilder.cs" />
<Compile Include="..\Common\OptionBuilder.cs" Link="Utility\OptionBuilder.cs" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.CommandLine.Invocation;
using System.CommandLine.Parsing;
using System.CommandLine.Tests.Binding;
using System.CommandLine.Utility;
using System.IO;
using System.Threading.Tasks;
using FluentAssertions;
Expand All @@ -30,7 +31,7 @@ public void Option_arguments_are_bound_by_name_to_constructor_parameters(

var command = new Command("the-command")
{
new Option("--value", argumentType: type)
OptionBuilder.CreateOption("--value", type)
};

var bindingContext = new InvocationContext(command.Parse(commandLine)).BindingContext;
Expand All @@ -57,11 +58,7 @@ public void Command_arguments_are_bound_by_name_to_constructor_parameters(

var command = new Command("the-command")
{
new Argument
{
Name = "value",
ValueType = type
}
ArgumentBuilder.CreateArgument(type)
};

var bindingContext = new InvocationContext(command.Parse(commandLine)).BindingContext;
Expand All @@ -84,11 +81,7 @@ public void Command_arguments_are_bound_by_name_to_complex_constructor_parameter

var command = new Command("the-command")
{
new Argument
{
Name = "value",
ValueType = type
}
ArgumentBuilder.CreateArgument(type)
};

var bindingContext = new InvocationContext(command.Parse(commandLine)).BindingContext;
Expand Down Expand Up @@ -135,7 +128,7 @@ public void Option_arguments_are_bound_by_name_to_property_setters(

var command = new Command("the-command")
{
new Option("--value", argumentType: type)
OptionBuilder.CreateOption("--value", type)
};
var parser = new Parser(command);

Expand Down Expand Up @@ -163,11 +156,7 @@ public void Command_arguments_are_bound_by_name_to_property_setters(

var command = new Command("the-command")
{
new Argument
{
Name = "value",
ValueType = type
}
ArgumentBuilder.CreateArgument(type)
};
var parser = new Parser(command);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
// // 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.CommandLine.Binding;
using System.CommandLine.Invocation;
using System.CommandLine.IO;
using System.CommandLine.Tests.Binding;
using System.CommandLine.Utility;
using System.IO;
using System.Threading.Tasks;
using FluentAssertions;
Expand Down Expand Up @@ -35,7 +35,7 @@ public async Task Option_arguments_are_bound_by_name_to_method_parameters(

var command = new Command("the-command")
{
new Option("--value", argumentType: type)
OptionBuilder.CreateOption("--value", type)
};

var console = new TestConsole();
Expand Down Expand Up @@ -67,7 +67,7 @@ public async Task Option_arguments_are_bound_by_name_to_the_properties_of_method

var command = new Command("the-command")
{
new Option("--value", argumentType: type)
OptionBuilder.CreateOption("--value", type)
};

var console = new TestConsole();
Expand Down Expand Up @@ -99,7 +99,7 @@ public async Task Option_arguments_are_bound_by_name_to_the_constructor_paramete

var command = new Command("the-command")
{
new Option("--value", argumentType: type)
OptionBuilder.CreateOption("--value", type)
};

var console = new TestConsole();
Expand Down Expand Up @@ -127,11 +127,7 @@ public async Task Command_arguments_are_bound_by_name_to_handler_method_paramete

var command = new Command("the-command")
{
new Argument
{
Name = "value",
ValueType = type
}
ArgumentBuilder.CreateArgument(type)
};

var console = new TestConsole();
Expand Down
Loading