template/interpolate: timestamp
This commit is contained in:
parent
b84ec8da4b
commit
7659a91445
|
@ -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 ""
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue