github.com/sleungcy/cli@v7.1.0+incompatible/util/command_parser/unknown_command_error.go (about)

     1  package command_parser
     2  
     3  import (
     4  	"fmt"
     5  	"reflect"
     6  
     7  	"code.cloudfoundry.org/cli/cf/util/spellcheck"
     8  	"code.cloudfoundry.org/cli/command/common"
     9  )
    10  
    11  type UnknownCommandError struct {
    12  	CommandName string
    13  	suggestions []string
    14  }
    15  
    16  func (e *UnknownCommandError) Suggest(pluginCommandNames []string) {
    17  	var commandNames []string
    18  
    19  	commandListStruct := reflect.TypeOf(common.Commands)
    20  	commandListStruct.FieldByNameFunc(
    21  		func(fieldName string) bool {
    22  			field, _ := commandListStruct.FieldByName(fieldName)
    23  			if commandName := field.Tag.Get("command"); commandName != "" {
    24  				commandNames = append(commandNames, commandName)
    25  			}
    26  			return false
    27  		})
    28  
    29  	cmdSuggester := spellcheck.NewCommandSuggester(append(commandNames, pluginCommandNames...))
    30  	e.suggestions = cmdSuggester.Recommend(e.CommandName)
    31  }
    32  
    33  func (e UnknownCommandError) Error() string {
    34  	message := fmt.Sprintf("'%s' is not a registered command. See 'cf help -a'", e.CommandName)
    35  
    36  	if len(e.suggestions) > 0 {
    37  		message += "\n\nDid you mean?"
    38  
    39  		for _, suggestion := range e.suggestions {
    40  			message += "\n    " + suggestion
    41  		}
    42  	}
    43  
    44  	return message
    45  }