From 02f7615ab06592ed0d2f0312e79473d3e8722831 Mon Sep 17 00:00:00 2001 From: Monica S Date: Sat, 12 Jun 2021 12:19:43 +0100 Subject: [PATCH] Allow commands with no parameters to compile (#20) Use `Array.Empty()` instead of `new[] { }` or `new IParameter[] { }` when no parameters are specified --- .../Console/TestCommands/HelloWorldCommand.cs | 8 +++++++ ...butedModelSourceGenerator.CommandSource.cs | 24 ++++++++++++------- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/samples/Console/TestCommands/HelloWorldCommand.cs b/samples/Console/TestCommands/HelloWorldCommand.cs index e5cfa8f..9512261 100644 --- a/samples/Console/TestCommands/HelloWorldCommand.cs +++ b/samples/Console/TestCommands/HelloWorldCommand.cs @@ -42,5 +42,13 @@ public ValueTask HelloWorldCommand( return new ValueTask(new NoContentCommandResult()); } + + [Command("code")] + public ValueTask HelloCodeCommand() + { + _logger.LogInformation("Hello code from HelloModule!"); + + return new ValueTask(new NoContentCommandResult()); + } } } diff --git a/tools/SourceGenerators/Models/AttributedModel/AttributedModelSourceGenerator.CommandSource.cs b/tools/SourceGenerators/Models/AttributedModel/AttributedModelSourceGenerator.CommandSource.cs index b6d94a5..dd3a37c 100644 --- a/tools/SourceGenerators/Models/AttributedModel/AttributedModelSourceGenerator.CommandSource.cs +++ b/tools/SourceGenerators/Models/AttributedModel/AttributedModelSourceGenerator.CommandSource.cs @@ -80,6 +80,13 @@ var parameterNamespaces .Select( x => $"new CommandFactory__{@class.Name}__{method.Name}__{x.Name}()")); + var parameterArray = parameterTypes == string.Empty + ? "Array.Empty()" + : $@"new IParameter[] + {{ + {parameterTypes} + }}"; + var parameterAccessors = string.Join(", ", method.Parameters .Select( @@ -97,6 +104,13 @@ var parameterNamespaces method.Parameters .Select(x => $"typeof({x.ToDisplayString()})")); + var reflectionArray = reflectionTypes == string.Empty + ? "types: Array.Empty()" + : $@"types: new[] + {{ + {reflectionTypes} + }}"; + return $@"{namespaces} @@ -118,10 +132,7 @@ private static readonly MethodInfo Method bindingAttr: {GetBindingFlags(method)}, binder: default, callConvention: {GetCallConv(method)}, - types: new[] - {{ - {reflectionTypes} - }}, + {reflectionArray}, modifiers: null)!; private IReadOnlyDictionary? _data; @@ -129,10 +140,7 @@ private static readonly MethodInfo Method public CommandString Name {{ get; }} = {commandPath}; public IReadOnlyList Parameters {{ get; }} - = new IParameter[] - {{ - {parameterTypes} - }}; + = {parameterArray}; public IReadOnlyDictionary Data {{