From f1d4bd983a62da2727245a355471fcb17d7115e2 Mon Sep 17 00:00:00 2001 From: Joshua Williams Date: Fri, 7 Aug 2020 16:59:57 -0400 Subject: [PATCH] Add template functions (#84) * Added a default function for plugin templates * Updated changelog --- CHANGELOG.md | 1 + operator/plugin.go | 17 ++++++++++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b3d57a886..3855421e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Unreleased ### Fixed - Google Cloud Output failure when sent a field of type uint16 +- Added a default function to plugin templates ## [0.9.7] - 2020-08-05 ### Changed diff --git a/operator/plugin.go b/operator/plugin.go index 4441e7efe..97a2a602f 100644 --- a/operator/plugin.go +++ b/operator/plugin.go @@ -127,7 +127,7 @@ func (r PluginRegistry) Add(pluginType string, contents string) error { return fmt.Errorf("plugin type %s already exists as a builtin plugin", pluginType) } - pluginTemplate, err := template.New(pluginType).Parse(contents) + pluginTemplate, err := template.New(pluginType).Funcs(pluginFuncs()).Parse(contents) if err != nil { return fmt.Errorf("failed to parse %s as a plugin template: %s", pluginType, err) } @@ -144,3 +144,18 @@ func NewPluginRegistry(dir string) (PluginRegistry, error) { } return registry, nil } + +// pluginFuncs returns a map of custom plugin functions used for templating. +func pluginFuncs() template.FuncMap { + funcs := make(map[string]interface{}) + funcs["default"] = defaultPluginFunc + return funcs +} + +// defaultPluginFunc is a plugin function that returns a default value if the supplied value is nil. +func defaultPluginFunc(def interface{}, val interface{}) interface{} { + if val == nil { + return def + } + return val +}