From 93f73cf38cefcd96da05d5825ee3ba7bc93443d5 Mon Sep 17 00:00:00 2001 From: Alec Thomas Date: Sat, 13 Mar 2021 20:25:26 +1100 Subject: [PATCH] Display multiple optional args in a more expected way. Previously: Usage: command [] [] Now: Usage: command [ []] Thanks to @juliaogris for the inspiration! --- help_test.go | 32 ++++++++++++++++++++++++++++++++ model.go | 10 ++++++++-- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/help_test.go b/help_test.go index 7537486..730c189 100644 --- a/help_test.go +++ b/help_test.go @@ -21,6 +21,38 @@ func (threeArg) Help() string { return `Detailed help provided through the HelpProvider interface.` } +func TestHelpOptionalArgs(t *testing.T) { + var cli struct { + One string `arg:"" optional:"" help:"One optional arg."` + Two string `arg:"" optional:"" help:"Two optional arg."` + } + w := bytes.NewBuffer(nil) + exited := false + app := mustNew(t, &cli, + kong.Name("test-app"), + kong.Writers(w, w), + kong.Exit(func(int) { + exited = true + panic(true) // Panic to fake "exit". + }), + ) + require.PanicsWithValue(t, true, func() { + _, err := app.Parse([]string{"--help"}) + require.NoError(t, err) + }) + require.True(t, exited) + expected := `Usage: test-app [ []] + +Arguments: + [] One optional arg. + [] Two optional arg. + +Flags: + -h, --help Show context-sensitive help. +` + require.Equal(t, expected, w.String()) +} + func TestHelp(t *testing.T) { // nolint: govet var cli struct { diff --git a/model.go b/model.go index 4ce2456..c1ef65b 100644 --- a/model.go +++ b/model.go @@ -146,11 +146,17 @@ func (n *Node) Summary() string { summary += " " + flags } args := []string{} + optional := 0 for _, arg := range n.Positional { - args = append(args, arg.Summary()) + summary := arg.Summary() + if arg.Tag.Optional { + optional++ + summary = strings.TrimRight(summary, "]") + } + args = append(args, summary) } if len(args) != 0 { - summary += " " + strings.Join(args, " ") + summary += " " + strings.Join(args, " ") + strings.Repeat("]", optional) } else if len(n.Children) > 0 { summary += " " }