fields.go (1546B)
1 // Copyright 2020 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 postpub
15
16 import (
17 "reflect"
18 )
19
20 const (
21 FieldNotSupported = "__field_not_supported"
22 )
23
24 func structToMapWithPlaceholders(root string, in any, createPlaceholder func(s string) string) map[string]any {
25 m := structToMap(in)
26 insertFieldPlaceholders(root, m, createPlaceholder)
27 return m
28 }
29
30 func structToMap(s any) map[string]any {
31 m := make(map[string]any)
32 t := reflect.TypeOf(s)
33
34 for i := 0; i < t.NumMethod(); i++ {
35 method := t.Method(i)
36 if method.PkgPath != "" {
37 continue
38 }
39 if method.Type.NumIn() == 1 {
40 m[method.Name] = ""
41 }
42 }
43
44 for i := 0; i < t.NumField(); i++ {
45 field := t.Field(i)
46 if field.PkgPath != "" {
47 continue
48 }
49 m[field.Name] = ""
50 }
51 return m
52 }
53
54 // insert placeholder for the templates. Do it very shallow for now.
55 func insertFieldPlaceholders(root string, m map[string]any, createPlaceholder func(s string) string) {
56 for k := range m {
57 m[k] = createPlaceholder(root + "." + k)
58 }
59 }