From dfbc6cd81b47b5fa7d49d9174d613cc63b0ea36e Mon Sep 17 00:00:00 2001 From: colin axner Date: Sat, 4 Apr 2020 11:24:11 -0700 Subject: [PATCH] Merge PR #5920: Fix validate cmd bug --- client/cmd.go | 37 ++++++++++++++++++++++++++++--------- client/cmd_test.go | 2 ++ 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/client/cmd.go b/client/cmd.go index afddf20fe..df9c5be62 100644 --- a/client/cmd.go +++ b/client/cmd.go @@ -2,6 +2,7 @@ package client import ( "fmt" + "strings" "github.com/pkg/errors" "github.com/spf13/cobra" @@ -9,23 +10,41 @@ import ( // ValidateCmd returns unknown command error or Help display if help flag set func ValidateCmd(cmd *cobra.Command, args []string) error { - var cmds []string - var help bool + var unknownCmd string + var skipNext bool - // construct array of commands and search for help flag for _, arg := range args { + // search for help flag if arg == "--help" || arg == "-h" { - help = true - } else if len(arg) > 0 && !(arg[0] == '-') { - cmds = append(cmds, arg) + return cmd.Help() + } + + // check if the current arg is a flag + switch { + case len(arg) > 0 && (arg[0] == '-'): + // the next arg should be skipped if the current arg is a + // flag and does not use "=" to assign the flag's value + if !strings.Contains(arg, "=") { + skipNext = true + } else { + skipNext = false + } + case skipNext: + // skip current arg + skipNext = false + case unknownCmd == "": + // unknown command found + // continue searching for help flag + unknownCmd = arg } } - if !help && len(cmds) > 0 { - err := fmt.Sprintf("unknown command \"%s\" for \"%s\"", cmds[0], cmd.CalledAs()) + // return the help screen if no unknown command is found + if unknownCmd != "" { + err := fmt.Sprintf("unknown command \"%s\" for \"%s\"", unknownCmd, cmd.CalledAs()) // build suggestions for unknown argument - if suggestions := cmd.SuggestionsFor(cmds[0]); len(suggestions) > 0 { + if suggestions := cmd.SuggestionsFor(unknownCmd); len(suggestions) > 0 { err += "\n\nDid you mean this?\n" for _, s := range suggestions { err += fmt.Sprintf("\t%v\n", s) diff --git a/client/cmd_test.go b/client/cmd_test.go index 554d39953..94de38311 100644 --- a/client/cmd_test.go +++ b/client/cmd_test.go @@ -41,6 +41,8 @@ func TestValidateCmd(t *testing.T) { {"no command provided", []string{}, false}, {"help flag", []string{"commission", "--help"}, false}, // nolint: misspell {"shorthand help flag", []string{"commission", "-h"}, false}, // nolint: misspell + {"flag only, no command provided", []string{"--gas", "1000atom"}, false}, + {"flag and misspelled command", []string{"--gas", "1000atom", "comission"}, true}, // nolint: misspell } for _, tt := range tests {