Skip to content

Commit

Permalink
Cumulative argument needs to be last (#331)
Browse files Browse the repository at this point in the history
  • Loading branch information
michal-kralik authored Sep 20, 2022
1 parent 15aa6d8 commit 9c8b401
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
24 changes: 20 additions & 4 deletions build.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
for i, curr := range node.Positional {
if last != nil && !last.Required && curr.Required {
return nil, fmt.Errorf("%s: required %q can not come after optional %q", node.FullPath(), curr.Name, last.Name)
if last != nil {
// 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
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 {
Expand Down
18 changes: 18 additions & 0 deletions kong_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1718,3 +1718,21 @@ func TestChildNameCanBeDuplicated(t *testing.T) {
}
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)
}

0 comments on commit 9c8b401

Please sign in to comment.