Debian Codegraph @

tpl/internal/templatefuncsRegistry.go

raw
1 // Copyright 2017-present The Hugo Authors. All rights reserved.
2 //
3 // Portions Copyright The Go Authors.
4
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15
16 package internal
17
18 import (
19 "bytes"
20 "context"
21 "encoding/json"
22 "fmt"
23 "go/ast"
24 "go/doc"
25 "go/parser"
26 "go/token"
27 "log"
28 "os"
29 "path/filepath"
30 "reflect"
31 "runtime"
32 "strings"
33 "sync"
34
35 "github.com/gohugoio/hugo/deps"
36 )
37
38 // TemplateFuncsNamespaceRegistry describes a registry of functions that provide
39 // namespaces.
40 var TemplateFuncsNamespaceRegistry []func(d *deps.Deps) *TemplateFuncsNamespace
41
42 // AddTemplateFuncsNamespace adds a given function to a registry.
43 func AddTemplateFuncsNamespace(ns func(d *deps.Deps) *TemplateFuncsNamespace) {
44 TemplateFuncsNamespaceRegistry = append(TemplateFuncsNamespaceRegistry, ns)
45 }
46
47 // TemplateFuncsNamespace represents a template function namespace.
48 type TemplateFuncsNamespace struct {
49 // The namespace name, "strings", "lang", etc.
50 Name string
51
52 // This is the method receiver.
53 Context func(ctx context.Context, v ...any) (any, error)
54
55 // OnCreated is called when all the namespaces are ready.
56 OnCreated func(namespaces map[string]any)
57
58 // Additional info, aliases and examples, per method name.
59 MethodMappings map[string]TemplateFuncMethodMapping
60 }
61
62 // TemplateFuncsNamespaces is a slice of TemplateFuncsNamespace.
63 type TemplateFuncsNamespaces []*TemplateFuncsNamespace
64
65 // AddMethodMapping adds a method to a template function namespace.
66 func (t *TemplateFuncsNamespace) AddMethodMapping(m any, aliases []string, examples [][2]string) {
67 if t.MethodMappings == nil {
68 t.MethodMappings = make(map[string]TemplateFuncMethodMapping)
69 }
70
71 name := methodToName(m)
72
73 // Rewrite §§ to ` in example commands.
74 for i, e := range examples {
75 examples[i][0] = strings.ReplaceAll(e[0], "§§", "`")
76 }
77
78 // sanity check
79 for _, e := range examples {
80 if e[0] == "" {
81 panic(t.Name + ": Empty example for " + name)
82 }
83 }
84 for _, a := range aliases {
85 if a == "" {
86 panic(t.Name + ": Empty alias for " + name)
87 }
88 }
89
90 t.MethodMappings[name] = TemplateFuncMethodMapping{
91 Method: m,
92 Aliases: aliases,
93 Examples: examples,
94 }
95 }
96
97 // TemplateFuncMethodMapping represents a mapping of functions to methods for a
98 // given namespace.
99 type TemplateFuncMethodMapping struct {
100 Method any
101
102 // Any template funcs aliases. This is mainly motivated by keeping
103 // backwards compatibility, but some new template funcs may also make
104 // sense to give short and snappy aliases.
105 // Note that these aliases are global and will be merged, so the last
106 // key will win.
107 Aliases []string
108
109 // A slice of input/expected examples.
110 // We keep it a the namespace level for now, but may find a way to keep track
111 // of the single template func, for documentation purposes.
112 // Some of these, hopefully just a few, may depend on some test data to run.
113 Examples [][2]string
114 }
115
116 func methodToName(m any) string {
117 name := runtime.FuncForPC(reflect.ValueOf(m).Pointer()).Name()
118 name = filepath.Ext(name)
119 name = strings.TrimPrefix(name, ".")
120 name = strings.TrimSuffix(name, "-fm")
121 return name
122 }
123
124 type goDocFunc struct {
125 Name string
126 Description string
127 Args []string
128 Aliases []string
129 Examples [][2]string
130 }
131
132 func (t goDocFunc) toJSON() ([]byte, error) {
133 args, err := json.Marshal(t.Args)
134 if err != nil {
135 return nil, err
136 }
137 aliases, err := json.Marshal(t.Aliases)
138 if err != nil {
139 return nil, err
140 }
141 examples, err := json.Marshal(t.Examples)
142 if err != nil {
143 return nil, err
144 }
145 var buf bytes.Buffer
146 buf.WriteString(fmt.Sprintf(`%q:
147 { "Description": %q, "Args": %s, "Aliases": %s, "Examples": %s }
148 `, t.Name, t.Description, args, aliases, examples))
149
150 return buf.Bytes(), nil
151 }
152
153 // ToMap returns a limited map representation of the namespaces.
154 func (namespaces TemplateFuncsNamespaces) ToMap() map[string]any {
155 m := make(map[string]any)
156 for _, ns := range namespaces {
157 mm := make(map[string]any)
158 for name, mapping := range ns.MethodMappings {
159 mm[name] = map[string]any{
160 "Examples": mapping.Examples,
161 "Aliases": mapping.Aliases,
162 }
163 }
164 m[ns.Name] = mm
165 }
166 return m
167 }
168
169 // MarshalJSON returns the JSON encoding of namespaces.
170 func (namespaces TemplateFuncsNamespaces) MarshalJSON() ([]byte, error) {
171 var buf bytes.Buffer
172
173 buf.WriteString("{")
174
175 for i, ns := range namespaces {
176
177 b, err := ns.toJSON(context.Background())
178 if err != nil {
179 return nil, err
180 }
181 if b != nil {
182 if i != 0 {
183 buf.WriteString(",")
184 }
185 buf.Write(b)
186 }
187 }
188
189 buf.WriteString("}")
190
191 return buf.Bytes(), nil
192 }
193
194 var ignoreFuncs = map[string]bool{
195 "Reset": true,
196 }
197
198 func (t *TemplateFuncsNamespace) toJSON(ctx context.Context) ([]byte, error) {
199 var buf bytes.Buffer
200
201 godoc := getGetTplPackagesGoDoc()[t.Name]
202
203 var funcs []goDocFunc
204
205 buf.WriteString(fmt.Sprintf(`%q: {`, t.Name))
206
207 tctx, err := t.Context(ctx)
208 if err != nil {
209 return nil, err
210 }
211 if tctx == nil {
212 // E.g. page.
213 // We should fix this, but we're going to abandon this construct in a little while.
214 return nil, nil
215 }
216 ctxType := reflect.TypeOf(tctx)
217 for method := range ctxType.Methods() {
218 method := method
219 if ignoreFuncs[method.Name] {
220 continue
221 }
222 f := goDocFunc{
223 Name: method.Name,
224 }
225
226 methodGoDoc := godoc[method.Name]
227
228 if mapping, ok := t.MethodMappings[method.Name]; ok {
229 f.Aliases = mapping.Aliases
230 f.Examples = mapping.Examples
231 f.Description = methodGoDoc.Description
232 f.Args = methodGoDoc.Args
233 }
234
235 funcs = append(funcs, f)
236 }
237
238 for i, f := range funcs {
239 if i != 0 {
240 buf.WriteString(",")
241 }
242 funcStr, err := f.toJSON()
243 if err != nil {
244 return nil, err
245 }
246 buf.Write(funcStr)
247 }
248
249 buf.WriteString("}")
250
251 return buf.Bytes(), nil
252 }
253
254 type methodGoDocInfo struct {
255 Description string
256 Args []string
257 }
258
259 var (
260 tplPackagesGoDoc map[string]map[string]methodGoDocInfo
261 tplPackagesGoDocInit sync.Once
262 )
263
264 func getGetTplPackagesGoDoc() map[string]map[string]methodGoDocInfo {
265 tplPackagesGoDocInit.Do(func() {
266 tplPackagesGoDoc = make(map[string]map[string]methodGoDocInfo)
267 pwd, err := os.Getwd()
268 if err != nil {
269 log.Fatal(err)
270 }
271
272 fset := token.NewFileSet()
273
274 // pwd will be inside one of the namespace packages during tests
275 var basePath string
276 if strings.Contains(pwd, "tpl") {
277 basePath = filepath.Join(pwd, "..")
278 } else {
279 basePath = filepath.Join(pwd, "tpl")
280 }
281
282 files, err := os.ReadDir(basePath)
283 if err != nil {
284 log.Fatal(err)
285 }
286
287 for _, fi := range files {
288 if !fi.IsDir() {
289 continue
290 }
291
292 namespaceDoc := make(map[string]methodGoDocInfo)
293 packagePath := filepath.Join(basePath, fi.Name())
294
295 astFiles, err := parseDir(fset, packagePath)
296 if err != nil {
297 log.Fatal(err)
298 }
299
300 if len(astFiles) > 0 {
301 p, err := doc.NewFromFiles(fset, astFiles, "./")
302 if err != nil {
303 log.Fatal(err)
304 }
305
306 for _, t := range p.Types {
307 if t.Name == "Namespace" {
308 for _, tt := range t.Methods {
309 var args []string
310 for _, p := range tt.Decl.Type.Params.List {
311 for _, pp := range p.Names {
312 args = append(args, pp.Name)
313 }
314 }
315
316 description := strings.TrimSpace(tt.Doc)
317 di := methodGoDocInfo{Description: description, Args: args}
318 namespaceDoc[tt.Name] = di
319 }
320 }
321 }
322 }
323
324 tplPackagesGoDoc[fi.Name()] = namespaceDoc
325 }
326 })
327
328 return tplPackagesGoDoc
329 }
330
331 func parseDir(fset *token.FileSet, dir string) ([]*ast.File, error) {
332 entries, err := os.ReadDir(dir)
333 if err != nil {
334 return nil, err
335 }
336 var files []*ast.File
337 for _, e := range entries {
338 if e.IsDir() || !strings.HasSuffix(e.Name(), ".go") {
339 continue
340 }
341 f, err := parser.ParseFile(fset, filepath.Join(dir, e.Name()), nil, parser.ParseComments)
342 if err != nil {
343 return nil, err
344 }
345 files = append(files, f)
346 }
347 return files, nil
348 }