config: Add new interpolation function - md5

This commit is contained in:
Radek Simko 2016-02-23 11:29:11 +00:00
parent 573d3bd7ab
commit 664ba5f5a6
2 changed files with 38 additions and 0 deletions

View File

@ -2,6 +2,7 @@ package config
import ( import (
"bytes" "bytes"
"crypto/md5"
"crypto/sha1" "crypto/sha1"
"crypto/sha256" "crypto/sha256"
"encoding/base64" "encoding/base64"
@ -40,6 +41,7 @@ func Funcs() map[string]ast.Function {
"join": interpolationFuncJoin(), "join": interpolationFuncJoin(),
"length": interpolationFuncLength(), "length": interpolationFuncLength(),
"lower": interpolationFuncLower(), "lower": interpolationFuncLower(),
"md5": interpolationFuncMd5(),
"replace": interpolationFuncReplace(), "replace": interpolationFuncReplace(),
"sha1": interpolationFuncSha1(), "sha1": interpolationFuncSha1(),
"sha256": interpolationFuncSha256(), "sha256": interpolationFuncSha256(),
@ -599,6 +601,20 @@ func interpolationFuncLower() ast.Function {
} }
} }
func interpolationFuncMd5() ast.Function {
return ast.Function{
ArgTypes: []ast.Type{ast.TypeString},
ReturnType: ast.TypeString,
Callback: func(args []interface{}) (interface{}, error) {
s := args[0].(string)
h := md5.New()
h.Write([]byte(s))
hash := hex.EncodeToString(h.Sum(nil))
return hash, nil
},
}
}
// interpolationFuncUpper implements the "upper" function that does // interpolationFuncUpper implements the "upper" function that does
// string upper casing. // string upper casing.
func interpolationFuncUpper() ast.Function { func interpolationFuncUpper() ast.Function {

View File

@ -923,6 +923,28 @@ func TestInterpolateFuncBase64Sha256(t *testing.T) {
}) })
} }
func TestInterpolateFuncMd5(t *testing.T) {
testFunction(t, testFunctionConfig{
Cases: []testFunctionCase{
{
`${md5("tada")}`,
"ce47d07243bb6eaf5e1322c81baf9bbf",
false,
},
{ // Confirm that we're not trimming any whitespaces
`${md5(" tada ")}`,
"aadf191a583e53062de2d02c008141c4",
false,
},
{ // We accept empty string too
`${md5("")}`,
"d41d8cd98f00b204e9800998ecf8427e",
false,
},
},
})
}
type testFunctionConfig struct { type testFunctionConfig struct {
Cases []testFunctionCase Cases []testFunctionCase
Vars map[string]ast.Variable Vars map[string]ast.Variable