File: suggestions.go

package info (click to toggle)
golang-github-urfave-cli-v2 2.25.7-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 7,188 kB
  • sloc: makefile: 41; sh: 28
file content (60 lines) | stat: -rw-r--r-- 1,412 bytes parent folder | download | duplicates (2)
1
2
3
4
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package cli

import (
	"fmt"

	"github.com/xrash/smetrics"
)

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)
}

func suggestFlag(flags []Flag, provided string, hideHelp bool) string {
	distance := 0.0
	suggestion := ""

	for _, flag := range flags {
		flagNames := flag.Names()
		if !hideHelp {
			flagNames = append(flagNames, HelpFlag.Names()...)
		}
		for _, name := range flagNames {
			newDistance := jaroWinkler(name, provided)
			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) {
			newDistance := jaroWinkler(name, provided)
			if newDistance > distance {
				distance = newDistance
				suggestion = name
			}
		}
	}

	return fmt.Sprintf(SuggestDidYouMeanTemplate, suggestion)
}