github.com/khulnasoft-lab/defsec@v1.0.5-0.20230827010352-5e9f46893d95/pkg/scanners/terraform/parser/funcs/string.go (about) 1 // Copied from github.com/hashicorp/terraform/internal/lang/funcs 2 package funcs 3 4 import ( 5 "regexp" 6 "strings" 7 8 "github.com/zclconf/go-cty/cty" 9 "github.com/zclconf/go-cty/cty/function" 10 ) 11 12 // ReplaceFunc constructs a function that searches a given string for another 13 // given substring, and replaces each occurrence with a given replacement string. 14 var 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) (ret cty.Value, err error) { 31 str := args[0].AsString() 32 substr := args[1].AsString() 33 replace := args[2].AsString() 34 35 // We search/replace using a regexp if the string is surrounded 36 // in forward slashes. 37 if len(substr) > 1 && substr[0] == '/' && substr[len(substr)-1] == '/' { 38 re, err := regexp.Compile(substr[1 : len(substr)-1]) 39 if err != nil { 40 return cty.UnknownVal(cty.String), err 41 } 42 43 return cty.StringVal(re.ReplaceAllString(str, replace)), nil 44 } 45 46 return cty.StringVal(strings.Replace(str, substr, replace, -1)), nil 47 }, 48 }) 49 50 // Replace searches a given string for another given substring, 51 // and replaces all occurrences with a given replacement string. 52 func Replace(str, substr, replace cty.Value) (cty.Value, error) { 53 return ReplaceFunc.Call([]cty.Value{str, substr, replace}) 54 }