cmd_suggestion.go 2.11 KB
Newer Older
1 2 3
package cli

import (
4
	"fmt"
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
	"sort"
	"strings"

	levenshtein "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/texttheater/golang-levenshtein/levenshtein"
	cmds "github.com/ipfs/go-ipfs/commands"
)

// Make a custom slice that can be sorted by its levenshtein value
type suggestionSlice []*suggestion

type suggestion struct {
	cmd         string
	levenshtein int
}

func (s suggestionSlice) Len() int {
	return len(s)
}

func (s suggestionSlice) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func (s suggestionSlice) Less(i, j int) bool {
	return s[i].levenshtein < s[j].levenshtein
}

func suggestUnknownCmd(args []string, root *cmds.Command) []string {
33 34 35 36
	if root == nil {
		return nil
	}

37 38 39 40 41 42
	arg := args[0]
	var suggestions []string
	sortableSuggestions := make(suggestionSlice, 0)
	var sFinal []string
	const MIN_LEVENSHTEIN = 3

Jan Winkelmann's avatar
Jan Winkelmann committed
43
	var options = levenshtein.Options{
44 45 46 47 48 49 50 51 52
		InsCost: 1,
		DelCost: 3,
		SubCost: 2,
		Matches: func(sourceCharacter rune, targetCharacter rune) bool {
			return sourceCharacter == targetCharacter
		},
	}

	// Start with a simple strings.Contains check
Jan Winkelmann's avatar
Jan Winkelmann committed
53
	for name := range root.Subcommands {
54 55 56 57 58 59 60 61 62 63
		if strings.Contains(arg, name) {
			suggestions = append(suggestions, name)
		}
	}

	// If the string compare returns a match, return
	if len(suggestions) > 0 {
		return suggestions
	}

Jan Winkelmann's avatar
Jan Winkelmann committed
64
	for name := range root.Subcommands {
65 66 67 68 69 70 71 72 73 74 75 76
		lev := levenshtein.DistanceForStrings([]rune(arg), []rune(name), options)
		if lev <= MIN_LEVENSHTEIN {
			sortableSuggestions = append(sortableSuggestions, &suggestion{name, lev})
		}
	}
	sort.Sort(sortableSuggestions)

	for _, j := range sortableSuggestions {
		sFinal = append(sFinal, j.cmd)
	}
	return sFinal
}
77 78 79 80 81 82 83 84 85

func printSuggestions(inputs []string, root *cmds.Command) (err error) {

	suggestions := suggestUnknownCmd(inputs, root)
	if len(suggestions) > 1 {
		err = fmt.Errorf("Unknown Command \"%s\"\n\nDid you mean any of these?\n\n\t%s", inputs[0], strings.Join(suggestions, "\n\t"))
	} else if len(suggestions) > 0 {
		err = fmt.Errorf("Unknown Command \"%s\"\n\nDid you mean this?\n\n\t%s", inputs[0], suggestions[0])
	} else {
Jan Winkelmann's avatar
Jan Winkelmann committed
86
		err = fmt.Errorf("Unknown Command %q", inputs[0])
87 88 89
	}
	return
}