tpl/time: Support overlapping namespace and template func
authorCameron Moore <moorereason@gmail.com>
Wed, 10 May 2017 01:24:23 +0000 (20:24 -0500)
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Fri, 19 May 2017 21:00:20 +0000 (00:00 +0300)
Fixes #3421

tpl/time/init.go
tpl/time/init_test.go

index 33f8a7dbb59acdc6bf7f25a607f587d087a9d2e5..9f9cf275fcf72f121982e9db27d6d7386e81ca51 100644 (file)
@@ -25,8 +25,26 @@ func init() {
                ctx := New()
 
                ns := &internal.TemplateFuncsNamespace{
-                       Name:    name,
-                       Context: func() interface{} { return ctx },
+                       Name: name,
+                       Context: func(v ...interface{}) interface{} {
+                               // Handle overlapping "time" namespace and func.
+                               //
+                               // If no args are passed to `time`, assume namespace usage and
+                               // return namespace context.
+                               //
+                               // If args are passed, show a deprecation warning and attempt to
+                               // simulate the old "as time" behavior.
+
+                               if len(v) == 0 {
+                                       return ctx
+                               }
+
+                               t, err := ctx.AsTime(v[0])
+                               if err != nil {
+                                       return err
+                               }
+                               return t
+                       },
                }
 
                ns.AddMethodMapping(ctx.Format,
@@ -42,7 +60,7 @@ func init() {
                )
 
                ns.AddMethodMapping(ctx.AsTime,
-                       []string{"asTime"}, // TODO(bep) handle duplicate
+                       []string{"asTime"},
                        [][2]string{
                                {`{{ (asTime "2015-01-21").Year }}`, `2015`},
                        },
index a41d8e4f33c18ca0e1893f0298919c7de0032fc4..fd49dc4be70c79c86aa2314109f6ca2e40968abf 100644 (file)
@@ -34,5 +34,5 @@ func TestInit(t *testing.T) {
        }
 
        require.True(t, found)
-       require.IsType(t, &Namespace{}, ns.Context.(func() interface{})())
+       require.IsType(t, &Namespace{}, ns.Context.(func(v ...interface{}) interface{})())
 }