Commit b84ec8da authored by Mitchell Hashimoto's avatar Mitchell Hashimoto

template/interpolate: isotime

parent 5d205ec1
......@@ -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()
......
......@@ -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 {
......
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