replace sed usage with replace and replace_all funcs

This commit is contained in:
Adrien Delorme 2019-09-17 16:02:05 +02:00
parent a279d2e071
commit feb3da4f56
2 changed files with 26 additions and 32 deletions

View File

@ -14,7 +14,6 @@ import (
"github.com/hashicorp/packer/common/uuid"
"github.com/hashicorp/packer/version"
vaultapi "github.com/hashicorp/vault/api"
"github.com/rwtodd/Go.Sed/sed"
)
// InitTime is the UTC time when this package was initialized. It is
@ -41,7 +40,9 @@ var FuncGens = map[string]interface{}{
"packer_version": funcGenPackerVersion,
"consul_key": funcGenConsul,
"vault": funcGenVault,
"sed": funcGenSed,
"replace": replace,
"replace_all": replace_all,
"upper": strings.ToUpper,
"lower": strings.ToLower,
@ -265,24 +266,10 @@ func funcGenVault(ctx *Context) interface{} {
}
}
func funcGenSed(ctx *Context) interface{} {
return func(expression string, inputString string) (string, error) {
engine, err := sed.New(strings.NewReader(expression))
if err != nil {
return "", err
}
result, err := engine.RunString(inputString)
if err != nil {
return "", err
}
// The sed library adds a \n to all processed strings.
resultLength := len(result)
result = result[:resultLength-1]
return result, err
}
func replace_all(old, new, src string) string {
return strings.ReplaceAll(src, old, new)
}
func replace(old, new string, n int, src string) string {
return strings.Replace(src, old, new, n)
}

View File

@ -8,6 +8,7 @@ import (
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/hashicorp/packer/version"
)
@ -316,30 +317,36 @@ func TestFuncPackerVersion(t *testing.T) {
}
}
func TestFuncSed(t *testing.T) {
func TestReplaceFuncs(t *testing.T) {
cases := []struct {
Input string
Output string
}{
{
`{{sed "s|hello|world|" "hello"}}`,
`world`,
`{{ "foo-bar-baz" | replace "-" "/" 1}}`,
`foo/bar-baz`,
},
{
`{{sed "s|foo|bar|" "hello"}}`,
`hello`,
`{{ replace "-" "/" 1 "foo-bar-baz" }}`,
`foo/bar-baz`,
},
{
`{{user "foo" | sed "s|foo|bar|"}}`,
`bar`,
`{{ "I Am Henry VIII" | replace_all " " "-" }}`,
`I-Am-Henry-VIII`,
},
{
`{{ replace_all " " "-" "I Am Henry VIII" }}`,
`I-Am-Henry-VIII`,
},
}
ctx := &Context{
UserVariables: map[string]string{
"foo": "foo",
"fee": "-foo-",
},
}
for _, tc := range cases {
@ -349,8 +356,8 @@ func TestFuncSed(t *testing.T) {
t.Fatalf("Input: %s\n\nerr: %s", tc.Input, err)
}
if result != tc.Output {
t.Fatalf("Input: %s\n\nGot: %s", tc.Input, result)
if diff := cmp.Diff(tc.Output, result); diff != "" {
t.Fatalf("Unexpected output: %s", diff)
}
}
}