Commit cd29c8d5 authored by Nika Jones's avatar Nika Jones

Fixes #1092, Adds a format option to the {{isotime}} variable.

Now using the golang magic date: Mon Jan 2 15:04:05 -0700 MST 2006
One can format the time like:

    {{isotime "2006-01-02"}} == "YYYY-MM-DD"
    {{isotime "060102-15"}}  == "YYMMDD-HH" (24-hour clock)
    {{isotime "060102-3"}}   == "YYMMDD-H"  (12-hour clock)

Using {{isotime}} as a standalone variable doesn't change. It still returns RFC3339 formatted time.
parent 7b090528
...@@ -110,8 +110,16 @@ func templateEnv(n string) string { ...@@ -110,8 +110,16 @@ func templateEnv(n string) string {
return os.Getenv(n) return os.Getenv(n)
} }
func templateISOTime() string { func templateISOTime(timeFormat ...string) (string, error) {
return time.Now().UTC().Format(time.RFC3339) if len(timeFormat) == 0 {
return time.Now().UTC().Format(time.RFC3339), nil
}
if len(timeFormat) > 1 {
return "", fmt.Errorf("too many values, 1 needed: %v", timeFormat)
}
return time.Now().UTC().Format(timeFormat[0]), nil
} }
func templatePwd() (string, error) { func templatePwd() (string, error) {
......
package packer package packer
import ( import (
"fmt"
"math" "math"
"os" "os"
"strconv" "strconv"
...@@ -42,6 +43,33 @@ func TestConfigTemplateProcess_isotime(t *testing.T) { ...@@ -42,6 +43,33 @@ func TestConfigTemplateProcess_isotime(t *testing.T) {
} }
} }
// Note must format with the magic Date: Mon Jan 2 15:04:05 -0700 MST 2006
func TestConfigTemplateProcess_isotime_withFormat(t *testing.T) {
tpl, err := NewConfigTemplate()
if err != nil {
t.Fatalf("err: %s", err)
}
// Checking for a too-many arguments error
// Because of the variadic function, compile time checking won't work
_, err = tpl.Process(`{{isotime "20060102" "huh"}}`, nil)
if err == nil {
t.Fatalf("err: cannot have more than 1 input")
}
result, err := tpl.Process(`{{isotime "20060102"}}`, nil)
if err != nil {
t.Fatalf("err: %s", err)
}
ti := time.Now().UTC()
val := fmt.Sprintf("%04d%02d%02d", ti.Year(), ti.Month(), ti.Day())
if result != val {
t.Fatalf("val: %s (formated: %s)", val, result)
}
}
func TestConfigTemplateProcess_pwd(t *testing.T) { func TestConfigTemplateProcess_pwd(t *testing.T) {
tpl, err := NewConfigTemplate() tpl, err := NewConfigTemplate()
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