github.com/fibonacci-chain/fbc@v0.0.0-20231124064014-c7636198c1e9/libs/cosmos-sdk/client/cmd.go (about)

     1  package client
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"github.com/spf13/cobra"
     7  	"strings"
     8  )
     9  
    10  // ValidateCmd returns unknown command error or Help display if help flag set
    11  func ValidateCmd(cmd *cobra.Command, args []string) error {
    12  	var unknownCmd string
    13  	var skipNext bool
    14  
    15  	for _, arg := range args {
    16  		// search for help flag
    17  		if arg == "--help" || arg == "-h" {
    18  			return cmd.Help()
    19  		}
    20  
    21  		// check if the current arg is a flag
    22  		switch {
    23  		case len(arg) > 0 && (arg[0] == '-'):
    24  			// the next arg should be skipped if the current arg is a
    25  			// flag and does not use "=" to assign the flag's value
    26  			if !strings.Contains(arg, "=") {
    27  				skipNext = true
    28  			} else {
    29  				skipNext = false
    30  			}
    31  		case skipNext:
    32  			// skip current arg
    33  			skipNext = false
    34  		case unknownCmd == "":
    35  			// unknown command found
    36  			// continue searching for help flag
    37  			unknownCmd = arg
    38  		}
    39  	}
    40  
    41  	// return the help screen if no unknown command is found
    42  	if unknownCmd != "" {
    43  		err := fmt.Sprintf("unknown command \"%s\" for \"%s\"", unknownCmd, cmd.CalledAs())
    44  
    45  		// build suggestions for unknown argument
    46  		if suggestions := cmd.SuggestionsFor(unknownCmd); len(suggestions) > 0 {
    47  			err += "\n\nDid you mean this?\n"
    48  			for _, s := range suggestions {
    49  				err += fmt.Sprintf("\t%v\n", s)
    50  			}
    51  		}
    52  		return errors.New(err)
    53  	}
    54  
    55  	return cmd.Help()
    56  }