Skip to content

Option actions are only invoked if the parent Command has an action #2771

@jalfd

Description

@jalfd

If you set an Action on an Option object, it is not automatically invoked.
It is only invoked if the Command object also has an action.

The following reproduces the problem, as the first test fails, but the second one passes:

using System.CommandLine;
using System.CommandLine.Invocation;

namespace CommandLineTest
{
    [TestClass]
    public sealed class CommandLineTests
    {
        [TestMethod]
        public void OptionActionIsInvokedWithoutCommandAction()
        {
            bool actionWasInvoked = false;
            RootCommand root = new("CommandLine Test");

            Option<bool> option = new("--arg");
            option.Action = new CustomAction(_ =>
            {
                actionWasInvoked = true;
                return 0;
            });
            root.Options.Add(option);

            ParseResult parsedArgs = root.Parse(["--arg"]);
            int result = parsedArgs.Invoke();

            Assert.IsTrue(actionWasInvoked);
        }

        [TestMethod]
        public void OptionActionIsInvokedWithCommandAction()
        {
            bool actionWasInvoked = false;
            RootCommand root = new("CommandLine Test");

            Option<bool> option = new("--arg");
            option.Action = new CustomAction(_ =>
            {
                actionWasInvoked = true;
                return 0;
            });
            root.Options.Add(option);
            root.SetAction(r => { });

            ParseResult parsedArgs = root.Parse(["--arg"]);
            int result = parsedArgs.Invoke();

            Assert.IsTrue(actionWasInvoked);
        }

        class CustomAction : SynchronousCommandLineAction
        {
            private readonly Func<ParseResult, int> _callback;

            internal CustomAction(Func<ParseResult, int> callback) => _callback = callback;
            public override int Invoke(ParseResult parseResult) => _callback(parseResult);
            public override bool Terminating => false;
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions