Suggesting commands

When the specified command does not exist, we can suggest some similar commands. In order to do so, we can use the Levenshtein distance formula, which measures the similarity between strings by counting deletions, insertions, and substitutions needed to go from one string to the other.

In the following code, we will use the agnivade/levenshtein package, which will be obtained through the go get command:

go get github.com/agnivade/levenshtein/...

Then, we define a new function to call when there is no match with existing commands:

func commandNotFound(w io.Writer, cmd string) {
var list []string
for _, c := range cmds {
d := levenshtein.ComputeDistance(c.Name, cmd)
if d < 3 {
list = append(list, c.Name)
}
}
fmt.Fprintf(w, "Command %q not found.", cmd)
if len(list) == 0 {
return
}
fmt.Fprint(w, " Maybe you meant: ")
for i := range list {
if i > 0 {
fmt.Fprint(w, ", ")
}
fmt.Fprintf(w, "%s", list[i])
}
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.76.72