Debian Codegraph @

tpl/collections/apply.go

raw
1 // Copyright 2017 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package collections
15
16 import (
17 "context"
18 "errors"
19 "fmt"
20 "reflect"
21 "strings"
22
23 "github.com/gohugoio/hugo/common/hreflect"
24 )
25
26 // Apply takes an array or slice c and returns a new slice with the function fname applied over it.
27 func (ns *Namespace) Apply(ctx context.Context, c any, fname string, args ...any) (any, error) {
28 if c == nil {
29 return make([]any, 0), nil
30 }
31
32 if fname == "apply" {
33 return nil, errors.New("can't apply myself (no turtles allowed)")
34 }
35
36 seqv := reflect.ValueOf(c)
37 seqv, isNil := hreflect.Indirect(seqv)
38 if isNil {
39 return nil, errors.New("can't iterate over a nil value")
40 }
41
42 fnv, found := ns.lookupFunc(ctx, fname)
43 if !found {
44 return nil, errors.New("can't find function " + fname)
45 }
46
47 switch seqv.Kind() {
48 case reflect.Array, reflect.Slice:
49 r := make([]any, seqv.Len())
50 for i := range seqv.Len() {
51 vv := seqv.Index(i)
52
53 vvv, err := applyFnToThis(ctx, fnv, vv, args...)
54 if err != nil {
55 return nil, err
56 }
57
58 r[i] = vvv.Interface()
59 }
60
61 return r, nil
62 default:
63 return nil, fmt.Errorf("can't apply over %v", c)
64 }
65 }
66
67 var typeOfReflectValue = reflect.TypeFor[reflect.Value]()
68
69 func applyFnToThis(ctx context.Context, fn, this reflect.Value, args ...any) (reflect.Value, error) {
70 num := fn.Type().NumIn()
71 if num > 0 && hreflect.IsContextType(fn.Type().In(0)) {
72 args = append([]any{ctx}, args...)
73 }
74
75 n := make([]reflect.Value, len(args))
76 for i, arg := range args {
77 if arg == "." {
78 n[i] = this
79 } else {
80 n[i] = reflect.ValueOf(arg)
81 }
82 }
83
84 if fn.Type().IsVariadic() {
85 num--
86 }
87
88 // TODO(bep) see #1098 - also see template_tests.go
89 /*if len(args) < num {
90 return reflect.ValueOf(nil), errors.New("Too few arguments")
91 } else if len(args) > num {
92 return reflect.ValueOf(nil), errors.New("Too many arguments")
93 }*/
94
95 for i := range num {
96 // Go's built-in template funcs (e.g. len) use reflect.Value as argument type.
97 if fn.Type().In(i) == typeOfReflectValue && n[i].Type() != typeOfReflectValue {
98 n[i] = reflect.ValueOf(n[i])
99 }
100
101 if xt, targ := n[i].Type(), fn.Type().In(i); !xt.AssignableTo(targ) {
102 return reflect.ValueOf(nil), errors.New("called apply using " + xt.String() + " as type " + targ.String())
103 }
104 }
105
106 res := fn.Call(n)
107
108 if len(res) == 1 || res[1].IsNil() {
109 return res[0], nil
110 }
111 return reflect.ValueOf(nil), res[1].Interface().(error)
112 }
113
114 func (ns *Namespace) lookupFunc(ctx context.Context, fname string) (reflect.Value, bool) {
115 namespace, methodName, ok := strings.Cut(fname, ".")
116 if !ok {
117 return ns.deps.GetTemplateStore().GetFunc(fname)
118 }
119
120 // Namespace
121 nv, found := ns.lookupFunc(ctx, namespace)
122 if !found {
123 return reflect.Value{}, false
124 }
125
126 fn, ok := nv.Interface().(func(context.Context, ...any) (any, error))
127 if !ok {
128 return reflect.Value{}, false
129 }
130 v, err := fn(ctx)
131 if err != nil {
132 panic(err)
133 }
134 nv = reflect.ValueOf(v)
135
136 // method
137 m := hreflect.GetMethodByName(nv, methodName)
138
139 if m.Kind() == reflect.Invalid {
140 return reflect.Value{}, false
141 }
142 return m, true
143 }