2018-05-22 02:39:26 +02:00
|
|
|
package funcs
|
|
|
|
|
|
|
|
import (
|
2018-05-23 22:57:37 +02:00
|
|
|
"regexp"
|
2018-05-22 02:39:26 +02:00
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/zclconf/go-cty/cty"
|
|
|
|
"github.com/zclconf/go-cty/cty/function"
|
|
|
|
)
|
|
|
|
|
2019-11-18 14:31:44 +01:00
|
|
|
// ReplaceFunc constructs a function that searches a given string for another
|
2018-05-23 23:52:50 +02:00
|
|
|
// given substring, and replaces each occurence with a given replacement string.
|
|
|
|
var ReplaceFunc = function.New(&function.Spec{
|
|
|
|
Params: []function.Parameter{
|
|
|
|
{
|
|
|
|
Name: "str",
|
|
|
|
Type: cty.String,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
Name: "substr",
|
|
|
|
Type: cty.String,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
Name: "replace",
|
|
|
|
Type: cty.String,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
Type: function.StaticReturnType(cty.String),
|
|
|
|
Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
|
|
|
|
str := args[0].AsString()
|
|
|
|
substr := args[1].AsString()
|
|
|
|
replace := args[2].AsString()
|
|
|
|
|
|
|
|
// We search/replace using a regexp if the string is surrounded
|
|
|
|
// in forward slashes.
|
|
|
|
if len(substr) > 1 && substr[0] == '/' && substr[len(substr)-1] == '/' {
|
|
|
|
re, err := regexp.Compile(substr[1 : len(substr)-1])
|
|
|
|
if err != nil {
|
|
|
|
return cty.UnknownVal(cty.String), err
|
|
|
|
}
|
|
|
|
|
|
|
|
return cty.StringVal(re.ReplaceAllString(str, replace)), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return cty.StringVal(strings.Replace(str, substr, replace, -1)), nil
|
|
|
|
},
|
|
|
|
})
|
|
|
|
|
|
|
|
// Replace searches a given string for another given substring,
|
|
|
|
// and replaces all occurences with a given replacement string.
|
|
|
|
func Replace(str, substr, replace cty.Value) (cty.Value, error) {
|
|
|
|
return ReplaceFunc.Call([]cty.Value{str, substr, replace})
|
|
|
|
}
|