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

cmd/cue: fix help cmd incorrect behavior #2759

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 12 additions & 7 deletions cmd/cue/cmd/help.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,14 @@
package cmd

import (
"os"
"strings"

"github.com/spf13/cobra"
)

var osExit = os.Exit

// TODO: intersperse the examples at the end of the texts in the
// body of text to make things more concrete for the user early on?
// The current approach works will if users just print the text without
Expand All @@ -34,7 +39,7 @@ func newHelpCmd(c *Command) *cobra.Command {
Long: `Help provides help for any command in the application.
Simply type ` + c.Name() + ` help [path to command] for full details.`,
Run: func(_ *cobra.Command, args []string) {
cmd, _, e := c.Root().Find(args)
cmd, rests, e := c.Root().Find(args)
if len(args) > 0 && args[0] == "cmd" {
// args is one of:
//
Expand All @@ -52,15 +57,15 @@ Simply type ` + c.Name() + ` help [path to command] for full details.`,
if err == nil {
addCustomCommands(c, cmd, commandSection, tools)
// For the sake of `cue help cmd mycmd`, find the command again.
cmd, _, e = c.Root().Find(args)
cmd, rests, e = c.Root().Find(args)
}
}
if cmd == nil || e != nil {
c.Printf("Unknown help topic %#q\n", args)
cobra.CheckErr(c.Root().Usage())
} else {
cobra.CheckErr(cmd.Help())
// If rests are not empty, args are invalid.
if cmd == nil || e != nil || len(rests) != 0 {
c.PrintErrf("Unknown help command: %#q\n", strings.Join(args, " "))
osExit(1)
}
cobra.CheckErr(cmd.Help())
},
}
return cmd
Expand Down
21 changes: 21 additions & 0 deletions cmd/cue/cmd/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,25 @@ func TestHelp(t *testing.T) {
if err := run("eval", "--help"); err != nil {
t.Error("help command failed unexpectedly")
}

// os.Exit(1) is expected
testOsExit(t, 1, []string{"help", "foo"}, run)

testOsExit(t, 1, []string{"help", "cmd", "foo"}, run)
}

// testOsExit tests that os.Exit is called with the given code when running f.
func testOsExit(t *testing.T, code int, args []string, f func(args ...string) error) {
t.Helper()
oldExit := osExit
defer func() { osExit = oldExit }()
var status int
exit := func(code int) {
status = code
}
osExit = exit
f(args...)
if status != code {
t.Errorf("os.Exit(%d) not called", code)
}
}