initrd/regexp.go

66 lines
1.3 KiB
Go
Raw Normal View History

package main
import (
"regexp"
2024-01-20 15:41:54 +00:00
"github.com/rs/zerolog/log"
)
2024-11-04 15:18:53 +00:00
type NameAliases struct {
Name string
Aliases []string
}
func nameAlias(name string) NameAliases {
return NameAliases{Name: name, Aliases: []string{name}}
}
func nameAliases(name string, aliases ...string) NameAliases {
na := NameAliases{Name: name, Aliases: make([]string, 0, len(aliases)+1)}
na.Aliases = append(na.Aliases, name)
for _, alias := range aliases {
na.AddAlias(alias)
}
2024-11-04 15:18:53 +00:00
return na
}
func (na *NameAliases) AddAlias(alias string) {
if alias == "" {
return
}
if contains(na.Aliases, func(s string) bool { return s == alias }) {
return
}
na.Aliases = append(na.Aliases, alias)
}
func regexpSelectN(n int, regexps []string, nameAliases []NameAliases) (matches []string) {
matches = make([]string, 0)
res := make([]*regexp.Regexp, 0, len(regexps))
for _, reStr := range regexps {
re, err := regexp.Compile(reStr)
if err != nil {
2024-01-20 15:41:54 +00:00
log.Warn().Err(err).Str("regexp", reStr).Msg("invalid regexp, ignored")
continue
}
res = append(res, re)
}
2024-11-04 15:18:53 +00:00
nameAliasesLoop:
for _, item := range nameAliases {
if len(matches) == n {
break
}
for _, re := range res {
2024-11-04 15:18:53 +00:00
for _, alias := range item.Aliases {
if re.MatchString(alias) {
matches = append(matches, item.Name)
continue nameAliasesLoop
}
}
}
}
return
}