Skip to content
Draft
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
22 changes: 22 additions & 0 deletions src/System.CommandLine.Tests/OptionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<bool>("--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();
}
}
}
16 changes: 15 additions & 1 deletion src/System.CommandLine/Parsing/ParseOperation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,7 @@ void ParseDirective()
}

private void AddPreAction(CommandLineAction action)
{
{
if (_preActions is null)
{
_preActions = new();
Expand All @@ -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)
Expand Down Expand Up @@ -435,6 +447,8 @@ private void ValidateAndAddDefaultResults()
}
}
}

AddPreActionsForImplicitOptions();
}
}
}