Cumulative argument needs to be last (#331)

This commit is contained in:
Michal Kralik
2022-09-20 14:47:41 +02:00
committed by GitHub
parent 15aa6d8d4e
commit 9c8b401de0
2 changed files with 38 additions and 4 deletions
+20 -4
View File
@@ -171,17 +171,33 @@ MAIN:
} }
} }
// Scan through argument positionals to ensure optional is never before a required. if err := validatePositionalArguments(node); err != nil {
return nil, err
}
return node, nil
}
func validatePositionalArguments(node *Node) error {
var last *Value var last *Value
for i, curr := range node.Positional { for i, curr := range node.Positional {
if last != nil && !last.Required && curr.Required { if last != nil {
return nil, fmt.Errorf("%s: required %q can not come after optional %q", node.FullPath(), curr.Name, last.Name) // Scan through argument positionals to ensure optional is never before a required.
if !last.Required && curr.Required {
return fmt.Errorf("%s: required %q cannot come after optional %q", node.FullPath(), curr.Name, last.Name)
}
// Cumulative argument needs to be last.
if last.IsCumulative() {
return fmt.Errorf("%s: argument %q cannot come after cumulative %q", node.FullPath(), curr.Name, last.Name)
}
} }
last = curr last = curr
curr.Position = i curr.Position = i
} }
return node, nil return nil
} }
func buildChild(k *Kong, node *Node, typ NodeType, v reflect.Value, ft reflect.StructField, fv reflect.Value, tag *Tag, name string, seenFlags map[string]bool) error { func buildChild(k *Kong, node *Node, typ NodeType, v reflect.Value, ft reflect.StructField, fv reflect.Value, tag *Tag, name string, seenFlags map[string]bool) error {
+18
View File
@@ -1718,3 +1718,21 @@ func TestChildNameCanBeDuplicated(t *testing.T) {
} }
mustNew(t, &cli) mustNew(t, &cli)
} }
func TestCumulativeArgumentLast(t *testing.T) {
var cli struct {
Arg1 string `arg:""`
Arg2 []string `arg:""`
}
_, err := kong.New(&cli)
assert.NoError(t, err)
}
func TestCumulativeArgumentNotLast(t *testing.T) {
var cli struct {
Arg2 []string `arg:""`
Arg1 string `arg:""`
}
_, err := kong.New(&cli)
assert.Error(t, err)
}