Debian Codegraph @

common/hmaps/maps.go

raw
1 // Copyright 2026 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 hmaps
15
16 import (
17 "fmt"
18 "strings"
19
20 "github.com/gohugoio/hugo/common/hstrings"
21 "github.com/gohugoio/hugo/common/types"
22
23 "github.com/gobwas/glob"
24 "github.com/spf13/cast"
25 )
26
27 // ToStringMapE converts in to map[string]interface{}.
28 func ToStringMapE(in any) (map[string]any, error) {
29 switch vv := in.(type) {
30 case Params:
31 return vv, nil
32 case map[string]string:
33 m := map[string]any{}
34 for k, v := range vv {
35 m[k] = v
36 }
37 return m, nil
38
39 default:
40 return cast.ToStringMapE(in)
41 }
42 }
43
44 // ToParamsAndPrepare converts in to Params and prepares it for use.
45 // If in is nil, an empty map is returned.
46 // See PrepareParams.
47 func ToParamsAndPrepare(in any) (Params, error) {
48 if types.IsNil(in) {
49 return Params{}, nil
50 }
51 m, err := ToStringMapE(in)
52 if err != nil {
53 return nil, err
54 }
55 PrepareParams(m)
56 return m, nil
57 }
58
59 // MustToParamsAndPrepare calls ToParamsAndPrepare and panics if it fails.
60 func MustToParamsAndPrepare(in any) Params {
61 p, err := ToParamsAndPrepare(in)
62 if err != nil {
63 panic(fmt.Sprintf("cannot convert %T to maps.Params: %s", in, err))
64 }
65 return p
66 }
67
68 // ToStringMap converts in to map[string]interface{}.
69 func ToStringMap(in any) map[string]any {
70 m, _ := ToStringMapE(in)
71 return m
72 }
73
74 // ToStringMapStringE converts in to map[string]string.
75 func ToStringMapStringE(in any) (map[string]string, error) {
76 m, err := ToStringMapE(in)
77 if err != nil {
78 return nil, err
79 }
80 return cast.ToStringMapStringE(m)
81 }
82
83 // ToStringMapString converts in to map[string]string.
84 func ToStringMapString(in any) map[string]string {
85 m, _ := ToStringMapStringE(in)
86 return m
87 }
88
89 // ToStringMapBool converts in to bool.
90 func ToStringMapBool(in any) map[string]bool {
91 m, _ := ToStringMapE(in)
92 return cast.ToStringMapBool(m)
93 }
94
95 // ToSliceStringMap converts in to []map[string]interface{}.
96 func ToSliceStringMap(in any) ([]map[string]any, error) {
97 switch v := in.(type) {
98 case []map[string]any:
99 return v, nil
100 case Params:
101 return []map[string]any{v}, nil
102 case map[string]any:
103 return []map[string]any{v}, nil
104 case []any:
105 var s []map[string]any
106 for _, entry := range v {
107 if vv, ok := entry.(map[string]any); ok {
108 s = append(s, vv)
109 }
110 }
111 return s, nil
112 default:
113 return nil, fmt.Errorf("unable to cast %#v of type %T to []map[string]interface{}", in, in)
114 }
115 }
116
117 // LookupEqualFold finds key in m with case insensitive equality checks.
118 func LookupEqualFold[T any | string](m map[string]T, key string) (T, string, bool) {
119 if v, found := m[key]; found {
120 return v, key, true
121 }
122 for k, v := range m {
123 if strings.EqualFold(k, key) {
124 return v, k, true
125 }
126 }
127 var s T
128 return s, "", false
129 }
130
131 // MergeShallow merges src into dst, but only if the key does not already exist in dst.
132 // The keys are compared case insensitively.
133 func MergeShallow(dst, src map[string]any) {
134 for k, v := range src {
135 found := false
136 for dk := range dst {
137 if strings.EqualFold(dk, k) {
138 found = true
139 break
140 }
141 }
142 if !found {
143 dst[k] = v
144 }
145 }
146 }
147
148 type keyRename struct {
149 pattern hstrings.Matcher
150 newKey string
151 }
152
153 // KeyRenamer supports renaming of keys in a map.
154 type KeyRenamer struct {
155 renames []keyRename
156 }
157
158 // NewKeyRenamer creates a new KeyRenamer given a list of pattern and new key
159 // value pairs.
160 func NewKeyRenamer(patternKeys ...string) (KeyRenamer, error) {
161 var renames []keyRename
162 for i := 0; i < len(patternKeys); i += 2 {
163 g, err := glob.Compile(strings.ToLower(patternKeys[i]), '/')
164 if err != nil {
165 return KeyRenamer{}, err
166 }
167 renames = append(renames, keyRename{pattern: g, newKey: patternKeys[i+1]})
168 }
169
170 return KeyRenamer{renames: renames}, nil
171 }
172
173 func (r KeyRenamer) getNewKey(keyPath string) string {
174 for _, matcher := range r.renames {
175 if matcher.pattern.Match(keyPath) {
176 return matcher.newKey
177 }
178 }
179
180 return ""
181 }
182
183 // Rename renames the keys in the given map according
184 // to the patterns in the current KeyRenamer.
185 func (r KeyRenamer) Rename(m map[string]any) {
186 r.renamePath("", m)
187 }
188
189 func (KeyRenamer) keyPath(k1, k2 string) string {
190 k1, k2 = strings.ToLower(k1), strings.ToLower(k2)
191 if k1 == "" {
192 return k2
193 }
194 return k1 + "/" + k2
195 }
196
197 func (r KeyRenamer) renamePath(parentKeyPath string, m map[string]any) {
198 for k, v := range m {
199 keyPath := r.keyPath(parentKeyPath, k)
200 switch vv := v.(type) {
201 case map[any]any:
202 r.renamePath(keyPath, cast.ToStringMap(vv))
203 case map[string]any:
204 r.renamePath(keyPath, vv)
205 }
206
207 newKey := r.getNewKey(keyPath)
208
209 if newKey != "" {
210 delete(m, k)
211 m[newKey] = v
212 }
213 }
214 }
215
216 // ConvertFloat64WithNoDecimalsToInt converts float64 values with no decimals to int recursively.
217 func ConvertFloat64WithNoDecimalsToInt(m map[string]any) {
218 for k, v := range m {
219 switch vv := v.(type) {
220 case float64:
221 if v == float64(int64(vv)) {
222 m[k] = int64(vv)
223 }
224 case map[string]any:
225 ConvertFloat64WithNoDecimalsToInt(vv)
226 case []any:
227 for i, vvv := range vv {
228 switch vvvv := vvv.(type) {
229 case float64:
230 if vvv == float64(int64(vvvv)) {
231 vv[i] = int64(vvvv)
232 }
233 case map[string]any:
234 ConvertFloat64WithNoDecimalsToInt(vvvv)
235 }
236 }
237 }
238 }
239 }