Igorgy
Igorgy

Reputation: 170

.net core CommandOption understanding

I have a simple .net core console application. I am trying to parse command options:

static void Main(string[] args)
{
  CommandLineApplication app = new CommandLineApplication(throwOnUnexpectedArg: true);

  app.Command("client", c =>
            {
                CommandArgument argument = c.Argument("action", "Client action");
                CommandOption first = c.Option("--f <NAME>", "Method argument.", CommandOptionType.MultipleValue);
                CommandOption second = c.Option("--s <NAME>", "Method argument.", CommandOptionType.MultipleValue);

                c.OnExecute(() =>
                {
                    switch (argument.Values.Last())
                    {
                        case "action":
                            {
                                bool hasFirstArg = first.HasValue();
                                var fVals = first.Values;
                                var sVals = second.Values;

                                break;
                            }
                        default:
                            throw new ArgumentException("Unrecognized client action");
                    }

                    return 0;

                });
            });


    app.Execute("client", "action", "--f: foo"); // command1
    // 'first' option values = {"foo"}, 'second' option values = {}
    app.Execute("client", "action", "--s: bar"); // command2
    // 'first' option values = {"foo"}, 'second' option values = {"bar"}
}

As you see command1 change only 'first' option, and command2 change only 'second' option ('first' collected after command1). But while command2 execute, i cant determine correct 'first' option value because CommandOption values it is a history of this option. I cant just take last value. Its previous command option.
How can i get current command options in that case?

Upvotes: 1

Views: 804

Answers (1)

Eroshkevich.E
Eroshkevich.E

Reputation: 11

I did it like this:

app.Command("run", c =>
        {
            var isLoopOption = c.Option(
                "-l | --loop",
                "Loop execution",
                CommandOptionType.NoValue);

            c.OnExecute(() =>
            {
                _isLoop = isLoopOption.HasValue()

                executeAction();

                isLoopOption.Values.Clear();
                return 0;
            });
        });

It's A little ugly, but it works :-8

Upvotes: 1

Related Questions