diff --git a/src/CommandLineUtils/Conventions/ArgumentAttributeConvention.cs b/src/CommandLineUtils/Conventions/ArgumentAttributeConvention.cs index 7b3f70b5..2545e2d4 100644 --- a/src/CommandLineUtils/Conventions/ArgumentAttributeConvention.cs +++ b/src/CommandLineUtils/Conventions/ArgumentAttributeConvention.cs @@ -150,26 +150,30 @@ private void AddArgument(PropertyInfo prop, if (r.SelectedCommand is IModelAccessor cmd) { - if (argument.Values.Count == 0) + var model = cmd.GetModel(); + if (prop.DeclaringType.IsAssignableFrom(model.GetType())) { - if (!ReflectionHelper.IsSpecialValueTupleType(prop.PropertyType, out _)) + if (argument.Values.Count == 0) { - var value = getter.Invoke(cmd.GetModel()); - if (value != null) + if (!ReflectionHelper.IsSpecialValueTupleType(prop.PropertyType, out _)) { - argument.TryParse(value.ToString()); - argument.DefaultValue = value.ToString(); + var value = getter.Invoke(model); + if (value != null) + { + argument.TryParse(value.ToString()); + argument.DefaultValue = value.ToString(); + } } } - } - else - { - setter.Invoke( - cmd.GetModel(), - parser.Parse( - argument.Name, - argument.Value, - convention.Application.ValueParsers.ParseCulture)); + else + { + setter.Invoke( + model, + parser.Parse( + argument.Name, + argument.Value, + convention.Application.ValueParsers.ParseCulture)); + } } } }); diff --git a/test/CommandLineUtils.Tests/ArgumentAttributeTests.cs b/test/CommandLineUtils.Tests/ArgumentAttributeTests.cs index 83a74ec3..7bf5aa87 100644 --- a/test/CommandLineUtils.Tests/ArgumentAttributeTests.cs +++ b/test/CommandLineUtils.Tests/ArgumentAttributeTests.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.Linq; using Xunit; using Xunit.Abstractions; @@ -94,5 +95,47 @@ public void KeepsDefaultValues() Assert.Equal("a", app3.Model.Arg1); Assert.Equal(new[] { "b", "c" }, app3.Model.Arg2); } + + [Subcommand(typeof(ACommand))] + public class Program + { + } + + [Command("a")] + [Subcommand(typeof(BCommand))] + public class ACommand + { + [Argument(0)] + public string? Arg1 { get; set; } + } + + [Command("b")] + public class BCommand + { + [Argument(0)] + public string? Arg1 { get; set; } + } + + [Fact] + public void SameArgumentInSubcommandsCallingACommand() + { + var app1 = new CommandLineApplication(); + app1.Conventions.UseDefaultConventions(); + var result = app1.Parse("a", "any-value"); + var command = result.SelectedCommand as CommandLineApplication; + Assert.NotNull(command); + Assert.Equal("any-value", command.Model.Arg1); + } + + [Fact] + public void SameArgumentInSubcommandsCallingBCommand() + { + var app1 = new CommandLineApplication(); + app1.Conventions.UseDefaultConventions(); + var result = app1.Parse("a", "b", "any-value"); + var command = result.SelectedCommand as CommandLineApplication; + Assert.NotNull(command); + Assert.Equal("any-value", command.Model.Arg1); + } } }