sys-exporter/utils/utils.go

74 lines
1.7 KiB
Go
Raw Permalink Normal View History

2024-12-01 17:12:19 +00:00
package utils
import (
"errors"
"regexp"
)
// HandleRegexp handles a regex with named capture groups.
// If the given regexp does not have any named capture group, or if no match is found, an error is returned
// Matches are returned as a map which keys are the capture groups names
func HandleRegexp(dat string, pattern regexp.Regexp) (res []map[string]string, err error) {
namedGroups := 0
for _, n := range pattern.SubexpNames() {
if n != "" {
namedGroups++
}
}
if namedGroups == 0 {
return nil, errors.New("no named subgroup in pattern")
}
matches := pattern.FindAllStringSubmatch(dat, -1)
if matches == nil {
return nil, errors.New("no match found")
}
res = make([]map[string]string, 0)
for _, line := range matches {
subMatchMap := make(map[string]string)
for i, name := range pattern.SubexpNames() {
if i != 0 {
subMatchMap[name] = string(line[i])
}
}
res = append(res, subMatchMap)
}
return
}
// HandleKeyValRegexRes merges a list of maps containing result as a key/value format
//
// Input maps all have the following format:
//
// {
// "key": "some_key",
// "value": "some_val",
// }
//
// Final result will have the format
//
// {
// "some_key": "some_val",
// }
func HandleKeyValRegexRes(rawMatches []map[string]string) map[string]string {
matchedMap := make(map[string]string)
for _, m := range rawMatches {
currKey := ""
currVal := ""
for k, v := range m {
if k == "key" {
currKey = v
} else if k == "value" {
currVal = v
}
// All other keys are ignored
// Should not happen given the given regexp
}
if currKey != "" && currVal != "" {
matchedMap[currKey] = currVal
}
}
return matchedMap
}