diff --git a/template/interpolate/funcs.go b/template/interpolate/funcs.go index 602702caf..51fcd0911 100644 --- a/template/interpolate/funcs.go +++ b/template/interpolate/funcs.go @@ -2,15 +2,18 @@ package interpolate import ( "errors" + "fmt" "os" "text/template" + "time" ) // Funcs are the interpolation funcs that are available within interpolations. var FuncGens = map[string]FuncGenerator{ - "env": funcGenEnv, - "pwd": funcGenPwd, - "user": funcGenUser, + "env": funcGenEnv, + "isotime": funcGenIsotime, + "pwd": funcGenPwd, + "user": funcGenUser, } // FuncGenerator is a function that given a context generates a template @@ -40,6 +43,20 @@ func funcGenEnv(ctx *Context) interface{} { } } +func funcGenIsotime(ctx *Context) interface{} { + return func(format ...string) (string, error) { + if len(format) == 0 { + return time.Now().UTC().Format(time.RFC3339), nil + } + + if len(format) > 1 { + return "", fmt.Errorf("too many values, 1 needed: %v", format) + } + + return time.Now().UTC().Format(format[0]), nil + } +} + func funcGenPwd(ctx *Context) interface{} { return func() (string, error) { return os.Getwd() diff --git a/template/interpolate/funcs_test.go b/template/interpolate/funcs_test.go index 7bd5c4647..ef0753e4f 100644 --- a/template/interpolate/funcs_test.go +++ b/template/interpolate/funcs_test.go @@ -3,6 +3,7 @@ package interpolate import ( "os" "testing" + "time" ) func TestFuncEnv(t *testing.T) { @@ -65,6 +66,25 @@ func TestFuncEnv_disable(t *testing.T) { } } +func TestFuncIsotime(t *testing.T) { + ctx := &Context{} + i := &I{Value: "{{isotime}}"} + result, err := i.Render(ctx) + if err != nil { + t.Fatalf("err: %s", err) + } + + val, err := time.Parse(time.RFC3339, result) + if err != nil { + t.Fatalf("err: %s", err) + } + + currentTime := time.Now().UTC() + if currentTime.Sub(val) > 2*time.Second { + t.Fatalf("val: %d (current: %d)", val, currentTime) + } +} + func TestFuncPwd(t *testing.T) { wd, err := os.Getwd() if err != nil {