Skip to content

ParseResultVisitor.ValidateAndConvertArgumentResults returns incorrect value for missing argument #2292

Closed

Description

@lukewis

I'm trying to understand the purpose of the ParseResultVisitor.ValidateAndConvertArgumentResults method. It seems to be the reason the test case below fails. Could you please help me understand this behavior?

using System.CommandLine.Invocation;

namespace System.CommandLine.Tests
{
    [TestClass]
    public class SystemCommandlineTests
    {
        [TestMethod]
        public void WrongValueForParameter()
        {
            var root = new MyRootCommand();
            var result = root.Parse(new[] { "myapp", "dosomething", "amazing", "today" });
            Assert.AreEqual("amazing", result.GetValueForArgument(MyCommand.Arg1));
            Assert.AreEqual("today", result.GetValueForArgument(MyCommand.Arg2));
            // The following fails.  Retrieving the value for Arg3 actually returns "today" (the value of arg2)
            Assert.IsNull(result.GetValueForArgument(MyCommand.Arg3));

            // If I change my assertion to this, the test passes, but this seems quite unexpected
            // Assert.AreEqual("today", result.GetValueForArgument(MyCommand.Arg3));
        }
    }

    class MyCommand : Command
    {
        public static readonly Argument Arg1 = new Argument<string>();
        public static readonly Argument Arg2 = new Argument<string>();
        public static readonly Argument Arg3 = new Argument<string>();

        public MyCommand() : base("dosomething", "Do something amazing")
        {
            AddArgument(Arg1);
            AddArgument(Arg2);
            AddArgument(Arg3);

            this.SetHandler(Handle);
        }

        private void Handle(InvocationContext context)
        {

        }
    }

    class MyRootCommand : RootCommand
    {
        public MyRootCommand()
        {
            AddCommand(new MyCommand());
        }
    }
}

Below is the relevant snippet from ParseResultVisitor.ValidateAndConvertArgumentResults that seems to be causing the problem. I would link to the code, but I can't find ParseResultVisitor anywhere in this repository.

if (commandArgumentResultCount == i)
{
		ArgumentResult argumentResult = new ArgumentResult(arguments[i], _innermostCommandResult);
		ArgumentResult argumentResult2 = _argumentResults[i - 1];
		int? num = _innermostCommandResult?.Tokens.Count;
		for (int j = argumentResult2.Tokens.Count; j < num; j++)
		{
			if (argumentResult.IsArgumentLimitReached)
			{
				break;
			}
			if (_innermostCommandResult != null)
			{
				argumentResult.AddToken(_innermostCommandResult!.Tokens[j]);
			}
		}
		_argumentResults.Add(argumentResult);
		if (argumentResult2.Parent is CommandResult)
		{
			AddToResult(argumentResult);
		}
		_symbolResults.TryAdd(argumentResult.Symbol, argumentResult);
}

