fix: ignore --help flag for determining optional flag usage

Fixes #508
This commit is contained in:
Alec Thomas
2025-03-08 21:05:55 +11:00
parent 5b36573738
commit 73db2e86a5
3 changed files with 30 additions and 7 deletions
+7 -7
View File
@@ -51,7 +51,7 @@ func TestHelpOptionalArgs(t *testing.T) {
assert.NoError(t, err)
})
assert.True(t, exited)
expected := `Usage: test-app [<one> [<two>]] [flags]
expected := `Usage: test-app [<one> [<two>]]
Arguments:
[<one>] One optional arg.
@@ -320,7 +320,7 @@ func TestHelpTree(t *testing.T) {
assert.NoError(t, err)
})
assert.True(t, exited)
expected := `Usage: test-app <command> [flags]
expected := `Usage: test-app <command>
A test app.
@@ -353,7 +353,7 @@ Run "test-app <command> --help" for more information on a command.
assert.NoError(t, err)
})
assert.True(t, exited)
expected := `Usage: test-app one (un,uno) <command> [flags]
expected := `Usage: test-app one (un,uno) <command>
subcommand one
@@ -413,7 +413,7 @@ func TestHelpCompactNoExpand(t *testing.T) {
assert.NoError(t, err)
})
assert.True(t, exited)
expected := `Usage: test-app <command> [flags]
expected := `Usage: test-app <command>
A test app.
@@ -442,7 +442,7 @@ Run "test-app <command> --help" for more information on a command.
assert.NoError(t, err)
})
assert.True(t, exited)
expected := `Usage: test-app one (un,uno) <command> [flags]
expected := `Usage: test-app one (un,uno) <command>
subcommand one
@@ -795,7 +795,7 @@ func TestUsageOnError(t *testing.T) {
_, err := p.Parse([]string{})
p.FatalIfErrorf(err)
expected := `Usage: test --flag=STRING [flags]
expected := `Usage: test --flag=STRING
Some description.
@@ -823,7 +823,7 @@ func TestShortUsageOnError(t *testing.T) {
assert.Error(t, err)
p.FatalIfErrorf(err)
expected := `Usage: test --flag=STRING [flags]
expected := `Usage: test --flag=STRING
Run "test --help" for more information.
test: error: missing flags: --flag=STRING
+3
View File
@@ -167,6 +167,9 @@ func (n *Node) Summary() string {
allFlags = append(allFlags, n.Parent.Flags...)
}
for _, flag := range allFlags {
if _, ok := flag.Target.Interface().(helpFlag); ok {
continue
}
if !flag.Required {
summary += " [flags]"
break
+20
View File
@@ -1,6 +1,7 @@
package kong_test
import (
"bytes"
"testing"
"github.com/alecthomas/assert/v2"
@@ -70,3 +71,22 @@ func TestFlagString(t *testing.T) {
assert.Equal(t, want, flag.String())
}
}
func TestIgnoreHelpInUsage(t *testing.T) {
var cli struct {
One string `required:""`
}
k := mustNew(t, &cli)
w := &bytes.Buffer{}
k.Stdout = w
k.Exit = func(code int) {}
_, err := k.Parse([]string{"--help"})
assert.Error(t, err)
assert.Equal(t, `Usage: test --one=STRING
Flags:
-h, --help Show context-sensitive help.
--one=STRING
`, w.String())
}