From 7610874264b0c39c119c52d6d1821677ad6bd4f1 Mon Sep 17 00:00:00 2001 From: Anthony Stanton Date: Tue, 15 Sep 2015 09:34:57 +0200 Subject: [PATCH] Initial implementation of compact() interpolation function --- config/interpolate_funcs.go | 17 +++++++++++++++++ config/string_list.go | 13 +++++++++++++ 2 files changed, 30 insertions(+) diff --git a/config/interpolate_funcs.go b/config/interpolate_funcs.go index abaa9817c1..67523ddb2b 100644 --- a/config/interpolate_funcs.go +++ b/config/interpolate_funcs.go @@ -30,6 +30,7 @@ func init() { "length": interpolationFuncLength(), "replace": interpolationFuncReplace(), "split": interpolationFuncSplit(), + "compact": interpolationFuncCompact(), "base64encode": interpolationFuncBase64Encode(), "base64decode": interpolationFuncBase64Decode(), } @@ -279,6 +280,22 @@ func interpolationFuncSplit() ast.Function { } } +// interpolationFuncCompact strips a list of values (e.g. as returned by +// "split") of any empty strings +func interpolationFuncCompact() ast.Function { + return ast.Function{ + ArgTypes: []ast.Type{ast.TypeString}, + ReturnType: ast.TypeString, + Variadic: false, + Callback: func(args []interface{}) (interface{}, error) { + if !IsStringList(args[0].(string)) { + return args[0].(string), nil + } + return CompactStringList(StringList(args[0].(string))).String(), nil + }, + } +} + // interpolationFuncLookup implements the "lookup" function that allows // dynamic lookups of map types within a Terraform configuration. func interpolationFuncLookup(vs map[string]ast.Variable) ast.Function { diff --git a/config/string_list.go b/config/string_list.go index 70d43d1e4b..d4d1850d05 100644 --- a/config/string_list.go +++ b/config/string_list.go @@ -74,3 +74,16 @@ func (sl StringList) String() string { func IsStringList(s string) bool { return strings.Contains(s, stringListDelim) } + +func CompactStringList(sl StringList) StringList { + parts := sl.Slice() + + var newlist []string + // drop the empty strings + for i := range parts { + if parts[i] != "" { + newlist = append(newlist, parts[i]) + } + } + return NewStringList(newlist) +}