1package stdlib
2
3import (
4	"regexp"
5	"strings"
6
7	"github.com/zclconf/go-cty/cty"
8	"github.com/zclconf/go-cty/cty/function"
9)
10
11// ReplaceFunc is a function that searches a given string for another given
12// substring, and replaces each occurence with a given replacement string.
13// The substr argument is a simple string.
14var ReplaceFunc = function.New(&function.Spec{
15	Params: []function.Parameter{
16		{
17			Name: "str",
18			Type: cty.String,
19		},
20		{
21			Name: "substr",
22			Type: cty.String,
23		},
24		{
25			Name: "replace",
26			Type: cty.String,
27		},
28	},
29	Type: function.StaticReturnType(cty.String),
30	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
31		str := args[0].AsString()
32		substr := args[1].AsString()
33		replace := args[2].AsString()
34
35		return cty.StringVal(strings.Replace(str, substr, replace, -1)), nil
36	},
37})
38
39// RegexReplaceFunc is a function that searches a given string for another
40// given substring, and replaces each occurence with a given replacement
41// string. The substr argument must be a valid regular expression.
42var RegexReplaceFunc = function.New(&function.Spec{
43	Params: []function.Parameter{
44		{
45			Name: "str",
46			Type: cty.String,
47		},
48		{
49			Name: "substr",
50			Type: cty.String,
51		},
52		{
53			Name: "replace",
54			Type: cty.String,
55		},
56	},
57	Type: function.StaticReturnType(cty.String),
58	Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
59		str := args[0].AsString()
60		substr := args[1].AsString()
61		replace := args[2].AsString()
62
63		re, err := regexp.Compile(substr)
64		if err != nil {
65			return cty.UnknownVal(cty.String), err
66		}
67
68		return cty.StringVal(re.ReplaceAllString(str, replace)), nil
69	},
70})
71
72// Replace searches a given string for another given substring,
73// and replaces all occurrences with a given replacement string.
74func Replace(str, substr, replace cty.Value) (cty.Value, error) {
75	return ReplaceFunc.Call([]cty.Value{str, substr, replace})
76}
77
78func RegexReplace(str, substr, replace cty.Value) (cty.Value, error) {
79	return RegexReplaceFunc.Call([]cty.Value{str, substr, replace})
80}
81