diff --git a/src/System.CommandLine.Tests/OptionTests.cs b/src/System.CommandLine.Tests/OptionTests.cs index f898c25024..10ec1630d8 100644 --- a/src/System.CommandLine.Tests/OptionTests.cs +++ b/src/System.CommandLine.Tests/OptionTests.cs @@ -531,5 +531,27 @@ public void Default_value_is_used_when_option_with_ZeroOrOne_arity_is_parsed_wit parseResult.GetValue(option).Should().Be(42); } + + [Fact] // https://github.com/dotnet/command-line-api/issues/2621 + public void Option_with_default_value_has_Action_added_to_PreActions_when_not_specified_but_has_default() + { + var preactionWasInvoked = false; + var option = new Option("--quiet") + { + DefaultValueFactory = _ => true, + Action = new SynchronousTestAction(_ => preactionWasInvoked = true, terminating: false) + }; + + var rootCommand = new RootCommand + { + option + }; + rootCommand.SetAction(_ => { }); + + var parseResult = rootCommand.Parse(""); + parseResult.Invoke(); + + preactionWasInvoked.Should().BeTrue(); + } } } diff --git a/src/System.CommandLine/Parsing/ParseOperation.cs b/src/System.CommandLine/Parsing/ParseOperation.cs index 0ae9c4bcf3..2d72376814 100644 --- a/src/System.CommandLine/Parsing/ParseOperation.cs +++ b/src/System.CommandLine/Parsing/ParseOperation.cs @@ -333,7 +333,7 @@ void ParseDirective() } private void AddPreAction(CommandLineAction action) - { + { if (_preActions is null) { _preActions = new(); @@ -342,6 +342,18 @@ private void AddPreAction(CommandLineAction action) _preActions.Add(action); } + private void AddPreActionsForImplicitOptions() + { + foreach (var kvp in _symbolResultTree) + { + if (kvp is { Key: Option { Action: { Terminating: false } action }, Value: OptionResult { Implicit: true } } && + _primaryAction != action) + { + AddPreAction(action); + } + } + } + private void AddCurrentTokenToUnmatched() { if (CurrentToken.Type == TokenType.DoubleDash) @@ -435,6 +447,8 @@ private void ValidateAndAddDefaultResults() } } } + + AddPreActionsForImplicitOptions(); } } } \ No newline at end of file