58 lines
1.6 KiB
Go
Raw Normal View History

2024-01-15 16:02:15 -05:00
package cache
2023-12-08 16:52:26 -05:00
import (
"strings"
"github.com/lithammer/fuzzysearch/fuzzy"
2024-01-15 15:39:35 -05:00
"gitlab.sweetwater.com/it/devops/tools/gitlab-project-manager/internal/remotes/projects"
2023-12-08 16:52:26 -05:00
)
// Performs a fuzzy find on the input string, returning the closest
// matched based on its Levenshtein distance, along with an integer
// indicating number of matches found
func (c *Cache) FuzzyFindAlias(name string) []*ProjectAlias {
ranks := fuzzy.RankFindFold(name, c.AliasStrings(""))
2023-12-08 16:52:26 -05:00
if ranks.Len() == 1 {
c.log.Debug("Fuzzy found alias result",
c.log.Args(
"searchTerm", ranks[0].Source,
"foundAlias", ranks[0].Target,
"levenshteinDistance", ranks[0].Distance,
))
} else if ranks.Len() > 1 {
found := make([]string, ranks.Len())
for i, r := range ranks {
found[i] = r.Target
}
2023-12-09 23:45:30 -05:00
c.log.Debug("Fuzzy found multiple aliases, try being more specific",
2023-12-08 23:13:17 -05:00
c.log.Args("foundAliases", strings.Join(found, ", ")))
2023-12-08 16:52:26 -05:00
}
var aliases []*ProjectAlias
if ranks.Len() > 0 {
aliases = make([]*ProjectAlias, ranks.Len())
for i, r := range ranks {
aliases[i] = c.GetAliasByName(r.Target)
}
}
return aliases
}
// Returns all matching projects by fuzzy find term
// Matches NameWithNamespace and Aliases
2024-01-15 15:39:35 -05:00
func (c *Cache) FuzzyFindProjects(search string) []*projects.Project {
projects := make([]*projects.Project, 0, len(c.Projects))
for _, p := range c.Projects {
if fuzzy.MatchFold(search, p.NameWithNamespace) {
projects = append(projects, p)
continue
}
for _, a := range c.GetProjectAliases(p) {
if fuzzy.MatchFold(search, a.Alias) {
projects = append(projects, p)
continue
}
}
}
return projects
}