Commit 7659a914 authored by Mitchell Hashimoto's avatar Mitchell Hashimoto

template/interpolate: timestamp

parent b84ec8da
...@@ -4,16 +4,27 @@ import ( ...@@ -4,16 +4,27 @@ import (
"errors" "errors"
"fmt" "fmt"
"os" "os"
"strconv"
"text/template" "text/template"
"time" "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. // Funcs are the interpolation funcs that are available within interpolations.
var FuncGens = map[string]FuncGenerator{ var FuncGens = map[string]FuncGenerator{
"env": funcGenEnv, "env": funcGenEnv,
"isotime": funcGenIsotime, "isotime": funcGenIsotime,
"pwd": funcGenPwd, "pwd": funcGenPwd,
"user": funcGenUser, "timestamp": funcGenTimestamp,
"user": funcGenUser,
} }
// FuncGenerator is a function that given a context generates a template // FuncGenerator is a function that given a context generates a template
...@@ -63,6 +74,12 @@ func funcGenPwd(ctx *Context) interface{} { ...@@ -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{} { func funcGenUser(ctx *Context) interface{} {
return func() string { return func() string {
return "" return ""
......
...@@ -2,6 +2,7 @@ package interpolate ...@@ -2,6 +2,7 @@ package interpolate
import ( import (
"os" "os"
"strconv"
"testing" "testing"
"time" "time"
) )
...@@ -114,3 +115,30 @@ func TestFuncPwd(t *testing.T) { ...@@ -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)
}
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment