github.com/crowdsecurity/crowdsec@v1.6.1/cmd/crowdsec-cli/item_suggest.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "slices" 6 "strings" 7 8 "github.com/agext/levenshtein" 9 "github.com/spf13/cobra" 10 11 "github.com/crowdsecurity/crowdsec/cmd/crowdsec-cli/require" 12 "github.com/crowdsecurity/crowdsec/pkg/cwhub" 13 ) 14 15 // suggestNearestMessage returns a message with the most similar item name, if one is found 16 func suggestNearestMessage(hub *cwhub.Hub, itemType string, itemName string) string { 17 const maxDistance = 7 18 19 score := 100 20 nearest := "" 21 22 for _, item := range hub.GetItemMap(itemType) { 23 d := levenshtein.Distance(itemName, item.Name, nil) 24 if d < score { 25 score = d 26 nearest = item.Name 27 } 28 } 29 30 msg := fmt.Sprintf("can't find '%s' in %s", itemName, itemType) 31 32 if score < maxDistance { 33 msg += fmt.Sprintf(", did you mean '%s'?", nearest) 34 } 35 36 return msg 37 } 38 39 func compAllItems(itemType string, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { 40 hub, err := require.Hub(csConfig, nil, nil) 41 if err != nil { 42 return nil, cobra.ShellCompDirectiveDefault 43 } 44 45 comp := make([]string, 0) 46 47 for _, item := range hub.GetItemMap(itemType) { 48 if !slices.Contains(args, item.Name) && strings.Contains(item.Name, toComplete) { 49 comp = append(comp, item.Name) 50 } 51 } 52 53 cobra.CompDebugln(fmt.Sprintf("%s: %+v", itemType, comp), true) 54 55 return comp, cobra.ShellCompDirectiveNoFileComp 56 } 57 58 func compInstalledItems(itemType string, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { 59 hub, err := require.Hub(csConfig, nil, nil) 60 if err != nil { 61 return nil, cobra.ShellCompDirectiveDefault 62 } 63 64 items, err := hub.GetInstalledItemNames(itemType) 65 if err != nil { 66 cobra.CompDebugln(fmt.Sprintf("list installed %s err: %s", itemType, err), true) 67 return nil, cobra.ShellCompDirectiveDefault 68 } 69 70 comp := make([]string, 0) 71 72 if toComplete != "" { 73 for _, item := range items { 74 if strings.Contains(item, toComplete) { 75 comp = append(comp, item) 76 } 77 } 78 } else { 79 comp = items 80 } 81 82 cobra.CompDebugln(fmt.Sprintf("%s: %+v", itemType, comp), true) 83 84 return comp, cobra.ShellCompDirectiveNoFileComp 85 }