Skip to content

Commit

Permalink
fix: set trailing positional arguments to active
Browse files Browse the repository at this point in the history
This fixes an issue where existingfile et al would not correctly apply
to positional arguments with defaults.
  • Loading branch information
alecthomas committed Nov 17, 2023
1 parent 0ecd272 commit 575d5b1
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
18 changes: 18 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -520,9 +520,26 @@ func (c *Context) trace(node *Node) (err error) { // nolint: gocyclo
return fmt.Errorf("unexpected token %s", token)
}
}
if err := c.traceDefaults(); err != nil {
return fmt.Errorf("error tracing defaults: %w", err)
}
return c.maybeSelectDefault(flags, node)
}

func (c *Context) traceDefaults() error {
tail := c.Path[len(c.Path)-1]
for _, positional := range tail.Node().Positional {
if positional.DefaultValue.IsValid() {
positional.Active = true
c.Path = append(c.Path, &Path{
Parent: tail.Node(),
Positional: positional,
})
}
}
return nil
}

// End of the line, check for a default command, but only if we're not displaying help,
// otherwise we'd only ever display the help for the default command.
func (c *Context) maybeSelectDefault(flags []*Flag, node *Node) error {
Expand All @@ -532,6 +549,7 @@ func (c *Context) maybeSelectDefault(flags []*Flag, node *Node) error {
}
}
if node.DefaultCmd != nil {
node.Active = true
c.Path = append(c.Path, &Path{
Parent: node.DefaultCmd,
Command: node.DefaultCmd,
Expand Down
15 changes: 15 additions & 0 deletions kong_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"bytes"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"

Expand Down Expand Up @@ -1984,3 +1986,16 @@ func TestEnumPtrOmittedNoDefault(t *testing.T) {
assert.NotZero(t, ctx)
assert.Zero(t, cli.X)
}

func TestTrailingPositionalActive(t *testing.T) {
var cli struct {
Arg string `arg:"" default:"." existingdir:"testdata"`
}
pwd, err := os.Getwd()
assert.NoError(t, err)
k, err := kong.New(&cli)
assert.NoError(t, err)
_, err = k.Parse([]string{})
assert.NoError(t, err)
assert.Equal(t, cli.Arg, filepath.Join(pwd, "testdata"))
}

0 comments on commit 575d5b1

Please sign in to comment.