From 664ba5f5a6f1095a8f24583ba50172c0e1f893a4 Mon Sep 17 00:00:00 2001 From: Radek Simko Date: Tue, 23 Feb 2016 11:29:11 +0000 Subject: [PATCH] config: Add new interpolation function - md5 --- config/interpolate_funcs.go | 16 ++++++++++++++++ config/interpolate_funcs_test.go | 22 ++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/config/interpolate_funcs.go b/config/interpolate_funcs.go index c28b694f9..d36bc65ea 100644 --- a/config/interpolate_funcs.go +++ b/config/interpolate_funcs.go @@ -2,6 +2,7 @@ package config import ( "bytes" + "crypto/md5" "crypto/sha1" "crypto/sha256" "encoding/base64" @@ -40,6 +41,7 @@ func Funcs() map[string]ast.Function { "join": interpolationFuncJoin(), "length": interpolationFuncLength(), "lower": interpolationFuncLower(), + "md5": interpolationFuncMd5(), "replace": interpolationFuncReplace(), "sha1": interpolationFuncSha1(), "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 // string upper casing. func interpolationFuncUpper() ast.Function { diff --git a/config/interpolate_funcs_test.go b/config/interpolate_funcs_test.go index 86f738ed6..2a2981b76 100644 --- a/config/interpolate_funcs_test.go +++ b/config/interpolate_funcs_test.go @@ -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 { Cases []testFunctionCase Vars map[string]ast.Variable