From 616d7504ffa62073fb126c6594516ecede21648d Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sun, 6 Jul 2025 10:36:09 +1000 Subject: [PATCH] use collection expressions --- src/Common/ArgumentBuilder.cs | 6 +-- src/Common/OptionBuilder.cs | 8 +-- .../DotnetSuggestEndToEndTests.cs | 6 ++- .../GlobalToolsSuggestionRegistrationTests.cs | 7 +-- .../SuggestionDispatcherTests.cs | 2 +- .../TestSuggestionRegistration.cs | 2 +- .../Binding/TestModels.cs | 2 +- .../Binding/TypeConversionTests.cs | 8 +-- .../CompletionContextTests.cs | 10 ++-- .../CompletionTests.cs | 8 +-- .../CustomParsingTests.cs | 36 ++++++------- .../GetValueByNameParserTests.cs | 2 +- .../Help/HelpBuilderTests.Customization.cs | 2 +- .../Help/HelpBuilderTests.cs | 10 ++-- .../CancelOnProcessTerminationTests.cs | 4 +- src/System.CommandLine.Tests/OptionTests.cs | 2 +- .../ParserTests.MultipleArguments.cs | 8 +-- src/System.CommandLine.Tests/ParserTests.cs | 50 +++++++++++-------- .../ParsingValidationTests.cs | 12 ++--- .../ResponseFileTests.cs | 2 +- .../SuggestDirectiveTests.cs | 2 +- .../TokenReplacementTests.cs | 8 +-- .../Utility/RemoteExecutor.cs | 10 ++-- src/System.CommandLine/Argument.cs | 6 +-- .../Help/HelpBuilder.Default.cs | 4 +- src/System.CommandLine/Option.cs | 2 +- 26 files changed, 116 insertions(+), 103 deletions(-) diff --git a/src/Common/ArgumentBuilder.cs b/src/Common/ArgumentBuilder.cs index 5c24853f32..e64c10a4f1 100644 --- a/src/Common/ArgumentBuilder.cs +++ b/src/Common/ArgumentBuilder.cs @@ -9,7 +9,7 @@ internal static class ArgumentBuilder static ArgumentBuilder() { - _ctor = typeof(Argument).GetConstructor(new[] { typeof(string) }); + _ctor = typeof(Argument).GetConstructor([typeof(string)]); } public static Argument CreateArgument(Type valueType, string name = "value") @@ -34,9 +34,9 @@ internal static Argument CreateArgument(ParameterInfo argsParam) var argumentType = typeof(Bridge<>).MakeGenericType(argsParam.ParameterType); - var ctor = argumentType.GetConstructor(new[] { typeof(string), argsParam.ParameterType }); + var ctor = argumentType.GetConstructor([typeof(string), argsParam.ParameterType]); - return (Argument)ctor.Invoke(new object[] { argsParam.Name, argsParam.DefaultValue }); + return (Argument)ctor.Invoke([argsParam.Name, argsParam.DefaultValue]); } private sealed class Bridge : Argument diff --git a/src/Common/OptionBuilder.cs b/src/Common/OptionBuilder.cs index fa9ca5d232..26c4c65704 100644 --- a/src/Common/OptionBuilder.cs +++ b/src/Common/OptionBuilder.cs @@ -11,7 +11,7 @@ internal static class OptionBuilder static OptionBuilder() { - _ctor = typeof(Option).GetConstructor(new[] { typeof(string), typeof(string[]) }); + _ctor = typeof(Option).GetConstructor([typeof(string), typeof(string[])]); } internal static Option CreateOption(string name, Type valueType, string description = null) @@ -24,7 +24,7 @@ internal static Option CreateOption(string name, Type valueType, string descript var ctor = optionType.GetConstructor(new[] { typeof(string), typeof(string[]) }); #endif - var option = (Option)ctor.Invoke(new object[] { name, Array.Empty() }); + var option = (Option)ctor.Invoke([name, Array.Empty()]); option.Description = description; @@ -40,9 +40,9 @@ internal static Option CreateOption(string name, Type valueType, string descript var optionType = typeof(Bridge<>).MakeGenericType(valueType); - var ctor = optionType.GetConstructor(new[] { typeof(string), typeof(Func), typeof(string) }); + var ctor = optionType.GetConstructor([typeof(string), typeof(Func), typeof(string)]); - var option = (Option)ctor.Invoke(new object[] { name, defaultValueFactory, description }); + var option = (Option)ctor.Invoke([name, defaultValueFactory, description]); return option; } diff --git a/src/System.CommandLine.Suggest.Tests/DotnetSuggestEndToEndTests.cs b/src/System.CommandLine.Suggest.Tests/DotnetSuggestEndToEndTests.cs index 7e08fc8d65..aff62d7103 100644 --- a/src/System.CommandLine.Suggest.Tests/DotnetSuggestEndToEndTests.cs +++ b/src/System.CommandLine.Suggest.Tests/DotnetSuggestEndToEndTests.cs @@ -52,9 +52,11 @@ public DotnetSuggestEndToEndTests(ITestOutputHelper output) PrepareTestHomeDirectoryToAvoidPolluteBuildMachineHome(); - _environmentVariables = new[] { + _environmentVariables = + [ ("DOTNET_ROOT", _dotnetHostDir.FullName), - ("INTERNAL_TEST_DOTNET_SUGGEST_HOME", _testRoot)}; + ("INTERNAL_TEST_DOTNET_SUGGEST_HOME", _testRoot) + ]; } public void Dispose() diff --git a/src/System.CommandLine.Suggest.Tests/GlobalToolsSuggestionRegistrationTests.cs b/src/System.CommandLine.Suggest.Tests/GlobalToolsSuggestionRegistrationTests.cs index d3ef83b775..989343ba81 100644 --- a/src/System.CommandLine.Suggest.Tests/GlobalToolsSuggestionRegistrationTests.cs +++ b/src/System.CommandLine.Suggest.Tests/GlobalToolsSuggestionRegistrationTests.cs @@ -10,7 +10,7 @@ namespace System.CommandLine.Suggest.Tests { public class GlobalToolsSuggestionRegistrationTests { - public static IEnumerable FilesNameWithoutExtensionUnderDotnetProfileToolsExample = new[] { "dotnet-suggest", "t-rex" }; + public static IEnumerable FilesNameWithoutExtensionUnderDotnetProfileToolsExample = ["dotnet-suggest", "t-rex"]; [Fact] public void Path_is_in_global_tools() { @@ -50,11 +50,12 @@ public void Global_tools_can_be_found() registrationPairs .Should() - .BeEquivalentTo( new [] { + .BeEquivalentTo([ new Registration( Path.Combine(dotnetProfileDirectory, "tools", "dotnet-suggest")), new Registration( - Path.Combine(dotnetProfileDirectory, "tools", "t-rex"))}); + Path.Combine(dotnetProfileDirectory, "tools", "t-rex")) + ]); } } } diff --git a/src/System.CommandLine.Suggest.Tests/SuggestionDispatcherTests.cs b/src/System.CommandLine.Suggest.Tests/SuggestionDispatcherTests.cs index fa7c4841d2..c15cb4434c 100644 --- a/src/System.CommandLine.Suggest.Tests/SuggestionDispatcherTests.cs +++ b/src/System.CommandLine.Suggest.Tests/SuggestionDispatcherTests.cs @@ -153,7 +153,7 @@ public async Task List_command_gets_all_executable_names() var dispatcher = new SuggestionDispatcher(testSuggestionProvider); dispatcher.Configuration.Output = new StringWriter(); - await dispatcher.InvokeAsync(new[] { "list" }); + await dispatcher.InvokeAsync(["list"]); dispatcher.Configuration.Output .ToString() diff --git a/src/System.CommandLine.Suggest.Tests/TestSuggestionRegistration.cs b/src/System.CommandLine.Suggest.Tests/TestSuggestionRegistration.cs index 2d0760becc..e92e6974b9 100644 --- a/src/System.CommandLine.Suggest.Tests/TestSuggestionRegistration.cs +++ b/src/System.CommandLine.Suggest.Tests/TestSuggestionRegistration.cs @@ -9,7 +9,7 @@ namespace System.CommandLine.Suggest.Tests { internal class TestSuggestionRegistration : ISuggestionRegistration { - private readonly List _suggestionRegistrations = new(); + private readonly List _suggestionRegistrations = []; public TestSuggestionRegistration(params Registration[] suggestionRegistrations) { diff --git a/src/System.CommandLine.Tests/Binding/TestModels.cs b/src/System.CommandLine.Tests/Binding/TestModels.cs index 49cd584e22..4ca907c8d7 100644 --- a/src/System.CommandLine.Tests/Binding/TestModels.cs +++ b/src/System.CommandLine.Tests/Binding/TestModels.cs @@ -37,7 +37,7 @@ public class ClassWithComplexTypes public string StringOption { get; set; } public bool BoolOption { get; set; } public List ListOptionDefaultNull { get; set; } - public List> ListOptionDefaultEmpty { get; set; } = new (); + public List> ListOptionDefaultEmpty { get; set; } = []; } public class ClassWithListTypePropertiesAndDefaultCtor diff --git a/src/System.CommandLine.Tests/Binding/TypeConversionTests.cs b/src/System.CommandLine.Tests/Binding/TypeConversionTests.cs index 454942a873..7bd2e12324 100644 --- a/src/System.CommandLine.Tests/Binding/TypeConversionTests.cs +++ b/src/System.CommandLine.Tests/Binding/TypeConversionTests.cs @@ -82,7 +82,7 @@ public void Command_argument_of_FileInfo_returns_null_when_argument_is_not_provi public void Argument_of_FileInfo_that_is_empty_results_in_an_informative_error() { var option = new Option("--file"); - var result = new RootCommand { option }.Parse(new string[] { "--file", "" }); + var result = new RootCommand { option }.Parse(["--file", ""]); result.Errors .Should() @@ -691,7 +691,7 @@ public void Values_can_be_correctly_converted_to_nullable_uint_without_the_parse [Fact] public void Values_can_be_correctly_converted_to_array_of_int_without_the_parser_specifying_a_custom_converter() - => GetValue(new Option("-x"), "-x 1 -x 2 -x 3").Should().BeEquivalentTo(new[] { 1, 2, 3 }); + => GetValue(new Option("-x"), "-x 1 -x 2 -x 3").Should().BeEquivalentTo([1, 2, 3]); [Theory] [InlineData(0, 100_000, typeof(string[]))] @@ -736,11 +736,11 @@ public void Max_arity_greater_than_1_converts_to_enumerable_types( [Fact] public void Values_can_be_correctly_converted_to_List_of_int_without_the_parser_specifying_a_custom_converter() - => GetValue(new Option>("-x"), "-x 1 -x 2 -x 3").Should().BeEquivalentTo(new[] {1, 2, 3}); + => GetValue(new Option>("-x"), "-x 1 -x 2 -x 3").Should().BeEquivalentTo([1, 2, 3]); [Fact] public void Values_can_be_correctly_converted_to_IEnumerable_of_int_without_the_parser_specifying_a_custom_converter() - => GetValue(new Option>("-x"), "-x 1 -x 2 -x 3").Should().BeEquivalentTo(new[] { 1, 2, 3 }); + => GetValue(new Option>("-x"), "-x 1 -x 2 -x 3").Should().BeEquivalentTo([1, 2, 3]); [Fact] public void Enum_values_can_be_correctly_converted_based_on_enum_value_name_without_the_parser_specifying_a_custom_converter() diff --git a/src/System.CommandLine.Tests/CompletionContextTests.cs b/src/System.CommandLine.Tests/CompletionContextTests.cs index 09d805d6e1..ef3a03abe8 100644 --- a/src/System.CommandLine.Tests/CompletionContextTests.cs +++ b/src/System.CommandLine.Tests/CompletionContextTests.cs @@ -64,7 +64,7 @@ public void CommandLineText_is_unavailable_when_string_array_is_parsed() } }; - var parseResult = command.Parse(new[] { "verb", "-x", "123" }); + var parseResult = command.Parse(["verb", "-x", "123"]); parseResult.GetCompletionContext() .Should() @@ -137,7 +137,7 @@ public void When_position_is_unspecified_in_array_command_line_and_final_token_i new Option("--option2") }; - string textToMatch = command.Parse(new[] { "the-command", "opt" }) + string textToMatch = command.Parse(["the-command", "opt"]) .GetCompletionContext() .WordToComplete; @@ -153,7 +153,7 @@ public void When_position_is_unspecified_in_array_command_line_and_final_token_m new Option("--option2") }; - string textToMatch = command.Parse(new[] { "the-command" }) + string textToMatch = command.Parse(["the-command"]) .GetCompletionContext() .WordToComplete; @@ -169,7 +169,7 @@ public void When_position_is_unspecified_in_array_command_line_and_final_token_m new Option("--option2") }; - string textToMatch = command.Parse(new[] { "the-command", "--option1" }) + string textToMatch = command.Parse(["the-command", "--option1"]) .GetCompletionContext() .WordToComplete; @@ -189,7 +189,7 @@ public void When_position_is_unspecified_in_array_command_line_and_final_token_m new Argument("arg") }; - string textToMatch = command.Parse(new[] { "the-command", "--option1", "a" }) + string textToMatch = command.Parse(["the-command", "--option1", "a"]) .GetCompletionContext() .WordToComplete; diff --git a/src/System.CommandLine.Tests/CompletionTests.cs b/src/System.CommandLine.Tests/CompletionTests.cs index 84d931f863..1f2aeaa581 100644 --- a/src/System.CommandLine.Tests/CompletionTests.cs +++ b/src/System.CommandLine.Tests/CompletionTests.cs @@ -313,7 +313,7 @@ public void When_a_subcommand_has_been_specified_then_its_sibling_commands_will_ result.GetCompletions() .Select(item => item.Label) .Should() - .NotContain(new[]{"apple", "banana", "cherry"}); + .NotContain(["apple", "banana", "cherry"]); } [Fact] @@ -343,7 +343,7 @@ public void When_a_subcommand_has_been_specified_then_its_sibling_commands_alias result.GetCompletions() .Select(item => item.Label) .Should() - .NotContain(new[] { "apl", "bnn" }); + .NotContain(["apl", "bnn"]); } [Fact] // https://github.com/dotnet/command-line-api/issues/1494 @@ -671,7 +671,7 @@ public void Command_argument_completions_can_be_provided_using_a_delegate() public void Option_argument_completions_can_be_provided_using_a_delegate() { var option = new Option("-x"); - option.CompletionSources.Add(_ => new[] { "vegetable", "mineral", "animal" }); + option.CompletionSources.Add(_ => ["vegetable", "mineral", "animal"]); var command = new Command("the-command") { @@ -806,7 +806,7 @@ public void When_parsing_from_array_if_the_proximate_option_is_completed_then_co new Option("--langVersion") }; var configuration = new CommandLineConfiguration(command); - var completions = command.Parse(new[]{"--framework","net8.0","--l"}, configuration).GetCompletions(); + var completions = command.Parse(["--framework","net8.0","--l"], configuration).GetCompletions(); completions.Select(item => item.Label) .Should() diff --git a/src/System.CommandLine.Tests/CustomParsingTests.cs b/src/System.CommandLine.Tests/CustomParsingTests.cs index fe706a04cb..24c97d70e3 100644 --- a/src/System.CommandLine.Tests/CustomParsingTests.cs +++ b/src/System.CommandLine.Tests/CustomParsingTests.cs @@ -171,7 +171,7 @@ public void custom_parsing_of_sequence_value_from_an_argument_with_one_token() new RootCommand { argument }.Parse("1,2,3") .GetValue(argument) .Should() - .BeEquivalentTo(new[] { 1, 2, 3 }); + .BeEquivalentTo([1, 2, 3]); } [Fact] @@ -185,7 +185,7 @@ public void custom_parsing_of_sequence_value_from_an_argument_with_multiple_toke new RootCommand { argument }.Parse("1 2 3") .GetValue(argument) .Should() - .BeEquivalentTo(new[] { 1, 2, 3 }); + .BeEquivalentTo([1, 2, 3]); } [Fact] @@ -631,12 +631,12 @@ public void Custom_parser_can_pass_on_remaining_tokens(string commandLine) { result.OnlyTake(3); - return new[] - { + return + [ int.Parse(result.Tokens[0].Value), int.Parse(result.Tokens[1].Value), int.Parse(result.Tokens[2].Value) - }; + ]; } }; var argument2 = new Argument("two") @@ -655,13 +655,13 @@ public void Custom_parser_can_pass_on_remaining_tokens(string commandLine) parseResult.GetResult(argument1) .GetValueOrDefault() .Should() - .BeEquivalentTo(new[] { 1, 2, 3 }, + .BeEquivalentTo([1, 2, 3], options => options.WithStrictOrdering()); parseResult.GetResult(argument2) .GetValueOrDefault() .Should() - .BeEquivalentTo(new[] { 4, 5, 6, 7, 8 }, + .BeEquivalentTo([4, 5, 6, 7, 8], options => options.WithStrictOrdering()); } @@ -698,15 +698,15 @@ public void When_tokens_are_passed_on_by_custom_parser_on_last_argument_then_the { result.OnlyTake(3); - return new[] - { + return + [ int.Parse(result.Tokens[0].Value), int.Parse(result.Tokens[1].Value), int.Parse(result.Tokens[2].Value) - }; + ]; } }; - + var command = new RootCommand { argument1 @@ -716,7 +716,7 @@ public void When_tokens_are_passed_on_by_custom_parser_on_last_argument_then_the parseResult.UnmatchedTokens .Should() - .BeEquivalentTo(new[] { "4", "5", "6", "7", "8" }, + .BeEquivalentTo(["4", "5", "6", "7", "8"], options => options.WithStrictOrdering()); } @@ -729,12 +729,12 @@ public void When_custom_parser_passes_on_tokens_the_argument_result_tokens_refle { result.OnlyTake(3); - return new[] - { + return + [ int.Parse(result.Tokens[0].Value), int.Parse(result.Tokens[1].Value), int.Parse(result.Tokens[2].Value) - }; + ]; } }; var argument2 = new Argument("two") @@ -753,14 +753,14 @@ public void When_custom_parser_passes_on_tokens_the_argument_result_tokens_refle .Tokens .Select(t => t.Value) .Should() - .BeEquivalentTo(new[] { "1", "2", "3" }, + .BeEquivalentTo(["1", "2", "3"], options => options.WithStrictOrdering()); parseResult.GetResult(argument2) .Tokens .Select(t => t.Value) .Should() - .BeEquivalentTo(new[] { "4", "5", "6", "7", "8" }, + .BeEquivalentTo(["4", "5", "6", "7", "8"], options => options.WithStrictOrdering()); } @@ -889,7 +889,7 @@ public void OnlyTake_can_pass_on_all_tokens_from_a_single_arity_argument_to_anot CustomParser = ctx => { ctx.OnlyTake(3); - return new[] { "1", "2", "3" }; + return ["1", "2", "3"]; }, Arity = ArgumentArity.ZeroOrMore }; diff --git a/src/System.CommandLine.Tests/GetValueByNameParserTests.cs b/src/System.CommandLine.Tests/GetValueByNameParserTests.cs index b787337c16..9ddeea2b0d 100644 --- a/src/System.CommandLine.Tests/GetValueByNameParserTests.cs +++ b/src/System.CommandLine.Tests/GetValueByNameParserTests.cs @@ -307,7 +307,7 @@ public void Array_of_T_can_be_cast_to_IEnumerable_of_T() ParseResult parseResult = command.Parse("1 2 3"); - parseResult.GetValue>("name").Should().BeEquivalentTo(new int[] { 1, 2, 3 }); + parseResult.GetValue>("name").Should().BeEquivalentTo([1, 2, 3]); } [Fact] diff --git a/src/System.CommandLine.Tests/Help/HelpBuilderTests.Customization.cs b/src/System.CommandLine.Tests/Help/HelpBuilderTests.Customization.cs index 22cced02a0..ff809868be 100644 --- a/src/System.CommandLine.Tests/Help/HelpBuilderTests.Customization.cs +++ b/src/System.CommandLine.Tests/Help/HelpBuilderTests.Customization.cs @@ -524,7 +524,7 @@ public void Help_customized_sections_can_be_wrapped() IEnumerable> CustomLayout(HelpContext _) { - yield return ctx => { ctx.HelpBuilder.WriteColumns(new[] { new TwoColumnHelpRow("12345678", "1234567890") }, ctx); return true; }; + yield return ctx => { ctx.HelpBuilder.WriteColumns([new TwoColumnHelpRow("12345678", "1234567890")], ctx); return true; }; } } diff --git a/src/System.CommandLine.Tests/Help/HelpBuilderTests.cs b/src/System.CommandLine.Tests/Help/HelpBuilderTests.cs index 4a735a4aad..8855f72cf2 100644 --- a/src/System.CommandLine.Tests/Help/HelpBuilderTests.cs +++ b/src/System.CommandLine.Tests/Help/HelpBuilderTests.cs @@ -922,7 +922,7 @@ public void Command_arguments_with_default_values_that_are_enumerable_display_pi { new Argument>("filter-size") { - DefaultValueFactory = (_) => new List() { 0, 2, 4 } + DefaultValueFactory = (_) => [0, 2, 4] } }; @@ -1053,7 +1053,7 @@ public void Options_section_aligns_options_on_new_lines() _helpBuilder.Write(command, _console); var help = _console.ToString(); - var lines = help.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); + var lines = help.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries); var optionA = lines.Last(line => line.Contains("-a")); var optionB = lines.Last(line => line.Contains("-b")); @@ -1290,7 +1290,7 @@ public void Options_help_preserves_the_order_options_are_added_the_the_parent_co _helpBuilder.Write(command, _console); var help = _console .ToString() - .Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries) + .Split(['\n', '\r'], StringSplitOptions.RemoveEmptyEntries) .Select(l => l.Trim()); help.Should().ContainInOrder( @@ -1341,7 +1341,7 @@ public void Option_arguments_with_default_values_that_are_enumerable_display_pip { new Option>("--filter-size") { - DefaultValueFactory = (_) => new List { 0, 2, 4 } + DefaultValueFactory = (_) => [0, 2, 4] } }; @@ -1360,7 +1360,7 @@ public void Option_arguments_with_default_values_that_are_array_display_pipe_del { new Option("--prefixes") { - DefaultValueFactory = (_) => new[]{ "^(TODO|BUG)", "^HACK" } + DefaultValueFactory = (_) => ["^(TODO|BUG)", "^HACK"] } }; diff --git a/src/System.CommandLine.Tests/Invocation/CancelOnProcessTerminationTests.cs b/src/System.CommandLine.Tests/Invocation/CancelOnProcessTerminationTests.cs index 656bba1424..4634315258 100644 --- a/src/System.CommandLine.Tests/Invocation/CancelOnProcessTerminationTests.cs +++ b/src/System.CommandLine.Tests/Invocation/CancelOnProcessTerminationTests.cs @@ -35,7 +35,7 @@ public async Task CancellableHandler_is_cancelled_on_process_termination() // Same for macOS, where RemoteExecutor does not support getting application arguments. if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { - await StartKillAndVerify(new[] { "--infiniteDelay", "false" }, Signals.SIGINT, GracefulExitCode); + await StartKillAndVerify(["--infiniteDelay", "false"], Signals.SIGINT, GracefulExitCode); } } @@ -44,7 +44,7 @@ public async Task NonCancellableHandler_is_interrupted_on_process_termination() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { - await StartKillAndVerify(new[] { "--infiniteDelay", "true" }, Signals.SIGTERM, SIGTERM_EXIT_CODE); + await StartKillAndVerify(["--infiniteDelay", "true"], Signals.SIGTERM, SIGTERM_EXIT_CODE); } } diff --git a/src/System.CommandLine.Tests/OptionTests.cs b/src/System.CommandLine.Tests/OptionTests.cs index 804af82386..79bbeb88ed 100644 --- a/src/System.CommandLine.Tests/OptionTests.cs +++ b/src/System.CommandLine.Tests/OptionTests.cs @@ -41,7 +41,7 @@ public void When_an_option_has_only_name_then_it_has_no_aliases() [Fact] public void When_an_option_has_several_aliases_then_they_do_not_affect_its_name() { - var option = new Option(name: "m", aliases: new[] { "longer" }); + var option = new Option(name: "m", aliases: ["longer"]); option.Name.Should().Be("m"); } diff --git a/src/System.CommandLine.Tests/ParserTests.MultipleArguments.cs b/src/System.CommandLine.Tests/ParserTests.MultipleArguments.cs index 4f90bb8ea8..6bd7671850 100644 --- a/src/System.CommandLine.Tests/ParserTests.MultipleArguments.cs +++ b/src/System.CommandLine.Tests/ParserTests.MultipleArguments.cs @@ -173,12 +173,12 @@ public void Tokens_that_cannot_be_converted_by_multiple_arity_argument_flow_to_n result.GetValue(ints) .Should() - .BeEquivalentTo(new[] { 1, 2, 3 }, + .BeEquivalentTo([1, 2, 3], options => options.WithStrictOrdering()); result.GetValue(strings) .Should() - .BeEquivalentTo(new[] { "one", "two" }, + .BeEquivalentTo(["one", "two"], options => options.WithStrictOrdering()); } @@ -200,7 +200,7 @@ public void Tokens_that_cannot_be_converted_by_multiple_arity_argument_flow_to_n result.GetValue(ints) .Should() - .BeEquivalentTo(new[] { 1, 2, 3 }, + .BeEquivalentTo([1, 2, 3], options => options.WithStrictOrdering()); result.GetValue(strings) @@ -302,7 +302,7 @@ public void When_there_are_not_enough_tokens_for_all_arguments_then_the_correct_ .Errors .Count .Should() - .Be(4 - providedArgs.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Length); + .Be(4 - providedArgs.Split([' '], StringSplitOptions.RemoveEmptyEntries).Length); } } } diff --git a/src/System.CommandLine.Tests/ParserTests.cs b/src/System.CommandLine.Tests/ParserTests.cs index 410c67bc82..070bb314c9 100644 --- a/src/System.CommandLine.Tests/ParserTests.cs +++ b/src/System.CommandLine.Tests/ParserTests.cs @@ -751,11 +751,13 @@ public void Subsequent_occurrences_of_tokens_matching_command_names_are_parsed_a } }; - ParseResult result = command.Parse(new[] { "the-command", - "complete", - "--position", - "7", - "the-command" }); + ParseResult result = command.Parse([ + "the-command", + "complete", + "--position", + "7", + "the-command" + ]); CommandResult completeResult = result.CommandResult; @@ -1076,7 +1078,7 @@ public void When_an_option_argument_is_enclosed_in_double_quotes_its_value_retai { var option = new Option("-x"); - var parseResult = new RootCommand { option }.Parse(new[] { arg1, arg2 }); + var parseResult = new RootCommand { option }.Parse([arg1, arg2]); parseResult .GetResult(option) @@ -1427,10 +1429,11 @@ public void Command_argument_arity_can_be_a_fixed_value_greater_than_1() .CommandResult .Tokens .Should() - .BeEquivalentTo(new [] { + .BeEquivalentTo([ new Token("1", TokenType.Argument, argument), new Token("2", TokenType.Argument, argument), - new Token("3", TokenType.Argument, argument)}); + new Token("3", TokenType.Argument, argument) + ]); } [Fact] @@ -1449,20 +1452,22 @@ public void Command_argument_arity_can_be_a_range_with_a_lower_bound_greater_tha .CommandResult .Tokens .Should() - .BeEquivalentTo(new [] { + .BeEquivalentTo([ new Token("1", TokenType.Argument, argument), new Token("2", TokenType.Argument, argument), - new Token("3", TokenType.Argument, argument)}); + new Token("3", TokenType.Argument, argument) + ]); command.Parse("1 2 3 4 5") .CommandResult .Tokens .Should() - .BeEquivalentTo(new [] { + .BeEquivalentTo([ new Token("1", TokenType.Argument, argument), new Token("2", TokenType.Argument, argument), new Token("3", TokenType.Argument, argument), new Token("4", TokenType.Argument, argument), - new Token("5", TokenType.Argument, argument)}); + new Token("5", TokenType.Argument, argument) + ]); } [Fact] @@ -1518,10 +1523,11 @@ public void Option_argument_arity_can_be_a_fixed_value_greater_than_1() .GetResult(option) .Tokens .Should() - .BeEquivalentTo(new [] { + .BeEquivalentTo([ new Token("1", TokenType.Argument, default), new Token("2", TokenType.Argument, default), - new Token("3", TokenType.Argument, default)}); + new Token("3", TokenType.Argument, default) + ]); } [Fact] @@ -1538,27 +1544,29 @@ public void Option_argument_arity_can_be_a_range_with_a_lower_bound_greater_than .GetResult(option) .Tokens .Should() - .BeEquivalentTo(new [] { + .BeEquivalentTo([ new Token("1", TokenType.Argument, default), new Token("2", TokenType.Argument, default), - new Token("3", TokenType.Argument, default)}); + new Token("3", TokenType.Argument, default) + ]); command.Parse("-x 1 -x 2 -x 3 -x 4 -x 5") .GetResult(option) .Tokens .Should() - .BeEquivalentTo(new [] { + .BeEquivalentTo([ new Token("1", TokenType.Argument, default), new Token("2", TokenType.Argument, default), new Token("3", TokenType.Argument, default), new Token("4", TokenType.Argument, default), - new Token("5", TokenType.Argument, default)}); + new Token("5", TokenType.Argument, default) + ]); } [Fact] public void When_option_arguments_are_fewer_than_minimum_arity_then_an_error_is_returned() { - var option = new Option("-x") - { + var option = new Option("-x") + { Arity = new ArgumentArity(2, 3) }; @@ -1646,7 +1654,7 @@ public void Parsed_value_of_empty_string_arg_is_an_empty_string(string arg1, str option }; - var result = rootCommand.Parse(new[] { arg1, arg2 }); + var result = rootCommand.Parse([arg1, arg2]); GetValue(result, option).Should().BeEmpty(); } diff --git a/src/System.CommandLine.Tests/ParsingValidationTests.cs b/src/System.CommandLine.Tests/ParsingValidationTests.cs index 097f6094b1..0dc804a8ca 100644 --- a/src/System.CommandLine.Tests/ParsingValidationTests.cs +++ b/src/System.CommandLine.Tests/ParsingValidationTests.cs @@ -65,7 +65,7 @@ public void When_FromAmong_is_used_then_the_OptionResult_ErrorMessage_is_set() error .Message .Should() - .Be(LocalizationResources.UnrecognizedArgument("c", new []{ "a", "b"})); + .Be(LocalizationResources.UnrecognizedArgument("c", ["a", "b"])); error .SymbolResult .Should() @@ -88,7 +88,7 @@ public void When_FromAmong_is_used_then_the_ArgumentResult_ErrorMessage_is_set() error .Message .Should() - .Be(LocalizationResources.UnrecognizedArgument("c", new []{ "a", "b"})); + .Be(LocalizationResources.UnrecognizedArgument("c", ["a", "b"])); error .SymbolResult .Should() @@ -148,7 +148,7 @@ public void When_FromAmong_is_used_multiple_times_only_the_most_recently_provide .Which .Message .Should() - .Be(LocalizationResources.UnrecognizedArgument("key2", new[] { "key1" })); + .Be(LocalizationResources.UnrecognizedArgument("key2", ["key1"])); argument.AcceptOnlyFromAmong("key2"); @@ -174,7 +174,7 @@ public void When_FromAmong_is_used_for_multiple_arguments_and_invalid_input_is_p .Which .Message .Should() - .Be(LocalizationResources.UnrecognizedArgument("not-value1", new[] { "value1", "value2" })); + .Be(LocalizationResources.UnrecognizedArgument("not-value1", ["value1", "value2"])); } [Fact] @@ -197,12 +197,12 @@ public void When_FromAmong_is_used_and_multiple_invalid_inputs_are_provided_the_ result.Errors[0] .Message .Should() - .Be(LocalizationResources.UnrecognizedArgument("c1", new[] { "author", "language", "tags", "type" })); + .Be(LocalizationResources.UnrecognizedArgument("c1", ["author", "language", "tags", "type"])); result.Errors[1] .Message .Should() - .Be(LocalizationResources.UnrecognizedArgument("c2", new[] { "author", "language", "tags", "type" })); + .Be(LocalizationResources.UnrecognizedArgument("c2", ["author", "language", "tags", "type"])); } [Fact] diff --git a/src/System.CommandLine.Tests/ResponseFileTests.cs b/src/System.CommandLine.Tests/ResponseFileTests.cs index 5404fdee22..42735999cf 100644 --- a/src/System.CommandLine.Tests/ResponseFileTests.cs +++ b/src/System.CommandLine.Tests/ResponseFileTests.cs @@ -13,7 +13,7 @@ namespace System.CommandLine.Tests { public class ResponseFileTests : IDisposable { - private readonly List _responseFiles = new(); + private readonly List _responseFiles = []; public void Dispose() { diff --git a/src/System.CommandLine.Tests/SuggestDirectiveTests.cs b/src/System.CommandLine.Tests/SuggestDirectiveTests.cs index ec1bb7209e..74f8f95e7b 100644 --- a/src/System.CommandLine.Tests/SuggestDirectiveTests.cs +++ b/src/System.CommandLine.Tests/SuggestDirectiveTests.cs @@ -25,7 +25,7 @@ public SuggestDirectiveTests() _fruitOption.CompletionSources.Add("apple", "banana", "cherry"); _vegetableOption = new Option("--vegetable"); - _vegetableOption.CompletionSources.Add(_ => new[] { "asparagus", "broccoli", "carrot" }); + _vegetableOption.CompletionSources.Add(_ => ["asparagus", "broccoli", "carrot"]); _eatCommand = new Command("eat") { diff --git a/src/System.CommandLine.Tests/TokenReplacementTests.cs b/src/System.CommandLine.Tests/TokenReplacementTests.cs index c96af9b0c2..719c286f4a 100644 --- a/src/System.CommandLine.Tests/TokenReplacementTests.cs +++ b/src/System.CommandLine.Tests/TokenReplacementTests.cs @@ -45,7 +45,7 @@ public void Token_replacer_can_expand_argument_values() { ResponseFileTokenReplacer = (string tokenToReplace, out IReadOnlyList tokens, out string message) => { - tokens = new[] { "123" }; + tokens = ["123"]; message = null; return true; } @@ -69,7 +69,7 @@ public void Custom_token_replacer_can_expand_option_argument_values() { ResponseFileTokenReplacer = (string tokenToReplace, out IReadOnlyList tokens, out string message) => { - tokens = new[] { "123" }; + tokens = ["123"]; message = null; return true; } @@ -93,7 +93,7 @@ public void Custom_token_replacer_can_expand_subcommands_and_options_and_argumen { ResponseFileTokenReplacer = (string tokenToReplace, out IReadOnlyList tokens, out string message) => { - tokens = new[] { "subcommand", "-x", "123" }; + tokens = ["subcommand", "-x", "123"]; message = null; return true; } @@ -117,7 +117,7 @@ public void Expanded_tokens_containing_whitespace_are_parsed_as_single_tokens() { ResponseFileTokenReplacer = (string tokenToReplace, out IReadOnlyList tokens, out string message) => { - tokens = new[] { "one two three" }; + tokens = ["one two three"]; message = null; return true; } diff --git a/src/System.CommandLine.Tests/Utility/RemoteExecutor.cs b/src/System.CommandLine.Tests/Utility/RemoteExecutor.cs index 23f7500f27..45c8bd1848 100644 --- a/src/System.CommandLine.Tests/Utility/RemoteExecutor.cs +++ b/src/System.CommandLine.Tests/Utility/RemoteExecutor.cs @@ -43,7 +43,7 @@ public static int Main(string[] args) instance = Activator.CreateInstance(type); } - object result = methodInfo.Invoke(instance, new object[] { methodArguments }); + object result = methodInfo.Invoke(instance, [methodArguments]); if (result is Task task) { exitCode = task.GetAwaiter().GetResult(); @@ -119,8 +119,10 @@ private static RemoteExecution Execute(MethodInfo methodInfo, string[] args, Pro psi.FileName = dotnetExecutable; var argumentList = new List(); - argumentList.AddRange(new[] { "exec", "--runtimeconfig", runtimeConfig, "--depsfile", depsFile, thisAssembly, - className, methodName, exceptionFile }); + argumentList.AddRange([ + "exec", "--runtimeconfig", runtimeConfig, "--depsfile", depsFile, thisAssembly, + className, methodName, exceptionFile + ]); if (args != null) { argumentList.AddRange(args); @@ -159,7 +161,7 @@ private static string[] GetApplicationArguments() if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { - s_arguments = File.ReadAllText($"/proc/{Diagnostics.Process.GetCurrentProcess().Id}/cmdline").Split(new[] { '\0' }); + s_arguments = File.ReadAllText($"/proc/{Diagnostics.Process.GetCurrentProcess().Id}/cmdline").Split(['\0']); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { diff --git a/src/System.CommandLine/Argument.cs b/src/System.CommandLine/Argument.cs index f278477afe..3cc9a6a09e 100644 --- a/src/System.CommandLine/Argument.cs +++ b/src/System.CommandLine/Argument.cs @@ -65,11 +65,11 @@ public List>> CompletionSour { _completionSources = new () { - static _ => new CompletionItem[] - { + static _ => + [ new(bool.TrueString), new(bool.FalseString) - } + ] }; } else if (!valueType.IsPrimitive && (valueType.IsEnum || (valueType.TryGetNullableType(out valueType) && valueType.IsEnum))) diff --git a/src/System.CommandLine/Help/HelpBuilder.Default.cs b/src/System.CommandLine/Help/HelpBuilder.Default.cs index 33e53c0da0..6aca3bc9e8 100644 --- a/src/System.CommandLine/Help/HelpBuilder.Default.cs +++ b/src/System.CommandLine/Help/HelpBuilder.Default.cs @@ -118,7 +118,7 @@ public static string GetOptionUsageLabel(Option symbol) private static string GetIdentifierSymbolUsageLabel(Symbol symbol, ICollection? aliasSet) { var aliases = aliasSet is null - ? new[] { symbol.Name } + ? [symbol.Name] : new[] { symbol.Name }.Concat(aliasSet) .Select(r => r.SplitPrefix()) .OrderBy(r => r.Prefix, StringComparer.OrdinalIgnoreCase) @@ -213,7 +213,7 @@ public static Func SubcommandsSection() => public static Func OptionsSection() => ctx => { - List optionRows = new(); + List optionRows = []; bool addedHelpOption = false; foreach (Option option in ctx.Command.Options) { diff --git a/src/System.CommandLine/Option.cs b/src/System.CommandLine/Option.cs index c9d81062e7..931cbad4f4 100644 --- a/src/System.CommandLine/Option.cs +++ b/src/System.CommandLine/Option.cs @@ -124,7 +124,7 @@ public override IEnumerable GetCompletions(CompletionContext con { if (completion.Label.ContainsCaseInsensitive(context.WordToComplete)) { - (completions ??= new List()).Add(completion); + (completions ??= []).Add(completion); } }