VictoriaMetrics/vendor/github.com/urfave/cli/v2/suggestions.go

61 lines
1.4 KiB
Go
Raw Normal View History

2022-05-20 11:45:24 +00:00
package cli
import (
"fmt"
2022-05-25 18:49:12 +00:00
"github.com/xrash/smetrics"
2022-05-20 11:45:24 +00:00
)
2022-05-25 18:49:12 +00:00
func jaroWinkler(a, b string) float64 {
// magic values are from https://github.com/xrash/smetrics/blob/039620a656736e6ad994090895784a7af15e0b80/jaro-winkler.go#L8
const (
boostThreshold = 0.7
prefixSize = 4
)
return smetrics.JaroWinkler(a, b, boostThreshold, prefixSize)
2022-05-20 11:45:24 +00:00
}
2022-05-25 18:49:12 +00:00
func suggestFlag(flags []Flag, provided string, hideHelp bool) string {
2022-05-20 11:45:24 +00:00
distance := 0.0
2022-05-25 18:49:12 +00:00
suggestion := ""
2022-05-20 11:45:24 +00:00
for _, flag := range flags {
flagNames := flag.Names()
2022-05-25 18:49:12 +00:00
if !hideHelp {
2022-05-20 11:45:24 +00:00
flagNames = append(flagNames, HelpFlag.Names()...)
}
for _, name := range flagNames {
2022-05-25 18:49:12 +00:00
newDistance := jaroWinkler(name, provided)
2022-05-20 11:45:24 +00:00
if newDistance > distance {
distance = newDistance
suggestion = name
}
}
}
if len(suggestion) == 1 {
suggestion = "-" + suggestion
} else if len(suggestion) > 1 {
suggestion = "--" + suggestion
}
return suggestion
}
// suggestCommand takes a list of commands and a provided string to suggest a
// command name
func suggestCommand(commands []*Command, provided string) (suggestion string) {
distance := 0.0
for _, command := range commands {
for _, name := range append(command.Names(), helpName, helpAlias) {
2022-05-25 18:49:12 +00:00
newDistance := jaroWinkler(name, provided)
2022-05-20 11:45:24 +00:00
if newDistance > distance {
distance = newDistance
suggestion = name
}
}
}
2022-05-25 18:49:12 +00:00
return fmt.Sprintf(SuggestDidYouMeanTemplate, suggestion)
2022-05-20 11:45:24 +00:00
}