Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: When a Grammar combines flags with passthrough args, see if an unrecognized flag may be treated as a positional argument #435

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,7 @@ issues:
# Duplicate words are okay in tests.
- linters: [dupword]
path: _test\.go

- linters: [maintidx]
path: context\.go
text: 'Function name: trace'
Comment on lines +90 to +93
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To bypass the linter error:

context.go:350:1: Function name: trace, Cyclomatic Complexity: 47, Halstead Volume: 4627.00, Maintainability Index: 18 (maintidx)

Would you prefer I extracted something from trace instead? Or reworked it to not have a nested if?

... maybe like

case FlagToken:
	if err := c.parseFlag(flags, token.String()); err == nil {
		// Flag was parsed successfully.
	} else if isUnknownFlagError(err) && positional < len(node.Positional) && node.Positional[positional].Passthrough {
		c.scan.Pop()
		c.scan.PushTyped(token.String(), PositionalArgumentToken)
	} else {
		return err
	}

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's fine, the linters are just guides, I usually disable them as necessary. FYI you can also just use //nolint:maintidx on the offending line.

26 changes: 23 additions & 3 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -420,12 +420,22 @@ func (c *Context) trace(node *Node) (err error) { //nolint: gocyclo

case FlagToken:
if err := c.parseFlag(flags, token.String()); err != nil {
return err
if isUnknownFlagError(err) && positional < len(node.Positional) && node.Positional[positional].Passthrough {
c.scan.Pop()
c.scan.PushTyped(token.String(), PositionalArgumentToken)
} else {
return err
}
}

case ShortFlagToken:
if err := c.parseFlag(flags, token.String()); err != nil {
return err
if isUnknownFlagError(err) && positional < len(node.Positional) && node.Positional[positional].Passthrough {
c.scan.Pop()
c.scan.PushTyped(token.String(), PositionalArgumentToken)
} else {
return err
}
}

case FlagValueToken:
Expand Down Expand Up @@ -728,9 +738,19 @@ func (c *Context) parseFlag(flags []*Flag, match string) (err error) {
c.Path = append(c.Path, &Path{Flag: flag})
return nil
}
return findPotentialCandidates(match, candidates, "unknown flag %s", match)
return &unknownFlagError{Cause: findPotentialCandidates(match, candidates, "unknown flag %s", match)}
}

func isUnknownFlagError(err error) bool {
var unknown *unknownFlagError
return errors.As(err, &unknown)
}

type unknownFlagError struct{ Cause error }

func (e *unknownFlagError) Unwrap() error { return e.Cause }
func (e *unknownFlagError) Error() string { return e.Cause.Error() }

// Call an arbitrary function filling arguments with bound values.
func (c *Context) Call(fn any, binds ...interface{}) (out []interface{}, err error) {
fv := reflect.ValueOf(fn)
Expand Down
48 changes: 48 additions & 0 deletions kong_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1526,6 +1526,54 @@ func TestEnumValidation(t *testing.T) {
}
}

func TestPassthroughArgs(t *testing.T) {
tests := []struct {
name string
args []string
flag string
cmdArgs []string
}{
{
"NoArgs",
[]string{},
"",
[]string(nil),
},
{
"RecognizedFlagAndArgs",
[]string{"--flag", "foobar", "something"},
"foobar",
[]string{"something"},
},
{
"DashDashBeforeRecognizedFlag",
[]string{"--", "--flag", "foobar"},
"",
[]string{"--flag", "foobar"},
},
{
"UnrecognizedFlagAndArgs",
[]string{"--unrecognized-flag", "something"},
"",
[]string{"--unrecognized-flag", "something"},
},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
var cli struct {
Flag string
Args []string `arg:"" optional:"" passthrough:""`
}
p := mustNew(t, &cli)
_, err := p.Parse(test.args)
assert.NoError(t, err)
assert.Equal(t, test.flag, cli.Flag)
assert.Equal(t, test.cmdArgs, cli.Args)
})
}
}

func TestPassthroughCmd(t *testing.T) {
tests := []struct {
name string
Expand Down