Skip to content

Commit bb817c6

Browse files
author
Jon Sequeira
committed
unspecified option with preaction and default value has preaction invoked
1 parent c32f786 commit bb817c6

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

src/System.CommandLine.Tests/OptionTests.cs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -531,5 +531,27 @@ public void Default_value_is_used_when_option_with_ZeroOrOne_arity_is_parsed_wit
531531

532532
parseResult.GetValue(option).Should().Be(42);
533533
}
534+
535+
[Fact] // https://github.com/dotnet/command-line-api/issues/2621
536+
public void Option_with_default_value_has_Action_added_to_PreActions_when_not_specified_but_has_default()
537+
{
538+
var actionInvoked = false;
539+
var option = new Option<bool>("--quiet")
540+
{
541+
DefaultValueFactory = _ => true,
542+
Action = new SynchronousTestAction(_ => actionInvoked = true, terminating: false)
543+
};
544+
545+
var rootCommand = new RootCommand
546+
{
547+
option
548+
};
549+
rootCommand.SetAction(_ => { });
550+
551+
var parseResult = rootCommand.Parse("");
552+
parseResult.Invoke();
553+
554+
actionInvoked.Should().BeTrue();
555+
}
534556
}
535557
}

src/System.CommandLine/Parsing/ParseOperation.cs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -342,6 +342,24 @@ private void AddPreAction(CommandLineAction action)
342342
_preActions.Add(action);
343343
}
344344

345+
private void AddActionsForImplicitOptions()
346+
{
347+
// Check for options with default values and actions that were implicitly added
348+
foreach (var kvp in _symbolResultTree)
349+
{
350+
if (kvp.Key is Option { Action: { } action } &&
351+
kvp.Value is OptionResult optionResult &&
352+
optionResult.Implicit)
353+
{
354+
if (!action.Terminating &&
355+
(_primaryAction is null || _primaryAction != action))
356+
{
357+
AddPreAction(action);
358+
}
359+
}
360+
}
361+
}
362+
345363
private void AddCurrentTokenToUnmatched()
346364
{
347365
if (CurrentToken.Type == TokenType.DoubleDash)
@@ -366,6 +384,9 @@ private void ValidateAndAddDefaultResults()
366384
currentResult = currentResult.Parent as CommandResult;
367385
}
368386

387+
// Add actions for options with default values that were not specified on the command line
388+
AddActionsForImplicitOptions();
389+
369390
if (_primaryAction is null)
370391
{
371392
if (_innermostCommandResult is { Command: { Action: null, HasSubcommands: true } })

0 commit comments

Comments
 (0)