From 7659a91445b1e63ea614dcb715d54dac008c307d Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Fri, 15 May 2015 21:14:41 -0700 Subject: [PATCH] template/interpolate: timestamp --- template/interpolate/funcs.go | 25 +++++++++++++++++++++---- template/interpolate/funcs_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 4 deletions(-) diff --git a/template/interpolate/funcs.go b/template/interpolate/funcs.go index 51fcd0911..ead8eb95e 100644 --- a/template/interpolate/funcs.go +++ b/template/interpolate/funcs.go @@ -4,16 +4,27 @@ import ( "errors" "fmt" "os" + "strconv" "text/template" "time" ) +// InitTime is the UTC time when this package was initialized. It is +// used as the timestamp for all configuration templates so that they +// match for a single build. +var InitTime time.Time + +func init() { + InitTime = time.Now().UTC() +} + // Funcs are the interpolation funcs that are available within interpolations. var FuncGens = map[string]FuncGenerator{ - "env": funcGenEnv, - "isotime": funcGenIsotime, - "pwd": funcGenPwd, - "user": funcGenUser, + "env": funcGenEnv, + "isotime": funcGenIsotime, + "pwd": funcGenPwd, + "timestamp": funcGenTimestamp, + "user": funcGenUser, } // FuncGenerator is a function that given a context generates a template @@ -63,6 +74,12 @@ func funcGenPwd(ctx *Context) interface{} { } } +func funcGenTimestamp(ctx *Context) interface{} { + return func() string { + return strconv.FormatInt(InitTime.Unix(), 10) + } +} + func funcGenUser(ctx *Context) interface{} { return func() string { return "" diff --git a/template/interpolate/funcs_test.go b/template/interpolate/funcs_test.go index ef0753e4f..37dee1ad6 100644 --- a/template/interpolate/funcs_test.go +++ b/template/interpolate/funcs_test.go @@ -2,6 +2,7 @@ package interpolate import ( "os" + "strconv" "testing" "time" ) @@ -114,3 +115,30 @@ func TestFuncPwd(t *testing.T) { } } } + +func TestFuncTimestamp(t *testing.T) { + expected := strconv.FormatInt(InitTime.Unix(), 10) + + cases := []struct { + Input string + Output string + }{ + { + `{{timestamp}}`, + expected, + }, + } + + ctx := &Context{} + for _, tc := range cases { + i := &I{Value: tc.Input} + result, err := i.Render(ctx) + if err != nil { + t.Fatalf("Input: %s\n\nerr: %s", tc.Input, err) + } + + if result != tc.Output { + t.Fatalf("Input: %s\n\nGot: %s", tc.Input, result) + } + } +}