...

Source file src/github.com/urfave/cli/v2/suggestions.go

Documentation: github.com/urfave/cli/v2

     1  //go:build !urfave_cli_no_suggest
     2  // +build !urfave_cli_no_suggest
     3  
     4  package cli
     5  
     6  import (
     7  	"fmt"
     8  
     9  	"github.com/xrash/smetrics"
    10  )
    11  
    12  func init() {
    13  	SuggestFlag = suggestFlag
    14  	SuggestCommand = suggestCommand
    15  }
    16  
    17  func jaroWinkler(a, b string) float64 {
    18  	// magic values are from https://github.com/xrash/smetrics/blob/039620a656736e6ad994090895784a7af15e0b80/jaro-winkler.go#L8
    19  	const (
    20  		boostThreshold = 0.7
    21  		prefixSize     = 4
    22  	)
    23  	return smetrics.JaroWinkler(a, b, boostThreshold, prefixSize)
    24  }
    25  
    26  func suggestFlag(flags []Flag, provided string, hideHelp bool) string {
    27  	distance := 0.0
    28  	suggestion := ""
    29  
    30  	for _, flag := range flags {
    31  		flagNames := flag.Names()
    32  		if !hideHelp && HelpFlag != nil {
    33  			flagNames = append(flagNames, HelpFlag.Names()...)
    34  		}
    35  		for _, name := range flagNames {
    36  			newDistance := jaroWinkler(name, provided)
    37  			if newDistance > distance {
    38  				distance = newDistance
    39  				suggestion = name
    40  			}
    41  		}
    42  	}
    43  
    44  	if len(suggestion) == 1 {
    45  		suggestion = "-" + suggestion
    46  	} else if len(suggestion) > 1 {
    47  		suggestion = "--" + suggestion
    48  	}
    49  
    50  	return suggestion
    51  }
    52  
    53  // suggestCommand takes a list of commands and a provided string to suggest a
    54  // command name
    55  func suggestCommand(commands []*Command, provided string) (suggestion string) {
    56  	distance := 0.0
    57  	for _, command := range commands {
    58  		for _, name := range append(command.Names(), helpName, helpAlias) {
    59  			newDistance := jaroWinkler(name, provided)
    60  			if newDistance > distance {
    61  				distance = newDistance
    62  				suggestion = name
    63  			}
    64  		}
    65  	}
    66  
    67  	return fmt.Sprintf(SuggestDidYouMeanTemplate, suggestion)
    68  }
    69  

View as plain text