Activity

  1. elgonzo commented on Nov 15, 2023

    @elgonzo
    Contributor

    Why is there a "myapp" string in your string array passed to the Parse method? Think about the string array being passed to the Parse method being like the args array passed to the main method of a program -- it should contain the CLI arguments as if you called the program from the commandline/shell. It should not contain the program/executable name itself.


    As for result.GetValueForArgument(MyCommand.Arg3) returning "today", this appears to be indeed a bug. However, note that the API surface of the library has significantly changed since the version you are using had been released. With the latest available build 2.0.0-beta4.23407.1 from August 7th 2023, the issue does not seem to occur anymore. When using the newest System.CommandLine library version, your test code would need to be adapted to the new APIs, e.g.:

    Assert.AreEqual("amazing", result.GetValue(MyCommand.Arg1));
    Assert.AreEqual("today", result.GetValue(MyCommand.Arg2));
    Assert.IsNull(result.GetValue(MyCommand.Arg3));
    
    class MyCommand : CliCommand
    {
        public static readonly CliArgument<string> Arg1 = new("1st");
        public static readonly CliArgument<string> Arg2 = new("2nd");
        public static readonly CliArgument<string?> Arg3 = new("3rd") { Arity = ArgumentArity.ZeroOrOne };
    
        public MyCommand() : base("dosomething", "Do something amazing")
        {
            Add(Arg1);
            Add(Arg2);
            Add(Arg3);
    
            this.SetAction(Handle);
        }
    
        private void Handle(ParseResult parseResult)
        {
    
        }
    }
    
    class MyRootCommand : CliRootCommand
    {
        public MyRootCommand()
        {
            Add(new MyCommand());
        }
    }
  2. lukewis commented on Nov 15, 2023

    @lukewis
    Author

    Wow! Thank you so much for taking the time to provide such a detailed answer!! I need to absorb it a bit and try out what you suggest tomorrow morning. For some reason I thought that Program.Main() args included the exe name. Not sure why I thought that. Perhaps it depends on how it's launched? dotnet run vs direct execution with an AOT app? Either way, thank you again for your help and I will close out this ticket as soon as I try out the things you suggest.

    I'm quite excited about the Arity property (although I find that name a bit obscure), I hadn't come across that before, but it looks a lot like what I need.

    Of interest, I'm using this methodology along with Spectre.Console to provide automatic prompts for missing arguments. That's not something that's anywhere on the roadmap for this team is it? Just making sure I'm not duplicating effort here.

  3. baronfel commented on Nov 15, 2023

    @baronfel
    Member

    Of interest, I'm using this methodology along with Spectre.Console to provide automatic prompts for missing arguments. That's not something that's anywhere on the roadmap for this team is it? Just making sure I'm not duplicating effort here.

    I want this so badly for the .NET CLI - we started down this path in a limited way for the template engine in dotnet new, and we took the approach of using a middleware to do intermediate parsing and re-parsing of arguments as the user filled them in. We likely won't continue that effort anytime soon, but if you want to take a look at some of the guts of it, the code is here.

  4. lukewis commented on Nov 15, 2023

    @lukewis
    Author
  5. lukewis commented on Nov 16, 2023

    @lukewis
    Author

    @elgonzo an update from the things I tried

    1. Removing the "myapp" argument didn't seem to have any effect on the parsing (although what you said makes sense.. The third argument still contains a value of "today". I also verified that the exe does not appear in the argument list on startup. I have no idea why I thought that.
    2. I looked for the newer version of the package that you mention (2.0.0-beta4.23407.1) but it doesn't appear to be published to nuget.org. Is there a myget feed or some other source I should be checking?
  6. elgonzo commented on Nov 16, 2023

    @elgonzo
    Contributor

    Removing the "myapp" argument didn't seem to have any effect on the parsing

    Yes, it's unrelated to the issue you observed. It would however lead to System.CommandLine issuing an error message (to the effect of "myapp" being an unknown/unmatched argument) when you try to invoke instead of just parsing.


    but it doesn't appear to be published to nuget.org

    It's available through the daily builds nuget feed mentioned in the readme.md

  7. lukewis commented on Nov 16, 2023

    @lukewis
    Author

    @elgonzo - Thanks again for your help. I can confirm this is resolved in the latest nightly build (apologies for missing that in the README), so I'll close this issue. I look forward to the next "public" release! I'm excited for "Arity", although I'm still hoping for a more "common" name. I've been a software engineer for over 15 years and never once encountered the term Arity until now (maybe that's on me lol, but I suspect others may also be in my boat)

    Brainstorming some ideas......

    var arg = new CliArgument<string> { Multiplicity = ArgumentMultiplicity.ZeroOrOne }
    var arg = new CliArgument<string> { Multiple = ArgumentMultiple.ZeroOrOne }
    var arg = new CliArgument<string> { AllowMultiple = ArgumentMultiple.ZeroOrOne }
    var arg = new CliArgument<string> { ExpectMultiple = ArgumentMultiple.ZeroOrOne }
    var arg = new CliArgument<string> { Number = ArgumentNumber.ZeroOrOne }
    var arg = new CliArgument<string> { Count = ArgumentCount.ZeroOrOne }
    var arg = new CliArgument<string> { Quantity = ArgumentQuantity.ZeroOrOne }
    var arg = new CliArgument<string> { Required= ArgumentRequirement.ZeroOrOne }
    var arg = new CliArgument<string> { Requirement = ArgumentRequirement.ZeroOrOne }
    var arg = new CliArgument<string> { HowMany = ArgumentQuantity.ZeroOrOne }
    
    • Multiplicity is still more obscure than I prefer, but maybe more common than Arity?
    • Number and Count have a strong association to an integer due to the collection types
    • Required tends to imply it's a boolean (although it would be called IsRequired in that case)
    • Requirement feels a little too "broad"
    • I think Quantity might be my "least hated" from above......it still has an association to an integer, but intellisense would help. I actually just realized that NSubstitute uses this verbiage when asserting that a method was called "n" times

    I have to admit I somewhat miss the simplicity of IsRequired. I appreciate the power of Arity, but I wonder if IsRequired might cover 60-70% of use cases?) Is it too confusing to have both? The setter for one would update the other (I don't love side effects, but maybe worth it here?)

    class CliArgument<T>
    {
       bool IsRequired {get; set;} = true;
       Arity? Arity {get; set;} = Arity.ExactlyOne;
    }
    
    arg.IsRequired = false; // Would update arg.Arity to Arity.ZeroOrOne (why not ZeroOrMore you might argue?)
    arg.Arity = Arity.ZeroOrOne; // Would update arg.IsRequired = false
    arg.Arity = Arity.OneOrMore; // Would update arg.IsRequired = true;
    

    You could also say that there is NO interaction between the two properties, but if Arity is set, it will take precedence over IsRequired? Side note - I'm curious as to the value of Arity.Zero......I can't think of a use case

    Anyways.....I'm sure you guys have already been through this thought exercise........just food for thought

  8. elgonzo commented on Nov 16, 2023

    @elgonzo
    Contributor

    I'm excited for "Arity", although I'm still hoping for a more "common" name.

    In case you haven't seen this already, but there is/was a comment thread #2046 which includes a discussion about better alternatives for the admittedly uncommon term "arity".

    I have to admit I somewhat miss the simplicity of IsRequired

    Well, for keeping the "simplicity" of "IsRequired", you propose quite some rules of how IsRequired and Arity are supposed to be related or intertwined. I wouldn't call this "simplicity" :-)

    Do not conflate or equate Arity with "IsRequired". They do not express the same thing. Required (as it is named in the current library version) specifies whether the user is forced to specify some option --foo (with a "required option" being kind of an oxymoron, more appropriately being described as a required named parameter). Arity on the other hand specifies how many values that option --foo accepts, regardless of whether that option is a required option or not.

    And if you take a closer look at the API of the current library version, you'll notice that Required is a property of CliOption's only, because only for them it makes sense. The choices between "providing an option or not providing an option" (Required) versus "providing an option with value(s) or without a value" (Arity) are not equivalent and can be freely combined with regard to options, as options appear by name in the CLI invocation regardless of whether they accept values or not.

    For arguments this does not make sense, as arguments only appear as their values in the CLI invocation, hence why CliArgument only supports Arity and not Required. (And trying to establish Required values true and false as some aliases for some particular arity values for CliArgument is not just a duplication of concern across two properties, it also just gets inelegant, messy and unclear fast, as your musings nicely demonstrate...)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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