1
0
Fork 0
mirror of https://github.com/kubernetes-sigs/node-feature-discovery.git synced 2025-03-28 02:37:11 +00:00

pkg/apis/nfd: helpers for handling templates in Rule names

Implement a private helper type (nameTemplateHelper) for handling
(executing and caching) of templated names. DeepCopy methods are
manually implemented as controller-gen is not able to help with that.
This commit is contained in:
Markus Lehtonen 2021-05-17 21:50:26 +03:00
parent ad933e44b4
commit 085af7c2c7

View file

@ -17,7 +17,9 @@ limitations under the License.
package v1alpha1
import (
"bytes"
"strings"
"text/template"
"fmt"
@ -98,3 +100,64 @@ func (m *FeatureMatcher) match(features map[string]*feature.DomainFeatures) (boo
}
return true, nil
}
type templateHelper struct {
template *template.Template
}
func newTemplateHelper(name string) (*templateHelper, error) {
tmpl, err := template.New("").Option("missingkey=error").Parse(name)
if err != nil {
return nil, fmt.Errorf("invalid template: %w", err)
}
return &templateHelper{template: tmpl}, nil
}
// DeepCopy is a stub to augment the auto-generated code
func (in *templateHelper) DeepCopy() *templateHelper {
if in == nil {
return nil
}
out := new(templateHelper)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is a stub to augment the auto-generated code
func (in *templateHelper) DeepCopyInto(out *templateHelper) {
// HACK: just re-use the template
out.template = in.template
}
func (h *templateHelper) execute(data interface{}) (string, error) {
var tmp bytes.Buffer
if err := h.template.Execute(&tmp, data); err != nil {
return "", err
}
return tmp.String(), nil
}
// expandMap is a helper for expanding a template in to a map of strings. Data
// after executing the template is expexted to be key=value pairs separated by
// newlines.
func (h *templateHelper) expandMap(data interface{}) (map[string]string, error) {
expanded, err := h.execute(data)
if err != nil {
return nil, err
}
// Split out individual key-value pairs
out := make(map[string]string)
for _, item := range strings.Split(expanded, "\n") {
// Remove leading/trailing whitespace and skip empty lines
if trimmed := strings.TrimSpace(item); trimmed != "" {
split := strings.SplitN(trimmed, "=", 2)
if len(split) == 1 {
out[split[0]] = ""
} else {
out[split[0]] = split[1]
}
}
}
return out, nil
}