Commit b84ec8da authored by Mitchell Hashimoto's avatar Mitchell Hashimoto

template/interpolate: isotime

parent 5d205ec1
...@@ -2,13 +2,16 @@ package interpolate ...@@ -2,13 +2,16 @@ package interpolate
import ( import (
"errors" "errors"
"fmt"
"os" "os"
"text/template" "text/template"
"time"
) )
// 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,
"pwd": funcGenPwd, "pwd": funcGenPwd,
"user": funcGenUser, "user": funcGenUser,
} }
...@@ -40,6 +43,20 @@ func funcGenEnv(ctx *Context) interface{} { ...@@ -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{} { func funcGenPwd(ctx *Context) interface{} {
return func() (string, error) { return func() (string, error) {
return os.Getwd() return os.Getwd()
......
...@@ -3,6 +3,7 @@ package interpolate ...@@ -3,6 +3,7 @@ package interpolate
import ( import (
"os" "os"
"testing" "testing"
"time"
) )
func TestFuncEnv(t *testing.T) { func TestFuncEnv(t *testing.T) {
...@@ -65,6 +66,25 @@ func TestFuncEnv_disable(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) { func TestFuncPwd(t *testing.T) {
wd, err := os.Getwd() wd, err := os.Getwd()
if err != nil { 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